<?php 
namespace App\Controllers\Owner; 

use App\Controllers\BaseController; 
use App\Models\PurchaseModel; 
use App\Models\PurchaseItemModel; 
use App\Models\ProductModel; 
use App\Models\SupplierModel; 

class Material extends BaseController 
{ 
    protected $purchase, $purchaseItem, $product, $supplier; 

    public function __construct() 
    { 
        helper(['form', 'url']); 
        $this->purchase     = new PurchaseModel(); 
        $this->purchaseItem = new PurchaseItemModel(); 
        $this->product      = new ProductModel(); 
        $this->supplier     = new SupplierModel(); 
    } 

    public function index() 
    { 
        // Menggabungkan data untuk list material 
        $items = $this->purchaseItem
            ->select('purchase_items.*, purchases.tanggal_beli, purchases.nomor_purchase, products.nama_product, suppliers.nama_supplier')
            ->join('purchases', 'purchases.id_purchase = purchase_items.id_purchase', 'left')
            ->join('products', 'products.id_product = purchase_items.id_product', 'left')
            ->join('suppliers', 'suppliers.id_supplier = purchases.id_supplier', 'left')
            ->orderBy('purchases.tanggal_beli', 'DESC')
            ->findAll(); 

        return view('owner/material/index', [ 
            'title' => 'Daftar Pembelian Material', 
            'items' => $items 
        ]); 
    } 

    public function create() 
    { 
        $db = \Config\Database::connect(); 
        // Mengambil data dari tabel orders untuk dropdown Customer Name 
        $orders = $db->table('orders')->get()->getResultArray(); 
        $products = $this->product->findAll(); 
        $suppliers = $this->supplier->findAll(); 

        return view('owner/material/create', [ 
            'title'     => 'Tambah Belanja Material Mentah', 
            'orders'    => $orders, 
            'products'  => $products, 
            'suppliers' => $suppliers 
        ]); 
    } 

    public function store() 
    { 
        // Validasi Dasar 
        if (!$this->validate([ 
            'nama_product'   => 'required', 
            'nama_supplier'  => 'required', 
            'qty'            => 'required|numeric', 
            'harga_beli'     => 'required|numeric' 
        ])) { 
            return redirect()->back()->withInput()->with('error', 'Semua kolom wajib diisi dengan benar.'); 
        } 

        $db = \Config\Database::connect(); 
        // Memulai Transaksi Database (Mencegah data tersimpan setengah jalan jika error) 
        $db->transStart(); 

        // 1. Logika Produk: Cari atau Buat Baru 
        $namaProduk = $this->request->getPost('nama_product'); 
        $existingProduct = $this->product->where('nama_product', $namaProduk)->first(); 
        if ($existingProduct) { 
            $id_product = $existingProduct['id_product']; 
        } else { 
            $id_product = $this->product->insert([ 
                'nama_product' => $namaProduk, 
                'status'       => 'active' 
            ]); 
        } 

        // 2. Logika Supplier: Cari atau Buat Baru (DIPERBAIKI) 
        $namaSupplier = $this->request->getPost('nama_supplier'); 
        $existingSupplier = $this->supplier->where('nama_supplier', $namaSupplier)->first(); 
        if ($existingSupplier) { 
            $id_supplier = $existingSupplier['id_supplier']; 
        } else { 
            $id_supplier = $this->supplier->insert([ 
                'nama_supplier' => $namaSupplier, 
                'kontak'        => '-', 
                'alamat'        => '-' 
            ]); 
        } 

        // 3. Simpan Header Purchase (Menggunakan id_supplier yang sudah didapat) 
        $this->purchase->insert([ 
            "nomor_purchase" => $this->request->getPost("nomor_purchase"), 
            "id_supplier"    => $id_supplier, 
            "tanggal_beli"   => date('Y-m-d'), 
            "total_biaya"    => (float) $this->request->getPost("total_biaya") 
        ]); 
        $id_purchase = $this->purchase->getInsertID(); 

        // 4. Simpan Item Purchase 
        $this->purchaseItem->insert([ 
            "id_purchase" => $id_purchase, 
            "id_product"  => $id_product, 
            "qty"         => (float) $this->request->getPost("qty"), 
            "harga_beli"  => (float) $this->request->getPost("harga_beli") 
        ]); 

        // Selesaikan Transaksi Database 
        $db->transComplete(); 

        // Cek apakah transaksi database berhasil secara keseluruhan 
        if ($db->transStatus() === FALSE) { 
            return redirect()->back()->withInput()->with("error", "Gagal menyimpan transaksi. Terjadi kesalahan pada database."); 
        } 

        return redirect()->to("/owner/material")->with("success", "Data berhasil disimpan!"); 
    } 

