<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\ProductOutModel;
use App\Models\ItemModel;
use App\Models\GudangModel;

class ProductOut extends BaseController
{
    protected $productOutModel;
    protected $gudangModel;

    public function __construct()
    {
        $this->productOutModel = new ProductOutModel();
        $this->gudangModel     = new GudangModel();

        
    }

    public function index()
    {
        $itemModel = new ItemModel();

        $data = [
            'title'    => 'Produk Keluar',
            'kode'     => $this->generateKode(),
            'data'     => $this->productOutModel->getJoinAll(),
            'items'    => $itemModel->select('items.*, gudang.nama as nama_gudang')
                                    ->join('gudang', 'gudang.id = items.id_gudang', 'left')
                                    ->findAll(),
            'gudangs'  => $this->gudangModel->findAll(),
        ];

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

    public function save()
    {
        $item_id    = $this->request->getPost('item_id');
        $barcode    = $this->request->getPost('barcode');
        $gudang_id  = $this->request->getPost('gudang_id');
        $qty        = (int) $this->request->getPost('qty');
        $tanggal    = $this->request->getPost('tanggal_keluar') ?? date('Y-m-d H:i:s');
        $keterangan = $this->request->getPost('keterangan');


        $itemModel = new ItemModel();
        $item      = $itemModel->find($item_id);

        if (!$item) {
            return redirect()->back()->with('error', 'Barang tidak ditemukan.');
        }

        if (($item['stok'] - $qty) < 0) {
            return redirect()->back()->with('error', 'Stok barang tidak mencukupi.');
        }

        $kode = $this->generateKode($tanggal);

        $this->productOutModel->save([
            'kode'           => $kode,
            'item_id'        => $item_id,
            'barcode'        => $barcode,
            'gudang_id'      => $gudang_id,
            'qty'            => $qty,
            'tanggal_keluar' => $tanggal,
            'keterangan'     => $keterangan,
            'created_by'     => session()->get('user_id'),
        ]);

        $itemModel->update($item_id, ['stok' => $item['stok'] - $qty]);

        return redirect()->to(base_url('admin/product_out'))->with('success', 'Produk keluar berhasil disimpan.');
    }

    public function delete($id)
    {
        $this->productOutModel->delete($id);
        return redirect()->to(base_url('admin/product_out'))->with('success', 'Data berhasil dihapus.');
    }

    private function generateKode($tanggal = null)
    {
        $tanggalFormat = date('Ymd', strtotime($tanggal ?? date('Y-m-d')));
        $prefix = 'OUT' . $tanggalFormat;

        $last = $this->productOutModel
            ->like('kode', $prefix, 'after')
            ->orderBy('kode', 'DESC')
            ->first();

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

        return $prefix . '-' . str_pad($nextNumber, 3, '0', STR_PAD_LEFT);
    }

    public function detail($kode = null)
{
    if (!$kode) {
        return 'Kode transaksi tidak tersedia.';
    }

    $model = new ProductOutModel();
    $data['detail'] = $model->getDetailByKode($kode);

    if (!$data['detail']) {
        return 'Data tidak ditemukan.';
    }

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

public function edit($kode)
{
    $product = $this->productOutModel->where('kode', $kode)->first();

    if (!$product) {
        return redirect()->to(base_url('admin/product_out'))->with('error', 'Data tidak ditemukan.');
    }

    $itemModel   = new \App\Models\ItemModel();
    $gudangModel = new \App\Models\GudangModel();

    $data = [
        'title'     => 'Edit Produk Keluar',
        'product'   => $product,
        'items'     => $itemModel->findAll(),
        'gudangs'   => $gudangModel->findAll(),
    ];

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

public function update($kode)
{
    $product = $this->productOutModel->where('kode', $kode)->first();

    if (!$product) {
        return redirect()->to(base_url('admin/product_out'))->with('error', 'Data tidak ditemukan.');
    }

    $data = [
        'item_id'        => $this->request->getPost('item_id'),
        'barcode'        => $this->request->getPost('barcode'),
        'gudang_id'      => $this->request->getPost('gudang_id'),
        'qty'            => $this->request->getPost('qty'),
        'tanggal_keluar' => $this->request->getPost('tanggal_keluar'),
        'keterangan'     => $this->request->getPost('keterangan'),
        'updated_at'     => date('Y-m-d H:i:s'),
        'created_by'     => session()->get('user_id'),
    ];

    $this->productOutModel->where('kode', $kode)->set($data)->update();

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


}
