<?php
require_once '../includes/functions.php';
requireLogin();

$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();

    $basePath = getBasePath();
    $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');
    $companyTagline = config('COMPANY_TAGLINE', 'Furniture & Design');
    $companyGstin = config('COMPANY_GSTIN', '22AAAAA0000A1Z5');
} catch (PDOException $e) {
    setFlash('error', 'Failed to load invoice.');
    header('Location: invoices.php');
    exit;
}
?>
<!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>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&family=JetBrains+Mono:wght@400;500&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    <script>
        tailwind.config = {
            theme: { extend: { fontFamily: { sans: ['Plus Jakarta Sans','sans-serif'], mono: ['JetBrains Mono','monospace'] }, colors: { brand: { 600:'#4f56ea', 700:'#4143d0', 950:'#1e1f52' } } } }
        }
    </script>
    <style>
        * { box-sizing: border-box; }
        body { font-family: 'Plus Jakarta Sans', sans-serif; background: #f5f7fb; margin: 0; padding: 20px; }
        .invoice-wrapper { border-radius: 28px; overflow: hidden; box-shadow: 0 25px 60px rgba(15, 23, 42, 0.08); background: #ffffff; }
        .invoice-header { padding: 32px 32px 24px; position: relative; }
        .invoice-header::before { content: ''; position: absolute; top: 0; left: 32px; right: 32px; height: 1px; background: #e2e8f0; }
        .invoice-brand { display: flex; justify-content: space-between; gap: 20px; flex-wrap: wrap; }
        .brand-left { max-width: 55%; }
        .brand-name { font-size: 1.9rem; font-weight: 800; color: #0f172a; margin-bottom: 6px; }
        .brand-tag { font-size: 0.75rem; letter-spacing: 0.3em; text-transform: uppercase; color: #94a3b8; margin-bottom: 12px; }
        .brand-info { color: #475569; font-size: 0.95rem; line-height: 1.8; }
        .brand-info div { margin-top: 4px; }
        .brand-right { text-align: right; min-width: 220px; }
        .title { font-size: 0.85rem; letter-spacing: 0.4em; text-transform: uppercase; color: #94a3b8; margin-bottom: 14px; }
        .number { font-size: 2.4rem; font-weight: 900; color: #0f172a; line-height: 1; letter-spacing: -0.02em; }
        .meta { margin-top: 18px; color: #64748b; font-size: 0.95rem; line-height: 1.8; }
        .invoice-body { padding: 28px 32px 32px; }
        .invoice-info { display: grid; grid-template-columns: 1.2fr 0.8fr; gap: 24px; margin-bottom: 28px; }
        .invoice-card { padding: 20px 24px; border: 1px solid #e2e8f0; border-radius: 24px; background: #f8fafc; }
        .invoice-card strong { display: block; font-size: 0.7rem; text-transform: uppercase; letter-spacing: 0.3em; color: #94a3b8; margin-bottom: 10px; }
        .invoice-card p { margin: 0; color: #334155; font-size: 0.95rem; line-height: 1.8; }
        .invoice-card p span { display: block; color: #0f172a; font-weight: 700; margin-top: 8px; }
        .items-table { width: 100%; border-collapse: collapse; margin-bottom: 24px; }
        .items-table th, .items-table td { padding: 14px 16px; font-size: 0.95rem; }
        .items-table th { color: #64748b; font-weight: 700; text-transform: uppercase; letter-spacing: 0.12em; border-bottom: 1px solid #e2e8f0; }
        .items-table td { color: #334155; border-bottom: 1px solid #f1f5f9; }
        .items-table td.amount, .items-table td.text-right { text-align: right; }
        .summary-panel { display: flex; justify-content: flex-end; }
        .summary-box { width: 320px; border: 1px solid #e2e8f0; border-radius: 22px; padding: 20px 24px; background: #f8fafc; }
        .summary-row { display: flex; justify-content: space-between; margin-bottom: 10px; font-size: 0.95rem; color: #475569; }
        .summary-row strong { color: #0f172a; }
        .summary-total { display: flex; justify-content: space-between; border-top: 1px solid #e2e8f0; padding-top: 12px; margin-top: 14px; font-weight: 800; color: #0f172a; }
        .invoice-note { margin-top: 28px; color: #64748b; font-size: 0.9rem; }
        .invoice-footer { margin-top: 32px; display: flex; justify-content: space-between; align-items: center; }
        .signature { border-top: 1px solid #cbd5e1; width: 240px; padding-top: 14px; color: #475569; font-size: 0.82rem; }
        .footer-note { color: #94a3b8; font-size: 0.82rem; }
        @media (max-width: 900px) {
            .invoice-info { grid-template-columns: 1fr; }
            .brand-right { text-align: left; }
            .summary-panel { justify-content: center; }
            .summary-box { width: 100%; }
        }
        @media (max-width: 640px) {
            .invoice-header { padding: 24px 18px 18px; }
            .brand-left, .brand-right { width: 100%; }
        }
    </style>
</head>
<body>

<!-- Action Bar -->
<div class="no-print bg-gradient-to-r from-slate-900 to-slate-800 text-white px-3 sm:px-6 py-2 sm:py-3 flex flex-col sm:flex-row sm:items-center justify-between gap-3 sticky top-0 z-50 shadow-lg border-b border-slate-700">
    <div class="flex items-center gap-4">
        <a href="invoices.php" class="text-slate-300 hover:text-white text-sm transition"><i class="fas fa-arrow-left mr-2"></i>Back to Invoices</a>
        <span class="text-slate-400 text-xs font-mono tracking-wider bg-slate-800 px-3 py-1 rounded-lg"><?= sanitize($inv['invoice_number']) ?></span>
    </div>
    <div class="flex items-center gap-3 flex-wrap">
        <a href="invoice_create.php?clone=<?= $inv['id'] ?>" class="bg-slate-700 hover:bg-slate-600 text-white px-3.5 py-1.5 rounded-lg text-sm font-semibold transition flex items-center gap-1.5">
            <i class="fas fa-copy mr-1"></i>Clone
        </a>
        <a href="pdf_invoice.php?id=<?= $inv['id'] ?>" target="_blank" class="bg-white text-slate-900 hover:bg-slate-100 border border-slate-300 px-3.5 py-1.5 rounded-lg text-sm font-semibold transition flex items-center gap-1.5">
            <i class="fas fa-file-pdf mr-1"></i>Download PDF
        </a>
        <button id="printInvoiceBtn" class="bg-indigo-600 hover:bg-indigo-700 text-white px-3.5 py-1.5 rounded-lg text-sm font-bold transition flex items-center gap-1.5">
            <i class="fas fa-print mr-1"></i>Print
        </button>
        <button id="whatsappInvoiceBtn" data-invoice-id="<?= $inv['id'] ?>" class="bg-emerald-600 hover:bg-emerald-700 text-white px-3.5 py-1.5 rounded-lg text-sm font-bold transition flex items-center gap-1.5">
            <svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4 fill-current" viewBox="0 0 24 24"><path d="M17.472 14.382c-.297-.149-1.758-.867-2.03-.967-.273-.099-.471-.148-.67.15-.197.297-.767.966-.94 1.164-.173.199-.347.223-.644.075-.297-.15-1.255-.463-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.298-.347.446-.52.149-.174.198-.298.298-.497.099-.198.05-.371-.025-.52-.075-.149-.669-1.612-.916-2.207-.242-.579-.487-.5-.669-.51-.173-.008-.371-.01-.57-.01-.198 0-.52.074-.792.372-.272.297-1.04 1.016-1.04 2.479 0 1.462 1.065 2.875 1.213 3.074.149.198 2.096 3.2 5.077 4.487.709.306 1.262.489 1.694.625.712.227 1.36.195 1.871.118.571-.085 1.758-.719 2.006-1.413.248-.694.248-1.289.173-1.413-.074-.124-.272-.198-.57-.347m-5.421 7.403h-.004a9.87 9.87 0 01-5.031-1.378l-.361-.214-3.741.982.998-3.648-.235-.374a9.86 9.86 0 01-1.51-5.26c.001-5.45 4.436-9.884 9.888-9.884 2.64 0 5.122 1.03 6.988 2.898a9.825 9.825 0 012.893 6.994c-.003 5.45-4.437 9.884-9.885 9.884m8.413-18.297A11.815 11.815 0 0012.05 0C5.495 0 .16 5.335.157 11.892c0 2.096.547 4.142 1.588 5.945L.057 24l6.305-1.654a11.882 11.882 0 005.683 1.448h.005c6.554 0 11.89-5.335 11.893-11.893a11.821 11.821 0 00-3.48-8.413z"/></svg>
            WhatsApp
        </button>
    </div>
</div>

<?php
$waInvoiceNumber = $inv['invoice_number'];
$waCustomerName  = $inv['cust_name'];
$waDate          = date('d M Y', strtotime($inv['invoice_date']));
$waTotal         = number_format($inv['total_amount'], 2);
$waStatus        = strtoupper($inv['status']);

$waItemsList = '';
foreach ($lineItems as $idx => $item) {
    $waItemsList .= ($idx + 1) . '. ' . $item['product_name'] . ' (Qty: ' . $item['quantity'] . ') - ' . number_format($item['line_total'], 2) . '\n';
}
?>

<div class="max-w-5xl mx-auto my-6 px-4">
    <div class="invoice-wrapper bg-white rounded-2xl shadow-2xl overflow-hidden border-2 border-slate-200">

        <!-- Professional Header -->
        <div class="invoice-header">
            <div class="invoice-brand">
                <div class="brand-left">
                    <div class="brand-name"><?= APP_NAME ?></div>
                    <div class="brand-tag"><?= sanitize($companyTagline) ?></div>
                    <div class="brand-info">
                        <div><?= nl2br(sanitize($companyAddress)) ?></div>
                        <div>Phone: <?= sanitize($companyPhone) ?></div>
                        <div>Email: <?= sanitize($companyEmail) ?></div>
                    </div>
                </div>
                <div class="brand-right">
                    <div class="title">INVOICE</div>
                    <div class="number"><?= sanitize($inv['invoice_number']) ?></div>
                    <div class="meta">Date: <?= formatDate($inv['invoice_date']) ?></div>
                    <?php if ($inv['due_date']): ?>
                    <div class="meta">Due Date: <?= formatDate($inv['due_date']) ?></div>
                    <?php endif; ?>
                    <div class="meta">Status: <?= sanitize(strtoupper($inv['status'])) ?></div>
                </div>
            </div>
        </div>

        <!-- Customer & Details Section -->
        <div class="px-6 sm:px-10 py-8 grid gap-6 md:grid-cols-3 border-b border-slate-200">
            <div class="rounded-2xl bg-gradient-to-br from-slate-50 to-slate-100 p-6 shadow-sm border border-slate-200">
                <div class="text-xs uppercase tracking-[0.3em] text-slate-500 font-bold mb-3">Bill To</div>
                <div class="mt-3 font-bold text-slate-900 text-lg"><?= sanitize($inv['cust_name']) ?></div>
                <?php if ($inv['cust_address']): ?><div class="text-sm text-slate-600 mt-3 leading-relaxed"><?= nl2br(sanitize($inv['cust_address'])) ?></div><?php endif; ?>
                <div class="text-sm text-slate-600 mt-2"><?= sanitize(implode(', ', array_filter([$inv['cust_city'], $inv['cust_state'], $inv['cust_pincode']]))) ?></div>
                <?php if ($inv['cust_phone']): ?><div class="text-sm text-slate-600 mt-3"><span class="font-semibold">Phone:</span> <?= sanitize($inv['cust_phone']) ?></div><?php endif; ?>
                <?php if ($inv['cust_email']): ?><div class="text-sm text-slate-600 mt-1"><span class="font-semibold">Email:</span> <?= sanitize($inv['cust_email']) ?></div><?php endif; ?>
                <?php if ($inv['cust_gstin']): ?><div class="text-sm text-slate-600 mt-1"><span class="font-semibold">GST ID:</span> <?= sanitize($inv['cust_gstin']) ?></div><?php endif; ?>
            </div>
            <div class="rounded-2xl bg-gradient-to-br from-indigo-50 to-indigo-100 p-6 shadow-sm border border-indigo-200">
                <div class="text-xs uppercase tracking-[0.3em] text-indigo-600 font-bold mb-3">Invoice Information</div>
                <div class="mt-3 space-y-2.5">
                    <div class="flex justify-between">
                        <span class="text-sm text-indigo-700 font-semibold">Date:</span>
                        <span class="text-sm text-indigo-900 font-bold"><?= formatDate($inv['invoice_date']) ?></span>
                    </div>
                    <?php if ($inv['due_date']): ?>
                    <div class="flex justify-between">
                        <span class="text-sm text-indigo-700 font-semibold">Due Date:</span>
                        <span class="text-sm text-indigo-900 font-bold"><?= formatDate($inv['due_date']) ?></span>
                    </div>
                    <?php endif; ?>
                    <div class="flex justify-between items-center">
                        <span class="text-sm text-indigo-700 font-semibold">Status:</span>
                        <?php
                            $statusClass = $inv['status'] === 'paid' ? 'bg-emerald-200 text-emerald-800' : ($inv['status'] === 'pending' ? 'bg-amber-200 text-amber-800' : 'bg-slate-200 text-slate-800');
                        ?>
                        <span class="inline-flex rounded-full <?= $statusClass ?> px-3 py-1 text-xs font-bold uppercase"><?= sanitize($inv['status']) ?></span>
                    </div>
                </div>
            </div>
            <div class="rounded-2xl bg-gradient-to-br from-emerald-50 to-emerald-100 p-6 shadow-sm border border-emerald-200">
                <div class="text-xs uppercase tracking-[0.3em] text-emerald-600 font-bold mb-3">Amount Summary</div>
                <div class="mt-4 space-y-2">
                    <div class="flex justify-between text-sm">
                        <span class="text-emerald-700">Subtotal:</span>
                        <span class="text-emerald-900 font-semibold"><?= formatCurrency($inv['subtotal']) ?></span>
                    </div>
                    <?php if ($inv['discount_amount'] > 0): ?>
                    <div class="flex justify-between text-sm">
                        <span class="text-emerald-700">Discount:</span>
                        <span class="text-amber-600 font-semibold">-<?= formatCurrency($inv['discount_amount']) ?></span>
                    </div>
                    <?php endif; ?>
                    <div class="flex justify-between text-sm">
                        <span class="text-emerald-700">GST:</span>
                        <span class="text-emerald-900 font-semibold"><?= formatCurrency($inv['gst_amount']) ?></span>
                    </div>
                    <div class="border-t-2 border-emerald-300 pt-2 flex justify-between">
                        <span class="text-emerald-900 font-bold">Total:</span>
                        <span class="text-2xl font-black text-emerald-600"><?= formatCurrency($inv['total_amount']) ?></span>
                    </div>
                </div>
            </div>
        </div>

        <div class="px-6 sm:px-10 py-4 sm:py-6 overflow-x-auto">
            <table class="w-full text-sm border-separate border-spacing-y-3">
                <thead>
                    <tr class="text-left text-slate-500 text-xs uppercase tracking-[0.25em]">
                        <th class="px-4 py-3">#</th>
                        <th class="px-4 py-3">Product / Service</th>
                        <th class="text-right px-4 py-3">Qty</th>
                        <th class="text-right px-4 py-3">Unit Price</th>
                        <th class="text-right px-4 py-3">GST%</th>
                        <th class="text-right px-4 py-3">Amount</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($lineItems as $i => $item): ?>
                    <tr class="rounded-3xl bg-slate-50 shadow-sm">
                        <td class="px-4 py-4 text-slate-600"><?= $i + 1 ?></td>
                        <td class="px-4 py-4 font-semibold text-slate-900"><?= sanitize($item['product_name']) ?></td>
                        <td class="text-right px-4 py-4 text-slate-600"><?= (int)$item['quantity'] ?></td>
                        <td class="text-right px-4 py-4 text-slate-600"><?= formatCurrency($item['unit_price']) ?></td>
                        <td class="text-right px-4 py-4 text-slate-600"><?= number_format($item['gst_percent'], 2) ?>%</td>
                        <td class="text-right px-4 py-4 font-bold text-slate-900"><?= formatCurrency($item['line_total']) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        </div>

        <!-- Summary & Notes -->
        <div class="px-6 sm:px-10 py-8 bg-slate-50 border-t border-slate-200">
            <div class="grid md:grid-cols-3 gap-8">
                <!-- Signature Area -->
                <div class="md:col-span-2 space-y-8">
                    <?php if ($inv['notes']): ?>
                    <div class="bg-white rounded-xl p-5 border border-slate-200">
                        <div class="text-xs font-bold uppercase tracking-widest text-slate-500 mb-3">Notes & Terms</div>
                        <p class="text-sm text-slate-700 leading-relaxed"><?= nl2br(sanitize($inv['notes'])) ?></p>
                    </div>
                    <?php endif; ?>
                    <div class="grid grid-cols-2 gap-6 pt-4 border-t border-slate-200">
                        <div>
                            <div class="text-xs font-bold uppercase tracking-widest text-slate-500 mb-12">Authorized By</div>
                            <div class="border-t-2 border-slate-900 pt-2 w-32"></div>
                            <div class="text-xs text-slate-600 mt-1 font-semibold">Signature</div>
                        </div>
                        <div class="text-right">
                            <div class="text-xs font-bold uppercase tracking-widest text-slate-500 mb-12">Customer Approval</div>
                            <div class="border-t-2 border-slate-900 pt-2 w-32 ml-auto"></div>
                            <div class="text-xs text-slate-600 mt-1 font-semibold">Signature</div>
                        </div>
                    </div>
                </div>
                <!-- Final Summary -->
                <div class="bg-white rounded-2xl p-6 shadow-md border-2 border-emerald-200 h-fit">
                    <div class="text-xs uppercase tracking-[0.3em] text-emerald-700 font-bold mb-4">Final Amount</div>
                    <div class="space-y-3">
                        <div class="flex justify-between text-sm">
                            <span class="text-slate-600">Subtotal</span>
                            <span class="text-slate-900 font-semibold"><?= formatCurrency($inv['subtotal']) ?></span>
                        </div>
                        <?php if ($inv['discount_amount'] > 0): ?>
                        <div class="flex justify-between text-sm">
                            <span class="text-slate-600">Discount</span>
                            <span class="text-amber-600 font-semibold">-<?= formatCurrency($inv['discount_amount']) ?></span>
                        </div>
                        <?php endif; ?>
                        <div class="flex justify-between text-sm border-b pb-3 border-slate-200">
                            <span class="text-slate-600">GST (Incl.)</span>
                            <span class="text-slate-900 font-semibold"><?= formatCurrency($inv['gst_amount']) ?></span>
                        </div>
                        <div class="flex justify-between items-baseline">
                            <span class="text-slate-900 font-bold uppercase text-sm">Total Due</span>
                            <span class="text-3xl font-black text-emerald-600"><?= formatCurrency($inv['total_amount']) ?></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Professional Footer -->
        <div class="px-6 sm:px-10 py-6 bg-gradient-to-r from-slate-900 to-slate-800 text-center border-t border-slate-200">
            <p class="text-xs text-slate-300 mb-1">Thank you for your business!</p>
            <p class="text-xs text-slate-400 tracking-wider">Generated by <?= APP_NAME ?> on <?= date('d M Y \a\t H:i') ?> | Customer Ref: <?= sanitize($inv['id']) ?></p>
            <p class="text-xs text-slate-500 mt-3">For inquiries, contact us at <?= sanitize($companyPhone) ?> or <?= sanitize($companyEmail) ?></p>
        </div>
    </div>
</div>
<script src="<?= $basePath ?>assets/js/invoice-view.js"></script>
</body>
</html>
