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

class Invoice_service
{
    protected $ci;

    public function __construct()
    {
        $this->ci =& get_instance();

        // gunakan pdf_helper yang sudah kamu punya (rupiah)
        $this->ci->load->helper(['url','pdf_helper']);
        $this->ci->load->library(['email','Dompdf_lib']);
        // load models yang ada di projectmu
        $this->ci->load->model(['Pembayaran_model', 'PembayaranSiswa_model', 'Siswa_model', 'User_model']);
        // Tagihan_model optional, hanya kalau table ada
        if ($this->ci->db->table_exists('TagihanHSI')) {
            $this->ci->load->model('Tagihan_model');
            $this->use_tagihan = true;
        } else {
            $this->use_tagihan = false;
        }
    }

    /**
     * Public: render HTML untuk email
     */
    public function render_invoice_html($ref_id): string
    {
        $data = $this->prepare_invoice_data($ref_id);
        return $this->ci->load->view('emails/invoice_html', $data, true);
    }

    /**
     * Public: render PDF (binary)
     */
    public function render_invoice_pdf($ref_id): string
    {
        $data = $this->prepare_invoice_data($ref_id);
        $html = $this->ci->load->view('pdf/invoice_pdf', $data, true);

        $dompdf = $this->ci->dompdf_lib->new();
        $dompdf->loadHtml($html);
        $dompdf->setPaper('A4','portrait');
        $dompdf->render();

        return $dompdf->output();
    }

    /**
     * Public: kirim email invoice, $ref_id bisa TagihanID atau PembayaranID
     */
    public function email_invoice($ref_id): bool
    {
        $data = $this->prepare_invoice_data($ref_id);

        $email_to = $data['email'] ?? '';
        if (empty($email_to)) return false;

        $subject = '[HSI] Invoice Pendaftaran ' . ($data['nama_siswa'] ?? '');

        $html_body = $this->ci->load->view('emails/invoice_html', $data, true);
        $pdf_binary = $this->render_invoice_pdf($ref_id);
        $filename = 'Invoice-HSI-' . ($data['invoice_no'] ?? time()) . '.pdf';

        // setup email
        $this->ci->email->clear(true);
        $this->ci->email->set_newline("\r\n");
        $this->ci->email->from($this->sender_email(), 'HSI Admin');
        $this->ci->email->to($email_to);
        if (!empty($data['email_cc'])) $this->ci->email->cc($data['email_cc']);
        $this->ci->email->subject($subject);
        $this->ci->email->message($html_body);

        // try attach binary (some CI support)
        try {
            $this->ci->email->attach($pdf_binary, 'attachment', $filename, 'application/pdf');
            if ($this->ci->email->send()) return true;
        } catch (Exception $e) {
            // ignore, fallback to temp file
        }

        // fallback: save to temp and attach
        $tmp = sys_get_temp_dir() . DIRECTORY_SEPARATOR . $filename;
        file_put_contents($tmp, $pdf_binary);

        $this->ci->email->clear(true);
        $this->ci->email->set_newline("\r\n");
        $this->ci->email->from($this->sender_email(), 'HSI Admin');
        $this->ci->email->to($email_to);
        if (!empty($data['email_cc'])) $this->ci->email->cc($data['email_cc']);
        $this->ci->email->subject($subject);
        $this->ci->email->message($html_body);
        $this->ci->email->attach($tmp);

        $sent = $this->ci->email->send();
        @unlink($tmp);
        return (bool)$sent;
    }

