<?php

namespace App\Controllers;

use App\Controllers\BaseController;
use App\Models\BahanModel;
use App\Models\PembelianBahanModel;
use App\Models\DetailPembelianBahanModel;

/**
 * Controller PembelianBahan
 *
 * Struktur 2 tabel:
 *   tb_pembelian_bahan        → header transaksi (tanggal, supplier, nota, dll)
 *   tb_detail_pembelian_bahan → item bahan per transaksi (id_bahan, jumlah, harga)
 *
 * 1 transaksi bisa berisi BANYAK bahan.
 * Stok di tb_bahan diupdate otomatis via DB Trigger pada tb_detail_pembelian_bahan.
 */
class PembelianBahan extends BaseController
{
    private BahanModel               $modelBahan;
    private PembelianBahanModel      $model;
    private DetailPembelianBahanModel $modelDetail;

    public function __construct()
    {
        $this->modelBahan   = new BahanModel();
        $this->model        = new PembelianBahanModel();
        $this->modelDetail  = new DetailPembelianBahanModel();
    }

    // ── GET /pembelian-bahan ──────────────────────────────────────────────────
    public function index(): string
    {
        return view('pembelian_bahan/index', [
            'title' => 'Pembelian Bahan',
        ]);
    }

    // ── GET /pembelian-bahan/data  (AJAX) ─────────────────────────────────────
    public function data(): \CodeIgniter\HTTP\ResponseInterface
    {
        if (! $this->request->isAJAX()) return $this->forbidden();

        return $this->response->setJSON([
            'success' => true,
            'list'    => $this->model->getAll(),       // header + detail ter-embed
            'summary' => $this->model->getSummary(),
        ]);
    }

    // ── POST /pembelian-bahan/simpan ──────────────────────────────────────────
    // Body JSON:
    // {
    //   tanggal_pembelian_bahan : "2024-01-01",
    //   supplier_pembelian      : "Toko ABC",
    //   tempat_pembelian_bahan  : "Pasar Batu",
    //   catatan_pembelian       : "...",
    //   foto_nota_base64        : "data:image/jpeg;base64,...",   // opsional
    //   items: [
    //     { id_bahan: 1, jumlah_bahan: 5, harga_satuan_bahan: 12000 },
    //     ...
    //   ]
    // }
    public function simpan(): \CodeIgniter\HTTP\ResponseInterface
    {
        if (! $this->request->isAJAX()) return $this->forbidden();

        $body = $this->request->getJSON(true) ?? [];

        $tanggal  = trim($body['tanggal_pembelian_bahan'] ?? date('Y-m-d'));
        $supplier = trim($body['supplier_pembelian']       ?? '');
        $tempat   = trim($body['tempat_pembelian_bahan']   ?? '');
        $catatan  = trim($body['catatan_pembelian']        ?? '');
        $items    = $body['items'] ?? [];
        $notaB64  = $body['foto_nota_base64'] ?? null;

        if (empty($items)) {
            return $this->response->setJSON([
                'success' => false,
                'error'   => 'Tambahkan minimal 1 bahan.',
            ]);
        }

        // ── Validasi & siapkan items ──────────────────────────────────────────
        $validItems = [];
        foreach ($items as $item) {
            $idBahan = (int)   ($item['id_bahan']           ?? 0);
            $jumlah  = (float) ($item['jumlah_bahan']        ?? 0);
            $harga   = (float) ($item['harga_satuan_bahan']  ?? 0);

            if (! $idBahan || $jumlah <= 0 || $harga <= 0) continue;
            if (! $this->modelBahan->find($idBahan))       continue;

            $validItems[] = [
                'id_bahan'          => $idBahan,
                'jumlah_bahan'      => $jumlah,
                'harga_satuan_bahan'=> $harga,
                'subtotal_bahan'    => round($jumlah * $harga, 2),
            ];
        }

        if (empty($validItems)) {
            return $this->response->setJSON([
                'success' => false,
                'error'   => 'Tidak ada item valid yang bisa disimpan.',
            ]);
        }

        // ── Simpan foto nota ──────────────────────────────────────────────────
        $namaFoto = null;
        if ($notaB64 && str_starts_with($notaB64, 'data:image')) {
            $namaFoto = $this->simpanFotoNota($notaB64);
        }

        // ── Transaksi DB ──────────────────────────────────────────────────────
        $db = \Config\Database::connect();
        $db->transStart();

        // 1. Insert header
        $totalKeseluruhan = array_sum(array_column($validItems, 'subtotal_bahan'));

        $this->model->insert([
            'tanggal_pembelian_bahan'   => $tanggal,
            'supplier_pembelian'        => $supplier,
            'tempat_pembelian_bahan'    => $tempat,
            'catatan_pembelian'         => $catatan,
            'foto_nota_pembelian_bahan' => $namaFoto,
            'total_pembelian_bahan'     => $totalKeseluruhan,  // juga diupdate trigger, ini awal saja
        ]);

        $idPembelian = $db->insertID();

        // 2. Insert detail items (trigger akan update stok otomatis)
        foreach ($validItems as &$item) {
            $item['id_pembelian_bahan'] = $idPembelian;
        }
        $this->modelDetail->insertBatch($validItems);

        $db->transComplete();

        if (! $db->transStatus()) {
            return $this->response->setJSON([
                'success' => false,
                'error'   => 'Gagal menyimpan ke database.',
            ]);
        }

        $jumlahItem = count($validItems);
        return $this->response->setJSON([
            'success' => true,
            'message' => "Pembelian berhasil dicatat ({$jumlahItem} item, total Rp " .
                         number_format($totalKeseluruhan, 0, ',', '.') . ").",
        ]);
    }

