<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Generateinvoice extends CI_Controller {

    public function generate($invoice_id)
    {
        // ❗ WAJIB: hindari output lain sebelum PDF
        ob_end_clean();

        // =========================
        // 🔥 AMBIL DATA PERUSAHAAN
        // =========================
        $invp = $this->db->get('pengaturan')->row_array(); // 🔥 FIX: tidak pakai GET server_id

        if(!$invp){
            show_error('Data perusahaan tidak ditemukan');
        }

        $nama        = $invp['nama_perusahaan'];
        $alamat      = $invp['alamat_perusahaan'];
        $telepon     = $invp['telepon_perusahaan'];
        $Keterangan  = $invp['catatan_perusahaan'];
        $Pembuat     = $invp['nama_bendahara'];
        $logo        = base_url('uploads/img/logo-ljn.png');

        // =========================
        // 🔥 GET INVOICE + CUSTOMER
        // =========================
        $invi = $this->db->select('invoices.*, customers.nama, customers.alamat, customers.telp')
            ->from('invoices')
            ->join('customers', 'customers.id = invoices.customer_id', 'left')
            ->where('invoices.id', $invoice_id)
            ->get()
            ->row_array();

        // =========================
        // VALIDASI
        // =========================
        if(!$invi){
            show_error('Invoice tidak ditemukan');
        }

        // =========================
        // MAPPING DATA
        // =========================
        $customerAddress = $invi['alamat'] ?? '-';
        $customerName    = $invi['nama'] ?? '-';
        $customerNumber  = $invi['telp'] ?? '-';

        $invoiceNumber   = $invi['no_invoice'] ?? '-';
        $invoiceDate     = $invi['tanggal'] ?? '-'; // 🔥 sesuaikan field kamu
        $invoiceLimit    = $invi['jatuh_tempo'] ?? '-'; // 🔥 sesuaikan juga

        // =========================
        // 🔥 DETAIL ITEM
        // =========================
        $header = ['No','Tanggal','Item','Deskripsi','Qty','Harga', 'Subtotal'];
        $data   = [];

        // 🔥 NOTE: sesuaikan tabel kamu (invoice_details / invoice_list)
        // $detail = $this->db->get_where('invoice_details', [
        //     'invoice_id' => $invoice_id
        // ])->result_array();
        
        $detail = $this->db
            ->where('invoice_id', $invoice_id)
            ->order_by('tanggal', 'ASC')
            ->get('invoice_details')
            ->result_array();

        $no = 1;
        foreach($detail as $d){
            $data[] = [
                $no++,
                $d['tanggal'],
                $d['nama_item'],
                $d['keterangan'],
                $d['qty'],
                number_format($d['harga']),
                number_format($d['subtotal'])
            ];
        }

        // =========================
        // 🔥 TOTAL
        // =========================
        $total = (float)$invi['total'];

        $this->db->select_sum('sisa_piutang');
        $this->db->where('customer_id', $invi['customer_id']);
        $this->db->where('status !=', 'paid');
        $this->db->where('id !=', $invoice_id); // exclude invoice sekarang

        $tunggakan = $this->db->get('invoices')->row()->sisa_piutang ?? 0;

        // Ngambil Data Tunggakan bulan lalu jika ada.
        $keteranganlain = 'Akumulasi Tunggakan Invoice Bulan Lalu';
        $nom_lainnya    = $tunggakan;

        $subtotal       = number_format($total);
        $lainnya        = number_format($nom_lainnya);
        $totalAmount    = number_format($total + $nom_lainnya);
        $terbilang      = trim($this->terbilang($total + $nom_lainnya)).' rupiah';

        $filename = 'INV-'.$customerName.'-'.$invoiceNumber.'.pdf';

        // =========================
        // 🔥 LOAD FPDF
        // =========================
        require_once(APPPATH.'third_party/fpdf/fpdf.php');
        require_once(APPPATH.'libraries/PDF_Invoice.php');

        $pdf = new PDF();

        // 🔥 FIX PATH LOGO (WAJIB)
        $logo_path = FCPATH.'img/user/'.$logo;
        if(!file_exists($logo_path)){
            $logo_path = ''; // biar gak error kalau logo tidak ada
        }

        $pdf->setHeaderData($nama, $alamat, $telepon, $logo);
        $pdf->AddPage();
        $pdf->SetFont('Arial','',12);

        $pdf->CustomerDetails(
            $customerName,
            $customerAddress,
            $invoiceNumber,
            $invoiceDate,
            $customerNumber,
            $invoiceLimit
        );

        $pdf->InvoiceTable($header, $data);
        $pdf->Total($subtotal,$lainnya,$totalAmount,$terbilang,$keteranganlain);
        $pdf->Keterangan($Keterangan);
        $pdf->Pembuat($Pembuat);

        // =========================
        // 🔥 OUTPUT LANGSUNG (TANPA SIMPAN)
        // =========================
        $pdf->Output('I', $filename);


        // =========================
        // LOG ACTIVITY
        // =========================
        log_activity(
            'invoice',
            'generate',
            'Generate invoice #' . $invoiceNumber . ' untuk ' . $customerName,
            'success'
        );

        exit;
    }

    // =========================
    // 🔥 TERBILANG
    // =========================
    private function terbilang($angka)
    {
        $angka = abs($angka);
        $baca = ["", "satu", "dua", "tiga", "empat", "lima", "enam", "tujuh", "delapan", "sembilan", "sepuluh", "sebelas"];

        if ($angka < 12) {
            return " " . $baca[$angka];
        } elseif ($angka < 20) {
            return $this->terbilang($angka - 10) . " belas";
        } elseif ($angka < 100) {
            return $this->terbilang(intval($angka / 10)) . " puluh" . $this->terbilang($angka % 10);
        } elseif ($angka < 200) {
            return " seratus" . $this->terbilang($angka - 100);
        } elseif ($angka < 1000) {
            return $this->terbilang(intval($angka / 100)) . " ratus" . $this->terbilang($angka % 100);
        } elseif ($angka < 2000) {
            return " seribu" . $this->terbilang($angka - 1000);
        } elseif ($angka < 1000000) {
            return $this->terbilang(intval($angka / 1000)) . " ribu" . $this->terbilang($angka % 1000);
        } elseif ($angka < 1000000000) {
            return $this->terbilang(intval($angka / 1000000)) . " juta" . $this->terbilang($angka % 1000000);
        }

        return "";
    }

}