<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\ProductInModel;
use App\Models\ItemModel;
use App\Models\SupplierModel;
use App\Models\GudangModel;

class ProductIn extends BaseController
{
    protected $productInModel;

    public function __construct()
    {
        $this->productInModel = new ProductInModel();

        
    }

    public function index()
    {
        $data = [
            'title' => 'Stok Masuk',
            'data'  => $this->productInModel->getJoinAll(),
        ];
        return view('product_in/index', $data);
    }

    public function create()
    {
        $itemModel     = new ItemModel();
        $supplierModel = new SupplierModel();
        $gudangModel   = new GudangModel();

        $data = [
            'title'     => 'Tambah Stok Masuk',
            'items'     => $itemModel->findAll(),
            'suppliers' => $supplierModel->findAll(),
            'warehouses'=> $gudangModel->findAll(),
        ];
        return view('product_in/create', $data);
    }

    public function save()
{
    $itemId   = $this->request->getPost('item_id');
    $qtyIn    = (int) $this->request->getPost('qty');
    $tanggal  = $this->request->getPost('tanggal_masuk') ?? date('Y-m-d');
    $tanggalFormat = date('dm y', strtotime($tanggal));
    $prefix   = 'INV-' . str_replace(' ', '', $tanggalFormat); // Contoh: INV-110725

    // Cari kode terakhir dengan prefix yang sama
    $last = $this->productInModel
        ->like('kode', $prefix, 'after')
        ->orderBy('kode', 'DESC')
        ->first();

    $nextNumber = 1;
    if ($last && preg_match('/-(\d+)$/', $last['kode'], $match)) {
        $nextNumber = (int)$match[1] + 1;
    }

    $kode = $prefix . '-' . str_pad($nextNumber, 3, '0', STR_PAD_LEFT);

    // Data untuk disimpan
    $data = [
        'kode'          => $kode,
        'item_id'       => $itemId,
        'barcode'       => $this->request->getPost('barcode'),
        'supplier_id'   => $this->request->getPost('supplier_id'),
        'id_gudang'     => $this->request->getPost('id_gudang'), // pastikan sesuai form
        'qty'           => $qtyIn,
        'tanggal_masuk' => $tanggal,
        'created_by'    => session()->get('user_id') ?? null
    ];

    // Simpan ke DB
    $this->productInModel->save($data);

    // Update stok barang
    $itemModel = new \App\Models\ItemModel();
    $item      = $itemModel->find($itemId);
    if ($item) {
        $newStock = $item['stok'] + $qtyIn;
        $itemModel->update($itemId, ['stok' => $newStock]);
    }

    return redirect()->to(base_url('admin/product_in'))->with('success', 'Stok berhasil ditambahkan.');
}


    public function edit($id)
{
    $dataMasuk = $this->productInModel
        ->join('items', 'items.id = product_in.item_id', 'left')
        ->select('product_in.*, items.nama as nama_item')
        ->where('product_in.id', $id)
        ->get()
        ->getRowArray();

    if (!$dataMasuk) {
        return redirect()->back()->with('error', 'Data tidak ditemukan');
    }

    $itemModel     = new ItemModel();
    $supplierModel = new SupplierModel();
    $gudangModel   = new GudangModel();

    $data = [
        'title'      => 'Edit Stok Masuk',
        'data'       => $dataMasuk,
        'items'      => $itemModel->findAll(),
        'suppliers'  => $supplierModel->findAll(),
        'warehouses' => $gudangModel->findAll(),
    ];

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


    public function update($id)
    {
        $oldData = $this->productInModel->find($id);
        if (!$oldData) {
            return redirect()->back()->with('error', 'Data tidak ditemukan');
        }

        $itemId     = $this->request->getPost('item_id');
        $newQty     = (int)$this->request->getPost('qty');
        $selisih    = $newQty - (int)$oldData['qty'];

        $data = [
            'id'            => $id,
            'item_id'       => $itemId,
            'barcode'       => $this->request->getPost('barcode'),
            'supplier_id'   => $this->request->getPost('supplier_id'),
            'id_gudang'     => $this->request->getPost('id_gudang'),
            'qty'           => $newQty,
            'tanggal_masuk' => $this->request->getPost('tanggal_masuk'),
        ];

        $this->productInModel->save($data);

        $itemModel = new ItemModel();
        $item      = $itemModel->find($itemId);
        if ($item) {
            $newStock = $item['stok'] + $selisih;
            $itemModel->update($itemId, ['stok' => $newStock]);
        }

        return redirect()->to(base_url('admin/product_in'))->with('success', 'Data berhasil diubah.');
    }

    public function delete($id)
    {
        $data = $this->productInModel->find($id);
        if ($data) {
            $itemModel = new ItemModel();
            $item      = $itemModel->find($data['item_id']);
            if ($item) {
                $updatedStock = max(0, $item['stok'] - $data['qty']);
                $itemModel->update($data['item_id'], ['stok' => $updatedStock]);
            }
            $this->productInModel->delete($id);
        }

        return redirect()->to(base_url('admin/product_in'))->with('success', 'Data berhasil dihapus.');
    }

    public function detail($id)
    {
        $detail = $this->productInModel->getJoinById($id);
        if (!$detail) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound("Data tidak ditemukan");
        }

        $data = [
            'title'  => 'Detail Stok Masuk',
            'detail' => $detail
        ];

        return view('product_in/detail', $data);
    }
}