    // ── POST /pembelian-bahan/hapus ───────────────────────────────────────────
    // Menghapus header → detail ter-CASCADE DELETE via FK → trigger kurangi stok
    public function hapus(): \CodeIgniter\HTTP\ResponseInterface
    {
        if (! $this->request->isAJAX()) return $this->forbidden();

        $id = (int) ($this->request->getJSON(true)['id_pembelian_bahan'] ?? 0);
        if (! $id) {
            return $this->response->setJSON(['success' => false, 'error' => 'ID tidak valid.']);
        }

        $row = $this->model->find($id);
        if (! $row) {
            return $this->response->setJSON(['success' => false, 'error' => 'Data tidak ditemukan.']);
        }

        // Hapus detail dulu (agar trigger kurangi stok jalan), lalu hapus header
        $db = \Config\Database::connect();
        $db->transStart();
        $this->modelDetail->deleteByPembelian($id);  // trigger AFTER DELETE per baris
        $this->model->delete($id);                   // soft delete header
        $db->transComplete();

        if (! $db->transStatus()) {
            return $this->response->setJSON(['success' => false, 'error' => 'Gagal menghapus.']);
        }

        return $this->response->setJSON([
            'success' => true,
            'message' => 'Transaksi pembelian berhasil dihapus. Stok bahan telah dikembalikan.',
        ]);
    }

    // ── Helper: simpan foto nota base64 ke disk ───────────────────────────────
    private function simpanFotoNota(string $dataUrl): ?string
    {
        try {
            [$meta, $base64] = explode(',', $dataUrl, 2);
            preg_match('/data:(image\/\w+);base64/', $meta, $m);
            $mime = $m[1] ?? 'image/jpeg';
            $ext  = match ($mime) {
                'image/png'  => 'png',
                'image/gif'  => 'gif',
                'image/webp' => 'webp',
                default      => 'jpg',
            };

            $namaFile   = 'nota_' . date('Ymd_His') . '_' . bin2hex(random_bytes(4)) . '.' . $ext;
            $uploadPath = FCPATH . 'uploads/nota/';

            if (! is_dir($uploadPath)) mkdir($uploadPath, 0755, true);

            file_put_contents($uploadPath . $namaFile, base64_decode($base64));
            return $namaFile;
        } catch (\Throwable $e) {
            log_message('error', 'simpanFotoNota: ' . $e->getMessage());
            return null;
        }
    }

    // ─────────────────────────────────────────────────────────────────────────
    private function forbidden(): \CodeIgniter\HTTP\ResponseInterface
    {
        return $this->response->setStatusCode(403)->setJSON([
            'success' => false,
            'error'   => 'Forbidden',
        ]);
    }
}