<?php

namespace App\Controllers;

use App\Models\TransaksiModel;
use App\Models\PetaniModel;
use App\Models\PupukModel;
use App\Models\KeuanganModel;

class Transaksi extends BaseController
{
    protected $transaksiM;
    protected $db;

    public function __construct()
    {
        $this->transaksiM = new TransaksiModel();
        $this->db = \Config\Database::connect();
    }

    public function index()
    {
        $petaniM = new PetaniModel();
        $pupukM = new PupukModel();

        $data = [
            'title'     => 'Transaksi Penebusan Pupuk',
            'transaksi' => $this->transaksiM->orderBy('tanggal_transaksi', 'DESC')->findAll(),
            'petani'    => $petaniM->findAll(),
            'pupuk'     => $pupukM->findAll()
        ];
        return view('transaksi/index', $data);
    }

    public function proses_penebusan()
    {
        $id_petani = $this->request->getPost('id_petani');
        $id_pupuk = $this->request->getPost('id_pupuk');
        $jumlah_beli = $this->request->getPost('jumlah_beli');
        $tahun_ini = date('Y');

        // 1. VALIDASI: Cek Sisa Kuota Petani
        $builderAlokasi = $this->db->table('alokasi_kuota');
        $kuota = $builderAlokasi->where(['id_petani' => $id_petani, 'id_pupuk' => $id_pupuk, 'tahun_tanam' => $tahun_ini])->get()->getRowArray();

        if (!$kuota || ($kuota['jatah_kg'] - $kuota['terpakai_kg']) < $jumlah_beli) {
            return redirect()->to('/transaksi')->with('error', 'Transaksi Ditolak! Kuota petani tidak mencukupi atau belum diatur.');
        }

        // 2. VALIDASI: Cek Stok Gudang
        $pupukM = new PupukModel();
        $dataPupuk = $pupukM->find($id_pupuk);

        if ($dataPupuk['stok_global'] < $jumlah_beli) {
            return redirect()->to('/transaksi')->with('error', 'Transaksi Ditolak! Stok pupuk di gudang tidak mencukupi.');
        }

        // HITUNG TOTAL BAYAR
        $total_bayar = $jumlah_beli * $dataPupuk['harga_het'];
        $no_invoice = 'INV-' . date('YmdHis');

        // ========================================================
        // MULAI DATABASE TRANSACTION (TRIGGER OTOMATIS)
        // ========================================================
        $this->db->transStart();

        // A. Insert ke Tabel Transaksi
        $this->transaksiM->insert([
            'no_invoice'  => $no_invoice,
            'id_petani'   => $id_petani,
            'id_pupuk'    => $id_pupuk,
            'jumlah_beli' => $jumlah_beli,
            'total_bayar' => $total_bayar
        ]);
        $id_transaksi_baru = $this->transaksiM->getInsertID();

        // B. Kurangi Stok Pupuk (Otomatis)
        $this->db->table('pupuk')
            ->where('id_pupuk', $id_pupuk)
            ->set('stok_global', 'stok_global - ' . (float)$jumlah_beli, false)
            ->update();

        // C. Update Kuota Terpakai (Otomatis)
        $this->db->table('alokasi_kuota')
            ->where('id_alokasi', $kuota['id_alokasi'])
            ->set('terpakai_kg', 'terpakai_kg + ' . (float)$jumlah_beli, false)
            ->update();

        // D. Catat Uang Masuk ke Keuangan (Otomatis)
        $keuanganM = new KeuanganModel();
        $saldoTerakhir = $keuanganM->orderBy('id_kas', 'DESC')->first()['saldo_akhir'] ?? 0;

        $keuanganM->insert([
            'tanggal'     => date('Y-m-d'),
            'keterangan'  => "Penebusan Pupuk ($no_invoice)",
            'jenis'       => 'masuk',
            'kategori'    => 'penebusan',
            'nominal'     => $total_bayar,
            'saldo_akhir' => $saldoTerakhir + $total_bayar,
            'id_referensi_transaksi' => $id_transaksi_baru
        ]);

        // SELESAI TRANSACTION
        $this->db->transComplete();
        // ========================================================

        if ($this->db->transStatus() === false) {
            return redirect()->to('/transaksi')->with('error', 'Terjadi kesalahan sistem saat memproses data.');
        }

        return redirect()->to('/transaksi')->with('success', 'Transaksi berhasil! Stok telah dikurangi dan kas bertambah sebesar <b>Rp ' . number_format($total_bayar, 0, ',', '.') . '</b>.');
    }
}
