<?php

namespace App\Controllers\Admin;

use App\Controllers\BaseController;
use App\Models\OrderModel;
use App\Models\OrderItemModel;
use App\Models\InvoiceModel;
use App\Models\ActivityLogModel;
use App\Models\CompanySettingModel;
use App\Services\InvoiceService;
use App\Services\NotificationService;
use Dompdf\Dompdf;
use Dompdf\Options;

class Invoice extends BaseController
{
    /**
     * Menghasilkan invoice (faktur penagihan) otomatis dari pesanan yang dibuat
     */
    public function generate($id_order, $tipe = 'umum')
    {
        $db = \Config\Database::connect();
        
        $orderModel = new OrderModel();
        $orderItemModel = new OrderItemModel();
        $invoiceModel = new InvoiceModel();
        
        $order = $orderModel->find($id_order);
        if (! $order) {
            return redirect()->back()->with('error', 'Pesanan tidak ditemukan.');
        }

        // Cek apakah invoice sudah ada
        $existingInvoice = $invoiceModel->where('id_order', $id_order)->first();

        $db->transStart();

        if (! $existingInvoice) {
            // Prefix invoice
            $systemSetting = $db->table('system_settings')->get()->getRowArray();
            $prefix = $systemSetting['invoice_prefix'] ?? 'INV';
            $dateStr = date('Ymd');
            
            $lastInv = $invoiceModel
                ->like('nomor_invoice', "{$prefix}-{$dateStr}-")
                ->orderBy('id_invoice', 'DESC')
                ->first();
                
            $nextNum = $lastInv ? ((int) substr($lastInv['nomor_invoice'], -4)) + 1 : 1;
            $nomor_invoice = "{$prefix}-{$dateStr}-" . str_pad($nextNum, 4, '0', STR_PAD_LEFT);
            
            // Token akses publik
            $accessToken = bin2hex(random_bytes(32));
            
            // Jatuh tempo
            $jatuhTempo = date('Y-m-d', strtotime('+7 days'));
            
            // Total invoice
            $totalTagihan = (float) ($order['total'] ?? $order['grand_total'] ?? 0);
            
            $invoiceModel->insert([
                'id_order'            => $id_order,
                'nomor_invoice'       => $nomor_invoice,
                'access_token'        => $accessToken,
                'tanggal_jatuh_tempo' => $jatuhTempo,
                'total_tagihan'       => $totalTagihan,
                'sisa_tagihan'        => $totalTagihan,
                'status'              => 'unpaid'
            ]);
            
            $id_invoice = $invoiceModel->insertID();
            $invoice = $invoiceModel->find($id_invoice);

            // Simpan detail invoice
            $items = $orderItemModel->where('id_order', $id_order)->findAll();
            foreach ($items as $item) {
                $db->table('invoice_items')->insert([
                    'id_invoice' => $id_invoice,
                    'item_name'  => $item['product_name'] ?? 'Produk',
                    'qty'        => $item['qty'],
                    'price'      => $item['price'] ?? $item['harga'] ?? 0,
                    'total'      => $item['subtotal']
                ]);
            }

            // Activity Log
            (new ActivityLogModel())->logActivity(
                session()->get('id_user') ?? 1,
                "Menerbitkan Faktur Tagihan: {$nomor_invoice}"
            );
            
        } else {
            // Invoice lama mungkin dibuat sebelum access_token digunakan.
            $invoice = (new InvoiceService())->ensureAccessToken($existingInvoice);
            $nomor_invoice = $existingInvoice['nomor_invoice'];
        }

        $db->transComplete();

        if ($db->transStatus() === false) {
            return redirect()->back()->with('error', 'Gagal memproses penerbitan invoice.');
        }

        // Kirim WhatsApp
        try {
            (new NotificationService())->sendOrderNotifications($order, $invoice);
        } catch (\Throwable $e) {
            log_message('error', 'Gagal mengirim WhatsApp invoice: ' . $e->getMessage());
        }

        // Ambil Data Pengaturan Perusahaan untuk Kop Surat
        $companySetting = new CompanySettingModel();
        $companyData = $companySetting->first() ?? [];

        $data = [
            'order'         => $order,
            'items'         => $orderItemModel->where('id_order', $id_order)->findAll(),
            'nomor_invoice' => $nomor_invoice,
            'invoice'       => $invoice,
            'company'       => $companyData, // Sisipkan data perusahaan ke view
        ];

        return view('invoice/pdf', $data);
    }

    /**
     * Fitur Tambahan: Menghasilkan dan Mendownload file PDF Invoice (Bisa di HP/Laptop)
     * URL Endpoint: /invoice/{token}/pdf
     */
    public function getPdf($token = null)
    {
        if (empty($token)) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound('Token invoice tidak valid.');
        }

        $invoiceModel = new InvoiceModel();
        $orderModel = new OrderModel();
        $orderItemModel = new OrderItemModel();

        // 1. Cari data invoice berdasarkan token
        $invoice = $invoiceModel->where('access_token', $token)->first();
        if (!$invoice) {
            throw \CodeIgniter\Exceptions\PageNotFoundException::forPageNotFound('Data Invoice tidak ditemukan.');
        }

        // 2. Ambil data order dan item
        $id_order = $invoice['id_order'];
        $order = $orderModel->find($id_order);
        $items = $orderItemModel->where('id_order', $id_order)->findAll();

        // 3. Ambil Data Pengaturan Perusahaan untuk Kop Surat di PDF
        $companySetting = new CompanySettingModel();
        $companyData = $companySetting->first() ?? [];

        $data = [
            'invoice'  => $invoice,
            'order'    => $order,
            'items'    => $items,
            'payments' => [], // Dikosongkan agar tidak memicu error database
            'company'  => $companyData, // Sisipkan data perusahaan ke view PDF
        ];

        // 4. Render tampilan HTML untuk dikonversi ke PDF
        $html = view('invoice/pdf', $data);

        // 5. Konfigurasi Dompdf
        $options = new Options();
        $options->set('isHtml5ParserEnabled', true);
        $options->set('isRemoteEnabled', true);
        
        $dompdf = new Dompdf($options);
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4', 'portrait');

        // 6. Render file HTML menjadi PDF
        $dompdf->render();

        // 7. Output / Download file PDF
        $fileName = 'Invoice-' . $invoice['nomor_invoice'] . '.pdf';
        $dompdf->stream($fileName, ["Attachment" => true]);
        
        exit();
    }
}