<?php
ini_set('display_errors', '0');
ini_set('display_startup_errors', '0');
error_reporting(E_ALL & ~E_WARNING & ~E_NOTICE);
require_once '../includes/functions.php';
require_once '../vendor/autoload.php';
requireLogin();

use Dompdf\Dompdf;
use Dompdf\Options;

$db = getDB();
$id = (int)($_GET['id'] ?? 0);
if (!$id) {
    header('Location: invoices.php');
    exit;
}

try {
    $stmt = $db->prepare("SELECT i.*, c.name as cust_name, c.address as cust_address, c.city as cust_city, c.state as cust_state, c.pincode as cust_pincode, c.email as cust_email, c.phone as cust_phone, c.gstin as cust_gstin FROM invoices i JOIN customers c ON i.customer_id = c.id WHERE i.id = ?");
    $stmt->execute([$id]);
    $inv = $stmt->fetch();
    if (!$inv) {
        header('Location: invoices.php');
        exit;
    }

    $items = $db->prepare("SELECT * FROM invoice_items WHERE invoice_id = ?");
    $items->execute([$id]);
    $lineItems = $items->fetchAll();

    $companyName = APP_NAME;
    $companyAddress = config('COMPANY_ADDRESS', 'Your Business Address Line 1, City, State, PIN 000000');
    $companyPhone = config('COMPANY_PHONE', '+91 87783 18977');
    $companyEmail = config('COMPANY_EMAIL', 'support@jbrsofa.com');
    $companyGstin = config('COMPANY_GSTIN', '22AAAAA0000A1Z5');
} catch (PDOException $e) {
    setFlash('error', 'Failed to load invoice.');
    header('Location: invoices.php');
    exit;
}

