<?php
namespace App\Controllers;

use App\Models\ItemModel;
use App\Models\CategoryModel;
use App\Models\UnitModel;
use App\Models\GudangModel;
use App\Models\ProductOutModel;
use CodeIgniter\Controller;

class Item extends Controller
{
    protected $itemModel, $categoryModel, $unitModel, $gudangModel, $productOutModel;

    public function __construct()
    {
        $this->itemModel       = new ItemModel();
        $this->categoryModel   = new CategoryModel();
        $this->unitModel       = new UnitModel();
        $this->gudangModel     = new GudangModel();
        $this->productOutModel = new ProductOutModel();

        $session = session();
    if (!$session->get('logged_in') || $session->get('role') === 'kasir') {
        redirect()->to(base_url('admin/dashboard'))->send();
        exit;
    }
    }

    public function index()
{
    $keyword = $this->request->getGet('keyword');
    $page    = (int) $this->request->getGet('page') ?: 1;
    $perPage = 10;
    $offset  = ($page - 1) * $perPage;

    $items      = $this->itemModel->getPaginatedItems($perPage, $offset, $keyword);
    $totalItems = $this->itemModel->countItems($keyword);
    $totalPages = ceil($totalItems / $perPage);

    $data = [
        'title'       => 'Data Item Produk',
        'items'       => $items,
        'keyword'     => $keyword,
        'totalItems'  => $totalItems,
        'totalPages'  => $totalPages,
        'currentPage' => $page,
        'perPage'     => $perPage
    ];

    return view('item/index', $data);
}



    public function create()
    {
        $data = [
            'title'      => 'Tambah Item',
            'categories' => $this->categoryModel->findAll(),
            'units'      => $this->unitModel->findAll(),
            'gudangs'    => $this->gudangModel->findAll()
        ];
        return view('item/create', $data);
    }

    public function save()
    {
        $this->itemModel->save([
            'barcode'     => $this->request->getPost('barcode'),
            'nama'        => $this->request->getPost('nama'),
            'id_category' => $this->request->getPost('id_category'),
            'id_unit'     => $this->request->getPost('id_unit'),
            'harga'       => $this->request->getPost('harga'),
            'stok'        => $this->request->getPost('stok'),
            'id_gudang'   => $this->request->getPost('id_gudang'),
            'diskon'      => $this->request->getPost('diskon') ?? 0,
            'total_harga' => $this->request->getPost('total_harga'),
            'is_active'   => 1
        ]);
        return redirect()->to('/admin/item')->with('success', 'Item berhasil ditambahkan.');
    }

    public function edit($id)
    {
        $item = $this->itemModel->find($id);

        if (!$item) {
            throw new \CodeIgniter\Exceptions\PageNotFoundException('Data item tidak ditemukan');
        }

        $data = [
            'title'      => 'Edit Item',
            'item'       => $item,
            'categories' => $this->categoryModel->findAll(),
            'units'      => $this->unitModel->findAll(),
            'gudangs'    => $this->gudangModel->findAll()
        ];

        return view('item/edit', $data);
    }

    public function update($id)
    {
        $this->itemModel->update($id, [
            'barcode'     => $this->request->getPost('barcode'),
            'nama'        => $this->request->getPost('nama'),
            'id_category' => $this->request->getPost('id_category'),
            'id_unit'     => $this->request->getPost('id_unit'),
            'harga'       => $this->request->getPost('harga'),
            'stok'        => $this->request->getPost('stok'),
            'id_gudang'   => $this->request->getPost('id_gudang'),
            'diskon'      => $this->request->getPost('diskon') ?? 0,
            'total_harga' => $this->request->getPost('total_harga')
        ]);

        return redirect()->to('/admin/item')->with('success', 'Data item berhasil diupdate.');
    }

    public function delete($id)
    {
        $related = $this->productOutModel->where('item_id', $id)->countAllResults();

        if ($related > 0) {
            $this->itemModel->update($id, ['is_active' => 0]);
            return redirect()->to('/admin/item')->with('warning', 'Item disembunyikan karena masih memiliki riwayat transaksi.');
        } else {
            $this->itemModel->softDelete($id);
            return redirect()->to('/admin/item')->with('success', 'Item berhasil dihapus.');
        }
    }
    public function disable($id)
{
    $this->itemModel->update($id, ['is_active' => 0]);
    return redirect()->to('/admin/item')->with('warning', 'Item dinonaktifkan.');
}

public function enable($id)
{
    $this->itemModel->update($id, ['is_active' => 1]);
    return redirect()->to('/admin/item')->with('warning', 'Item diaktifkan kembali.');
}

public function search()
{
    $keyword = $this->request->getGet('keyword');
    $items = $this->itemModel->searchItems($keyword);

    return view('item/table', ['items' => $items]);
}

}