    public function edit($id) 
    { 
        $item = $this->purchaseItem->find($id); 
        if (!$item) return redirect()->to('/owner/material')->with('error', 'Data tidak ditemukan'); 

        $purchase = $this->purchase->find($item['id_purchase']); 
        $product = $this->product->find($item['id_product']); 
        $supplier = $this->supplier->find($purchase['id_supplier'] ?? 0); 

        return view('owner/material/edit', [ 
            'title'    => 'Edit Pembelian Material', 
            'item'     => $item, 
            'purchase' => $purchase, 
            'product'  => $product, 
            'supplier' => $supplier 
        ]); 
    } 

    public function update($id) 
    { 
        $item = $this->purchaseItem->find($id); 
        if (!$item) return redirect()->to('/owner/material')->with('error', 'Data tidak ditemukan'); 

        $purchase = $this->purchase->find($item['id_purchase']); 
        $db = \Config\Database::connect(); 

        // Memulai Transaksi Database karena kita memperbarui/menambah ke banyak tabel 
        $db->transStart(); 

        // 1. Handle Product Manual Input 
        $namaProduct = $this->request->getPost('nama_product'); 
        $product = $this->product->where('nama_product', $namaProduct)->first(); 
        $id_product = $product ? $product['id_product'] : $this->product->insert([ 
            'nama_product' => $namaProduct, 
            'status'       => 'active' 
        ]); 

        // 2. Handle Supplier Manual Input 
        $namaSupplier = $this->request->getPost('nama_supplier'); 
        $supplier = $this->supplier->where('nama_supplier', $namaSupplier)->first(); 
        $id_supplier = $supplier ? $supplier['id_supplier'] : $this->supplier->insert([ 
            'nama_supplier' => $namaSupplier, 
            'kontak' => '-', 
            'alamat' => '-' 
        ]); 

        // 3. Update Tables 
        $this->purchase->update($purchase['id_purchase'], [ 
            'id_supplier'  => $id_supplier, 
            'tanggal_beli' => $this->request->getPost('tanggal_beli'), 
            'total_biaya'  => (float) $this->request->getPost('total_biaya') 
        ]); 
        $this->purchaseItem->update($id, [ 
            'id_product' => $id_product, 
            'qty'        => (float) $this->request->getPost('qty'), 
            'harga_beli' => (float) $this->request->getPost('harga_beli') 
        ]); 

        // Selesaikan Transaksi Database 
        $db->transComplete(); 

        // Cek jika ada yang gagal di tengah proses 
        if ($db->transStatus() === FALSE) { 
            return redirect()->back()->withInput()->with("error", "Gagal memperbarui data. Terjadi kesalahan sistem."); 
        } 
        return redirect()->to("/owner/material")->with("success", "Data berhasil diperbarui!"); 
    } 

    // ---------------------------------------------------------
    // METODE DELETE BARU DITAMBAHKAN DI SINI
    // ---------------------------------------------------------
    public function delete($id)
    {
        // 1. Cari data item berdasarkan ID yang dikirim dari URL
        $item = $this->purchaseItem->find($id);

        if (!$item) {
            return redirect()->to('/owner/material')->with('error', 'Data gagal dihapus: Data tidak ditemukan.');
        }

        $id_purchase = $item['id_purchase'];
        $db = \Config\Database::connect();
        
        $db->transStart();

        // 2. Hapus data dari tabel purchase_items
        $this->purchaseItem->delete($id);

        // 3. Cek apakah tabel purchases (header) masih punya item lain selain yang baru dihapus
        $sisaItem = $this->purchaseItem->where('id_purchase', $id_purchase)->findAll();

        if (empty($sisaItem)) {
            // Jika tidak ada item lain, hapus sekalian header purchase-nya
            $this->purchase->delete($id_purchase);
        }

        $db->transComplete();

        if ($db->transStatus() === FALSE) {
            return redirect()->to('/owner/material')->with('error', 'Gagal menghapus data dari sistem database.');
        }

        return redirect()->to('/owner/material')->with('success', 'Data pembelian material berhasil dihapus!');
    }
}