ob_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Invoice <?= sanitize($inv['invoice_number']) ?></title>
    <style>
        * { box-sizing: border-box; }
        body { font-family: 'DejaVu Sans', sans-serif; background: #f8fbff; margin: 0; padding: 0; color: #1f2937; }
        .invoice-wrapper { width: 100%; max-width: 840px; margin: 0 auto; background: white; border-radius: 30px; overflow: hidden; box-shadow: 0 30px 80px rgba(15, 23, 42, 0.08); }
        .invoice-panel { padding: 0; }
        .invoice-header { background: #0f172a; color: white; padding: 40px 36px 30px; }
        .invoice-header .company-top { display: table; width: 100%; table-layout: fixed; }
        .company-left, .company-right { display: table-cell; vertical-align: top; }
        .company-left { width: 65%; }
        .company-right { width: 35%; text-align: right; }
        .company-tag { font-size: 10px; letter-spacing: 1.8px; text-transform: uppercase; color: #c7d2fe; margin-bottom: 10px; }
        .company-name { font-size: 32px; font-weight: 800; margin: 0; line-height: 1; }
        .company-details { margin-top: 18px; font-size: 11px; line-height: 1.8; color: #dbeafe; }
        .invoice-badge { display: inline-block; background: #4338ca; padding: 10px 16px; border-radius: 16px; color: white; font-size: 10px; letter-spacing: 1.4px; text-transform: uppercase; margin-bottom: 16px; }
        .invoice-number { font-size: 38px; font-weight: 800; letter-spacing: -0.03em; margin: 0; }
        .invoice-date { margin-top: 10px; color: #c7d2fe; font-size: 13px; }
        .details-row { display: table; width: 100%; border-collapse: collapse; background: white; }
        .detail-cell { display: table-cell; vertical-align: top; width: 50%; padding: 28px 32px; }
        .detail-card { border-radius: 24px; background: #f8fafc; padding: 22px 24px; }
        .detail-label { font-size: 10px; color: #475569; text-transform: uppercase; letter-spacing: 0.18em; font-weight: 700; margin-bottom: 8px; }
        .detail-value { font-size: 14px; color: #0f172a; font-weight: 700; line-height: 1.6; }
        .status-badge { display: inline-flex; align-items: center; justify-content: center; padding: 6px 14px; border-radius: 999px; background: #4338ca; color: white; font-size: 10px; text-transform: uppercase; letter-spacing: 0.12em; font-weight: 700; }
        .customer-box { margin: 24px 24px 0; padding: 22px 24px; border-radius: 24px; background: #eef2ff; border-left: 6px solid #4338ca; }
        .customer-box h3 { margin: 0 0 10px; font-size: 11px; color: #4338ca; letter-spacing: 0.18em; text-transform: uppercase; font-weight: 800; }
        .customer-name { margin: 0 0 8px; font-size: 16px; font-weight: 800; color: #0f172a; }
        .customer-info { margin: 4px 0; font-size: 12px; color: #475569; line-height: 1.7; }
        .items-table { width: 100%; border-collapse: collapse; margin: 24px 0 0; }
        .items-table th, .items-table td { padding: 14px 16px; font-size: 12px; }
        .items-table th { text-align: left; color: #475569; text-transform: uppercase; letter-spacing: 0.12em; border-bottom: 2px solid #e2e8f0; }
        .items-table td { border-bottom: 1px solid #e2e8f0; color: #334155; }
        .items-table td.amount { text-align: right; font-weight: 700; }
        .items-table tbody tr:nth-child(odd) { background: #f8fafc; }
        .summary { padding: 28px 32px 32px; }
        .summary-row { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; font-size: 12px; color: #475569; }
        .summary-row strong { color: #0f172a; font-weight: 700; }
        .summary-total { margin-top: 14px; padding-top: 14px; border-top: 1px solid #e2e8f0; display: flex; justify-content: space-between; font-size: 14px; font-weight: 800; color: #0f172a; }
        .notes-section { margin: 0 24px 24px; padding: 18px 20px; border-radius: 22px; background: #f8fafc; border-left: 5px solid #10b981; color: #334155; font-size: 12px; line-height: 1.7; }
        .footer { padding: 22px 24px 28px; text-align: center; font-size: 11px; color: #64748b; }
        .footer strong { color: #0f172a; }
    </style>
</head>
<body>
    <div class="invoice-wrapper">
        <!-- Professional Header -->
        <div class="invoice-header">
            <div class="invoice-title-line">
                <div class="invoice-tag">INVOICE</div>
                <div class="invoice-number"><?= sanitize($inv['invoice_number']) ?></div>
            </div>
            <div class="invoice-row">
                <div class="company-block">
                    <div class="company-name"><?= sanitize($companyName) ?></div>
                    <div class="company-tag"><?= sanitize($companyAddress) ?></div>
                    <div class="company-details">
                        Phone: <?= sanitize($companyPhone) ?><br>
                        Email: <?= sanitize($companyEmail) ?><br>
                        GST: <?= sanitize($companyGstin) ?>
                    </div>
                </div>
                <div class="details-block">
                    <span class="meta-label">Invoice Date</span>
                    <span class="meta-value"><?= date('d M Y', strtotime($inv['invoice_date'])) ?></span>
                    <?php if (!empty($inv['due_date'])): ?>
                    <span class="meta-label">Due Date</span>
                    <span class="meta-value"><?= date('d M Y', strtotime($inv['due_date'])) ?></span>
                    <?php endif; ?>
                    <span class="meta-label">Status</span>
                    <span class="meta-value"><?= strtoupper(sanitize($inv['status'])) ?></span>
                </div>
            </div>
        </div>

        <!-- Invoice Details -->
        <div class="details-row">
            <div class="detail-cell">
                <div class="detail-label">Invoice Date</div>
                <div class="detail-value"><?= date('d M Y', strtotime($inv['invoice_date'])) ?></div>
                <?php if ($inv['due_date']): ?>
                <div class="detail-label" style="margin-top: 10px;">Due Date</div>
                <div class="detail-value"><?= date('d M Y', strtotime($inv['due_date'])) ?></div>
                <?php endif; ?>
            </div>
            <div class="detail-cell">
                <div class="detail-label">Status</div>
                <div class="status-badge"><?= strtoupper($inv['status']) ?></div>
                <div class="detail-label" style="margin-top: 10px;">Customer Reference</div>
                <div class="detail-value"><?= sanitize($inv['id']) ?></div>
            </div>
        </div>

        <!-- Customer Section -->
        <div class="customer-box">
            <h3>Bill To</h3>
            <div class="customer-name"><?= sanitize($inv['cust_name']) ?></div>
            <?php if ($inv['cust_address']): ?>
            <div class="customer-info"><?= nl2br(sanitize($inv['cust_address'])) ?></div>
            <?php endif; ?>
            <?php if ($inv['cust_city'] || $inv['cust_state'] || $inv['cust_pincode']): ?>
            <div class="customer-info"><?= sanitize(trim($inv['cust_city'] . ' ' . $inv['cust_state'] . ' ' . $inv['cust_pincode'])) ?></div>
            <?php endif; ?>
            <?php if ($inv['cust_phone']): ?><div class="customer-info">Phone: <?= sanitize($inv['cust_phone']) ?></div><?php endif; ?>
            <?php if ($inv['cust_email']): ?><div class="customer-info">Email: <?= sanitize($inv['cust_email']) ?></div><?php endif; ?>
            <?php if ($inv['cust_gstin']): ?><div class="customer-info">GSTIN: <?= sanitize($inv['cust_gstin']) ?></div><?php endif; ?>
        </div>

        <table class="items-table">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Description</th>
                    <th class="amount">Qty</th>
                    <th class="amount">Rate</th>
                    <th class="amount">GST%</th>
                    <th class="amount">Amount</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($lineItems as $index => $item): ?>
                <tr>
                    <td><?= $index + 1 ?></td>
                    <td><?= sanitize($item['product_name']) ?></td>
                    <td class="amount"><?= (int)$item['quantity'] ?></td>
                    <td class="amount"><?= formatCurrency($item['unit_price']) ?></td>
                    <td class="amount"><?= number_format($item['gst_percent'], 2) ?>%</td>
                    <td class="amount"><?= formatCurrency($item['line_total']) ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>

        <div class="summary">
            <div class="summary-row"><div class="summary-label">Subtotal</div><div class="summary-value"><?= formatCurrency($inv['subtotal']) ?></div></div>
            <?php if ($inv['discount_amount'] > 0): ?>
            <div class="summary-row"><div class="summary-label">Discount</div><div class="summary-value">- <?= formatCurrency($inv['discount_amount']) ?></div></div>
            <?php endif; ?>
            <div class="summary-row"><div class="summary-label">GST</div><div class="summary-value"><?= formatCurrency($inv['gst_amount']) ?></div></div>
            <div class="summary-row summary-total"><div class="summary-label">Total</div><div class="summary-value"><?= formatCurrency($inv['total_amount']) ?></div></div>
        </div>

        <?php if ($inv['notes']): ?>
        <div class="notes">
            <strong>Notes:</strong>
            <p><?= nl2br(sanitize($inv['notes'])) ?></p>
        </div>
        <?php endif; ?>

        <div class="footer">Thank you for your business. Generated by JBR Sofa.</div>
    </div>
</body>
</html>
<?php
$html = ob_get_clean();

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

$dompdf->stream('invoice_' . $inv['invoice_number'] . '.pdf', array('Attachment' => true));
exit;