    /**
     * Prepare data: support TagihanHSI (if exist) else fallback to pembayaran (ambil pembayaran terbaru untuk user / ref)
     * $ref_id: TagihanID or PembayaranID or UserID (Auth dapat mengoper user id)
     */
    protected function prepare_invoice_data($ref_id): array
    {
        // jika TagihanHSI ada, cek dulu
        if ($this->use_tagihan) {
            $tagihan = $this->ci->Tagihan_model->get_by_id($ref_id);
            if ($tagihan) {
                return $this->map_tagihan_to_invoice($tagihan);
            }
        }

        // else, asumsi ref_id adalah PembayaranID atau UserID
        // Try get pembayaransiswa by ID
        $pembayaran = $this->ci->Pembayaran_model->get_by_id($ref_id);
        if (!$pembayaran) {
            // kalau ga ada, coba treat ref_id as user id: ambil pembayaran terakhir utk user
            $pembayaran = $this->ci->Pembayaran_model->get_latest_by_user($ref_id);
        }

        if (!$pembayaran) {
            // fallback minimal: coba pembayaransiswa model
            $pembayaran = $this->ci->PembayaranSiswa_model->get_by_id($ref_id);
        }

        if (!$pembayaran) {
            show_error('Data pembayaran/tagihan tidak ditemukan untuk id: ' . $ref_id, 404);
        }

        // ambil user/siswa
        $user_id = $pembayaran->SiswaUserID ?? $pembayaran->UserID ?? $pembayaran->SiswaID ?? null;
        $user = $this->ci->User_model->get_by_id($user_id);
        $siswa = $this->ci->Siswa_model->get_by_user_id($user_id);

        $nama_siswa = $siswa->FullName ?? $user->FullName ?? ($user->Email ?? 'Calon Siswa');
        $email = $user->Email ?? '';

        // nomor invoice: gunakan nomor pembayaran jika ada, else generate
        $invoice_no = $pembayaran->InvoiceNo ?? ('INV-HSI/'.date('Y').'/'.sprintf('%05d', $pembayaran->PembayaranID ?? time()));

        return [
            'invoice_no' => $invoice_no,
            'ref_type' => 'pembayaran',
            'pembayaran_id' => $pembayaran->PembayaranID ?? null,
            'created_at' => $pembayaran->CreatedAt ?? date('Y-m-d H:i:s'),
            'due_date' => $pembayaran->DueDate ?? date('Y-m-d', strtotime('+7 days')),
            'deskripsi' => $pembayaran->Keterangan ?? 'Biaya Pendaftaran HSI',
            'nominal' => (float)($pembayaran->JumlahBayar ?? $pembayaran->Nominal ?? 0),
            'status' => $pembayaran->Status ?? ($pembayaran->StatusKonfirmasi ?? 'Pending'),
            'nama_siswa' => $nama_siswa,
            'email' => $email,
            'email_cc' => '',
            'phone' => $user->Phone ?? '',
            'bank_nama' => 'BCA',
            'bank_no' => '1234567890',
            'bank_an' => 'Yayasan HSI',
            'base_url' => base_url(),
            'logo_url' => base_url('assets/img/hsi-logo.png'),
            'whatsapp_url' => 'https://wa.me/62' . preg_replace('/^0/','', preg_replace('/\D+/', '', ($user->Phone ?? ''))),
        ];
    }

    protected function map_tagihan_to_invoice($tagihan)
    {
        // jika TagihanHSI table ada (tidak di kasusmu), map field standard
        $invoice_no = !empty($tagihan->InvoiceNo) ? $tagihan->InvoiceNo : ('INV-HSI/'.date('Y').'/'.str_pad($tagihan->TagihanID,5,'0',STR_PAD_LEFT));
        $user_id = $tagihan->SiswaUserID ?? $tagihan->UserID ?? null;
        $user = $this->ci->User_model->get_by_id($user_id);
        $siswa = $this->ci->Siswa_model->get_by_user_id($user_id);

        return [
            'invoice_no' => $invoice_no,
            'ref_type' => 'tagihan',
            'tagihan_id' => $tagihan->TagihanID ?? null,
            'created_at' => $tagihan->CreatedAt ?? date('Y-m-d H:i:s'),
            'due_date' => $tagihan->DueDate ?? date('Y-m-d', strtotime('+7 days')),
            'deskripsi' => $tagihan->Deskripsi ?? 'Biaya Pendaftaran HSI',
            'nominal' => (float)($tagihan->Nominal ?? 0),
            'status' => $tagihan->StatusTagihan ?? 'Pending',
            'nama_siswa' => $siswa->FullName ?? $user->FullName ?? 'Calon Siswa',
            'email' => $user->Email ?? '',
            'email_cc' => '',
            'phone' => $user->Phone ?? '',
            'bank_nama' => 'BCA',
            'bank_no' => '1234567890',
            'bank_an' => 'Yayasan HSI',
            'base_url' => base_url(),
            'logo_url' => base_url('assets/img/hsi-logo.png'),
            'whatsapp_url' => 'https://wa.me/62' . preg_replace('/^0/','', preg_replace('/\D+/', '', ($user->Phone ?? ''))),
        ];
    }

    protected function sender_email()
    {
        $smtp_user = $this->ci->config->item('smtp_user');
        return !empty($smtp_user) ? $smtp_user : 'no-reply@hsi.local';
    }
}
