<?php

namespace App\Controllers;

use App\Models\StokBatchModel;
use App\Models\RiwayatStokModel;
use CodeIgniter\RESTful\ResourceController;

class Stok extends ResourceController
{
    protected $format = 'json';

    // 1. MODUL MONITORING (UNTUK DASHBOARD FLUTTER)
    public function monitoring()
    {
        $db = \Config\Database::connect();
        $sql = "SELECT b.*, p.nama_produk, p.satuan,
                DATEDIFF(b.tgl_kadaluwarsa, CURDATE()) as sisa_hari,
                CASE 
                    WHEN DATEDIFF(b.tgl_kadaluwarsa, CURDATE()) <= 0 THEN 'merah'
                    WHEN DATEDIFF(b.tgl_kadaluwarsa, CURDATE()) <= 30 THEN 'kuning'
                    ELSE 'hijau'
                END as status_warna
                FROM stok_batch b
                JOIN produk p ON b.id_produk = p.id_produk
                WHERE b.jumlah_stok > 0
                ORDER BY b.tgl_kadaluwarsa ASC";
        
        $data = $db->query($sql)->getResultArray();
        return $this->respond(['status' => 200, 'data' => $data]);
    }

    // 2. INPUT STOK MASUK (FIXED)
    public function masuk()
    {
        $db = \Config\Database::connect();
        $json = $this->request->getJSON();

        // Validasi data dasar agar tidak Error 500 jika data kosong
        if (!isset($json->id_produk) || !isset($json->jumlah_stok)) {
            return $this->fail('Data tidak lengkap', 400);
        }

        $db->transStart(); // Mulai transaksi database

        // Gunakan nama key yang dikirim dari Flutter: jumlah_stok & harga_beli_satuan
        $dataBatch = [
            'id_produk'         => $json->id_produk,
            'jumlah_stok'       => $json->jumlah_stok,
            'harga_beli_satuan' => $json->harga_beli_satuan,
            'tgl_kadaluwarsa'   => $json->tgl_kadaluwarsa
        ];

        $db->table('stok_batch')->insert($dataBatch);
        $idBatch = $db->insertID();

        // Catat di riwayat_stok
        $db->table('riwayat_stok')->insert([
            'id_batch'       => $idBatch,
            'id_pengguna'    => $json->id_pengguna,
            'tipe_transaksi' => 'masuk',
            'jumlah'         => $json->jumlah_stok,
            'keterangan'     => 'Input stok masuk dari mobile'
        ]);

        $db->transComplete(); // Selesai transaksi

        if ($db->transStatus() === false) {
            return $this->fail('Gagal menyimpan ke database');
        }

        return $this->respondCreated(['status' => 201, 'message' => 'Stok batch berhasil dicatat']);
    }

    // 3. LOGIKA EMAS: STOK KELUAR (FEFO FIXED)
    public function keluar()
    {
        $db = \Config\Database::connect();
        $json = $this->request->getJSON();
        
        $id_produk = $json->id_produk;
        $jumlah_diminta = $json->jumlah_stok; // Samakan key dengan Flutter
        $id_user = $json->id_pengguna;

        // Cek stok total dulu (opsional tapi bagus untuk user experience)
        $cekStok = $db->query("SELECT SUM(jumlah_stok) as total FROM stok_batch WHERE id_produk = $id_produk")->getRow();
        if ($cekStok->total < $jumlah_diminta) {
            return $this->fail('Stok total tidak mencukupi');
        }

        $db->transStart();

        // Ambil batch yang expired paling dekat
        $batches = $db->query("SELECT * FROM stok_batch 
                               WHERE id_produk = $id_produk AND jumlah_stok > 0 
                               ORDER BY tgl_kadaluwarsa ASC")->getResultArray();

        $sisa_perlu_dikurangi = $jumlah_diminta;

        foreach ($batches as $batch) {
            if ($sisa_perlu_dikurangi <= 0) break;

            $stok_sekarang = $batch['jumlah_stok'];
            $id_batch = $batch['id_batch'];

            if ($stok_sekarang >= $sisa_perlu_dikurangi) {
                $db->query("UPDATE stok_batch SET jumlah_stok = jumlah_stok - $sisa_perlu_dikurangi WHERE id_batch = $id_batch");
                $db->table('riwayat_stok')->insert([
                    'id_batch' => $id_batch, 
                    'id_pengguna' => $id_user, 
                    'tipe_transaksi' => 'keluar', 
                    'jumlah' => $sisa_perlu_dikurangi
                ]);
                $sisa_perlu_dikurangi = 0;
            } else {
                $db->query("UPDATE stok_batch SET jumlah_stok = 0 WHERE id_batch = $id_batch");
                $db->table('riwayat_stok')->insert([
                    'id_batch' => $id_batch, 
                    'id_pengguna' => $id_user, 
                    'tipe_transaksi' => 'keluar', 
                    'jumlah' => $stok_sekarang
                ]);
                $sisa_perlu_dikurangi -= $stok_sekarang;
            }
        }

        $db->transComplete();

        if ($db->transStatus() === false) {
            return $this->fail('Gagal memproses FEFO');
        }

        return $this->respond(['status' => 200, 'message' => 'Stok berhasil dikurangi (FEFO)']);
    }
    
    // Tambahkan di app/Controllers/Stok.php

public function laporan()
{
    $db = \Config\Database::connect();

    // 1. Hitung Total Aset (Stok yang masih ada x Harga Beli)
    $aset = $db->query("SELECT SUM(jumlah_stok * harga_beli_satuan) as total FROM stok_batch WHERE jumlah_stok > 0")->getRow();

    // 2. Hitung Potensi Kerugian (Barang Expired yang belum laku)
    $kerugian = $db->query("SELECT SUM(jumlah_stok * harga_beli_satuan) as total FROM stok_batch WHERE tgl_kadaluwarsa <= CURDATE() AND jumlah_stok > 0")->getRow();

    // 3. Ringkasan Status Barang
    $summary = $db->query("SELECT 
                COUNT(CASE WHEN DATEDIFF(tgl_kadaluwarsa, CURDATE()) <= 0 THEN 1 END) as expired,
                COUNT(CASE WHEN DATEDIFF(tgl_kadaluwarsa, CURDATE()) BETWEEN 1 AND 30 THEN 1 END) as warning,
                COUNT(CASE WHEN DATEDIFF(tgl_kadaluwarsa, CURDATE()) > 30 THEN 1 END) as aman
                FROM stok_batch WHERE jumlah_stok > 0")->getRow();

    return $this->respond([
        'status' => 200,
        'data' => [
            'total_aset' => (float)($aset->total ?? 0),
            'total_kerugian' => (float)($kerugian->total ?? 0),
            'ringkasan' => $summary
        ]
    ]);
}
}