<?php
// Error Reporting (Development Mode)
ini_set('display_errors', 0); // লাইভ সাইটে এরর হাইড রাখাই ভালো
error_reporting(E_ALL);

use Dompdf\Dompdf;
use Dompdf\Options;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    require_once __DIR__ . '/dompdf/autoload.inc.php';

    // আপনার আগের হুবহু একই PDF জেনারেশন লজিকটি এখানে বসবে
    $invoice_number = trim($_POST['invoice_number'] ?? '');
    $theme_color    = trim($_POST['theme_color'] ?? '#2ecc71');
    $currency_sym   = trim($_POST['currency_symbol'] ?? '$');
    
    $label_invoice = trim($_POST['label_invoice'] ?? 'INVOICE');
    $label_from    = trim($_POST['label_from'] ?? 'From');
    $label_to      = trim($_POST['label_to'] ?? 'To');
    $label_date    = trim($_POST['label_date'] ?? 'Date');
    $label_terms   = trim($_POST['label_terms'] ?? 'Payment Terms');
    $label_due     = trim($_POST['label_due'] ?? 'Due Date');
    $label_po      = trim($_POST['label_po'] ?? 'PO Number');
    $label_notes   = trim($_POST['label_notes'] ?? 'Notes');
    $label_terms_cond = trim($_POST['label_terms_cond'] ?? 'Terms');
    $label_subtotal = trim($_POST['label_subtotal'] ?? 'Subtotal');
    $label_tax      = trim($_POST['label_tax'] ?? 'Tax');
    $label_discount = trim($_POST['label_discount'] ?? 'Discount');
    $label_shipping = trim($_POST['label_shipping'] ?? 'Shipping');
    $label_total    = trim($_POST['label_total'] ?? 'Total');
    $label_paid     = trim($_POST['label_paid'] ?? 'Amount Paid');
    $label_balance  = trim($_POST['label_balance'] ?? 'Balance Due');
    $label_signature = trim($_POST['label_signature'] ?? 'Signature');

    $from_text      = trim($_POST['from_text'] ?? '');
    $to_text        = trim($_POST['to_text'] ?? '');
    $optional_text  = trim($_POST['optional_text'] ?? '');
    $date           = trim($_POST['date'] ?? '');
    $payment_terms  = trim($_POST['payment_terms'] ?? '');
    $due_date       = trim($_POST['due_date'] ?? '');
    $po_number      = trim($_POST['po_number'] ?? '');
    $notes          = trim($_POST['notes'] ?? '');
    $terms_cond     = trim($_POST['terms'] ?? '');
    
    $tax_amount     = floatval($_POST['tax_amount'] ?? 0);
    $tax_type       = $_POST['tax_type'] ?? 'percent'; 
    $discount_amount= floatval($_POST['discount_amount'] ?? 0);
    $discount_type  = $_POST['discount_type'] ?? 'percent'; 
    $shipping_amount= floatval($_POST['shipping_amount'] ?? 0);
    $amount_paid    = floatval($_POST['amount_paid'] ?? 0);
    
    $items =[];
    $subtotal = 0;
    if (isset($_POST['item_desc']) && is_array($_POST['item_desc'])) {
        for ($i = 0; $i < count($_POST['item_desc']); $i++) {
            $desc  = trim($_POST['item_desc'][$i]);
            $rate  = floatval($_POST['item_rate'][$i]);
            $qty   = floatval($_POST['item_qty'][$i]);
            $total = $rate * $qty;
            if($desc !== '' || $total > 0) {
                $subtotal += $total;
                $items[] =['desc' => $desc, 'rate' => $rate, 'qty' => $qty, 'total' => $total];
            }
        }
    }
    
    $calculated_discount = ($discount_type === 'percent') ? ($subtotal * ($discount_amount / 100)) : $discount_amount;
    $after_discount = $subtotal - $calculated_discount;
    $calculated_tax = ($tax_type === 'percent') ? ($after_discount * ($tax_amount / 100)) : $tax_amount;
    $total_due = $after_discount + $calculated_tax + $shipping_amount;
    $balance_due = $total_due - $amount_paid;

    $logo_base64 = '';
    if (isset($_FILES['logo']) && $_FILES['logo']['error'] === UPLOAD_ERR_OK) {
        $logo_base64 = 'data:' . $_FILES['logo']['type'] . ';base64,' . base64_encode(file_get_contents($_FILES['logo']['tmp_name']));
    }
    
    $signature_base64 = '';
    if (isset($_FILES['signature']) && $_FILES['signature']['error'] === UPLOAD_ERR_OK) {
        $signature_base64 = 'data:' . $_FILES['signature']['type'] . ';base64,' . base64_encode(file_get_contents($_FILES['signature']['tmp_name']));
    }

    $html = '
    <html>
    <head>
        <style>
            body { font-family: "DejaVu Sans", sans-serif; color: #333; font-size: 13px; margin: 0; padding: 0; line-height: 1.4; }
            table { width: 100%; border-collapse: collapse; }
            td { vertical-align: top; }
            .text-right { text-align: right; }
            .title { font-size: 36px; font-weight: 300; color: ' . $theme_color . '; letter-spacing: 1px; margin-bottom: 5px; text-transform: uppercase; }
            .invoice-meta td { padding: 5px 10px 5px 0; border-bottom: 1px solid #f0f0f0; }
            .items-table { margin-top: 30px; margin-bottom: 20px; }
            .items-table th { background: ' . $theme_color . '; color: #fff; padding: 12px 10px; font-size: 12px; text-align: left; text-transform: uppercase; }
            .items-table th.text-right { text-align: right; }
            .items-table td { padding: 12px 10px; border-bottom: 1px solid #e9ecef; }
            .summary-table { width: 100%; margin-top: 10px; }
            .summary-table td { padding: 8px 10px; border-bottom: 1px solid #f0f0f0; }
            .grand-total { font-weight: bold; font-size: 16px; color: #222; }
            .balance-due { font-weight: bold; font-size: 15px; background: #f8f9fa; color: ' . $theme_color . '; }
            .section-title { font-weight: bold; color: #777; font-size: 12px; text-transform: uppercase; margin-bottom: 8px; margin-top: 20px; }
            .text-muted { color: #555; }
            .signature-box { margin-top: 40px; text-align: right; }
            .signature-box img { max-width: 150px; max-height: 80px; margin-bottom: 5px; }
            .signature-line { border-top: 1px solid #333; width: 150px; display: inline-block; margin-top: 10px; padding-top: 5px; font-size: 12px; }
        </style>
    </head>
    <body>
        <table style="margin-bottom: 35px;">
            <tr>
                <td style="width: 50%;">';
                if ($logo_base64) { $html .= '<img src="' . $logo_base64 . '" style="max-width: 180px; max-height: 80px;">'; }
    $html .= '  </td>
                <td class="text-right" style="width: 50%;">
                    <div class="title">' . htmlspecialchars($label_invoice) . '</div>
                    ' . ($invoice_number !== '' ? '<div style="font-size: 16px; color: #555;"># ' . htmlspecialchars($invoice_number) . '</div>' : '') . '
                </td>
            </tr>
        </table>
        
        <table style="margin-bottom: 30px;">
            <tr>
                <td style="width: 50%; padding-right: 20px;">
                    ' . ($from_text !== '' ? '<div class="section-title">' . htmlspecialchars($label_from) . '</div><div class="text-muted">' . nl2br(htmlspecialchars($from_text)) . '</div>' : '') . '
                    ' . ($to_text !== '' ? '<div class="section-title">' . htmlspecialchars($label_to) . '</div><div class="text-muted">' . nl2br(htmlspecialchars($to_text)) . '</div>' : '') . '
                    ' . ($optional_text !== '' ? '<div style="margin-top: 10px;" class="text-muted">' . nl2br(htmlspecialchars($optional_text)) . '</div>' : '') . '
                </td>
                <td style="width: 50%;">
                    <table class="invoice-meta">';
                    if ($date !== '') { $html .= '<tr><td><strong>' . htmlspecialchars($label_date) . ':</strong></td><td class="text-right">' . htmlspecialchars($date) . '</td></tr>'; }
                    if ($payment_terms !== '') { $html .= '<tr><td><strong>' . htmlspecialchars($label_terms) . ':</strong></td><td class="text-right">' . htmlspecialchars($payment_terms) . '</td></tr>'; }
                    if ($due_date !== '') { $html .= '<tr><td><strong>' . htmlspecialchars($label_due) . ':</strong></td><td class="text-right">' . htmlspecialchars($due_date) . '</td></tr>'; }
                    if ($po_number !== '') { $html .= '<tr><td><strong>' . htmlspecialchars($label_po) . ':</strong></td><td class="text-right">' . htmlspecialchars($po_number) . '</td></tr>'; }
    $html .= '      </table>
                </td>
            </tr>
        </table>';

    if (count($items) > 0) {
        $html .= '
        <table class="items-table">
            <thead>
                <tr>
                    <th>Description</th>
                    <th class="text-right">Rate</th>
                    <th class="text-right">Qty</th>
                    <th class="text-right">Amount</th>
                </tr>
            </thead>
            <tbody>';
            foreach ($items as $item) {
                $html .= '
                <tr>
                    <td>' . nl2br($item['desc']) . '</td>
                    <td class="text-right">' . $currency_sym . number_format($item['rate'], 2) . '</td>
                    <td class="text-right">' . $item['qty'] . '</td>
                    <td class="text-right">' . $currency_sym . number_format($item['total'], 2) . '</td>
                </tr>';
            }
        $html .= '
            </tbody>
        </table>';
    }

    $html .= '
        <table>
            <tr>
                <td style="width: 50%; padding-right: 20px;">
                    ' . ($notes !== '' ? '<div class="section-title">' . htmlspecialchars($label_notes) . '</div><div class="text-muted" style="margin-bottom: 15px;">' . nl2br(htmlspecialchars($notes)) . '</div>' : '') . '
                    ' . ($terms_cond !== '' ? '<div class="section-title">' . htmlspecialchars($label_terms_cond) . '</div><div class="text-muted">' . nl2br(htmlspecialchars($terms_cond)) . '</div>' : '') . '
                </td>
                <td style="width: 50%;">
                    <table class="summary-table">
                        <tr><td>' . htmlspecialchars($label_subtotal) . '</td><td class="text-right">' . $currency_sym . number_format($subtotal, 2) . '</td></tr>';
                        
                        if ($discount_amount > 0) {
                            $discount_display = ($discount_type === 'percent') ? " (" . $discount_amount . "%)" : "";
                            $html .= '<tr><td style="color:#e74c3c;">' . htmlspecialchars($label_discount) . $discount_display . '</td><td class="text-right" style="color:#e74c3c;">-' . $currency_sym . number_format($calculated_discount, 2) . '</td></tr>';
                        }
                        if ($tax_amount > 0) {
                            $tax_display = ($tax_type === 'percent') ? " (" . $tax_amount . "%)" : "";
                            $html .= '<tr><td>' . htmlspecialchars($label_tax) . $tax_display . '</td><td class="text-right">' . $currency_sym . number_format($calculated_tax, 2) . '</td></tr>';
                        }
                        if ($shipping_amount > 0) {
                            $html .= '<tr><td>' . htmlspecialchars($label_shipping) . '</td><td class="text-right">' . $currency_sym . number_format($shipping_amount, 2) . '</td></tr>';
                        }
                        
    $html .= '          <tr><td class="grand-total">' . htmlspecialchars($label_total) . '</td><td class="text-right grand-total">' . $currency_sym . number_format($total_due, 2) . '</td></tr>';
                        
                        if ($amount_paid > 0) {
                            $html .= '<tr><td>' . htmlspecialchars($label_paid) . '</td><td class="text-right">' . $currency_sym . number_format($amount_paid, 2) . '</td></tr>';
                        }
                        
    $html .= '          <tr class="balance-due"><td style="padding: 12px 10px;">' . htmlspecialchars($label_balance) . '</td><td class="text-right" style="padding: 12px 10px;">' . $currency_sym . number_format($balance_due, 2) . '</td></tr>
                    </table>
                </td>
            </tr>
        </table>';

    if ($signature_base64) {
        $html .= '
        <div class="signature-box">
            <img src="' . $signature_base64 . '"><br>
            <div class="signature-line">' . htmlspecialchars($label_signature) . '</div>
        </div>';
    }

    $html .= '
    </body>
    </html>';

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

    $dompdf->stream("Invoice_" . ($invoice_number ?: time()) . ".pdf",["Attachment" => true]);
    exit;
}
?>