<?php
if (!defined('INSTALLED')) require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/includes/db.php';
require_once dirname(__DIR__) . '/includes/functions.php';
startSecureSession();
requireAdmin();

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

$inv = Database::fetchOne("SELECT i.*, c.company_name, c.contact_name, c.email AS cust_email, c.phone AS cust_phone, c.address AS cust_address, c.city AS cust_city, c.ntn AS cust_ntn, c.gst_number AS cust_gst FROM invoices i LEFT JOIN customers c ON i.customer_id=c.id WHERE i.id=?", [$id]);
if (!$inv) { header('Location: /admin/invoices.php'); exit; }

$items = Database::fetchAll("SELECT * FROM invoice_items WHERE invoice_id=? ORDER BY id", [$id]);

$co      = setting('company_name', 'Rig N Dig');
$coAddr  = setting('address', 'Industrial Area, Islamabad, Pakistan');
$coPhone = setting('phone', '');
$coEmail = setting('email', '');
$coNTN   = setting('ntn_number', '');
$coGST   = setting('gst_number', '');
$logo    = setting('logo', '');
$watermark = setting('watermark', '');
$bankName    = setting('bank_name', '');
$bankAccount = setting('bank_account', '');
$bankIban    = setting('bank_iban', '');

$billName = $inv['company_name'] ?: $inv['contact_name'];
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Refined Invoice <?= e($inv['invoice_number']) ?></title>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;600;700;800&family=Rajdhani:wght@600;700&display=swap" rel="stylesheet">
<style>
:root {
    --navy: #0a122a;
    --orange: #ff6b00;
    --gray-bg: #f8f9fc;
    --text-main: #1e293b;
    --text-muted: #64748b;
}

*{margin:0;padding:0;box-sizing:border-box; -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important;}
body{font-family:'Inter', sans-serif; background:#e2e8f0; color:var(--text-main); font-size:9pt; line-height:1.4;}

/* Printing Controls */
.print-bar{position:fixed;top:0;left:0;right:0;background:var(--navy);padding:10px 24px;display:flex;gap:12px;justify-content:flex-end;z-index:999;box-shadow:0 4px 12px rgba(0,0,0,0.2);}
.print-bar button{padding:6px 16px;border:none;border-radius:6px;font-size:8.5pt;font-weight:700;cursor:pointer;transition:all 0.2s;}
.btn-pdf{background:var(--orange);color:#fff;}
.btn-pdf:hover{background:#e65a00; transform:translateY(-1px);}
.btn-cls{background:#334155;color:#fff;}

/* A4 Page Layout */
.page{width:210mm; min-height:297mm; background:#fff; margin:60px auto 40px; position:relative; overflow:hidden; box-shadow:0 20px 50px rgba(0,0,0,0.15);}

/* Decorative Accents */
.accent-line{position:absolute; top:0; left:0; width:100%; height:8px; background:var(--orange); border-bottom:4px solid var(--navy);}
.corner-accent{position:absolute; top:0; right:0; width:80px; height:80px; background:var(--navy); clip-path: polygon(100% 0, 0 0, 100% 100%); z-index:1;}

.inner{padding:12mm 15mm 10mm; position:relative; z-index:2;}

/* Header Section */
.header-grid{display:grid; grid-template-columns: 1.5fr 1fr; gap:15px; margin-bottom:10mm;}

.brand-area .logo-box img{max-height:135px; max-width:100%; object-fit:contain; margin-bottom:3mm;}
.brand-area .co-details{font-size:7.5pt; color:var(--text-muted); line-height:1.3;}

.title-area{text-align:right;}
.title-area .doc-type{font-family:'Rajdhani', sans-serif; font-size:42pt; font-weight:800; color:var(--navy); line-height:0.8; margin-bottom:4px; letter-spacing:-1px;}
.title-area .doc-type span{color:var(--orange);}
.title-area .doc-id{font-size:11pt; font-weight:700; color:var(--text-muted); text-transform:uppercase; letter-spacing:2px;}

/* Address & Meta Boxes */
.info-section{display:grid; grid-template-columns: repeat(3, 1fr); gap:8mm; margin-bottom:8mm;}

.info-block h4{font-size:6.5pt; font-weight:800; text-transform:uppercase; color:var(--orange); letter-spacing:1px; margin-bottom:5px; border-bottom:1px solid #edf2f7; padding-bottom:3px;}
.info-block p{font-size:8.5pt; font-weight:700; color:var(--navy); line-height:1.2;}
.info-block .sub-text{font-size:7.5pt; font-weight:400; color:var(--text-muted); margin-top:1px;}

/* Items Table */
.table-container{margin-bottom:6mm; border-radius:8px; overflow:hidden; border:1px solid #f1f5f9; background:#fff;}
.items-table{width:100%; border-collapse:collapse;}
.items-table thead{background:var(--navy);}
.items-table th{padding:10px 14px; font-size:7.5pt; font-weight:700; color:#fff; text-transform:uppercase; letter-spacing:0.8px; text-align:left;}
.items-table th.right{text-align:right;}

.items-table td{padding:10px 14px; font-size:8.5pt; color:var(--text-main); border-bottom:1px solid #f1f5f9; vertical-align:middle;}
.items-table tr:nth-child(even){background:#fbfcfd;}
.items-table td.right{text-align:right; font-weight:700; color:var(--navy);}

.description-main{font-weight:700; color:var(--navy); display:block; margin-bottom:1px; font-size:8.5pt;}
.description-sub{font-size:7.5pt; color:var(--text-muted); font-weight:400;}

/* Footer Section */
.footer-grid{display:grid; grid-template-columns: 1.5fr 1fr; gap:25px;}

.payment-box{background:var(--gray-bg); padding:16px; border-radius:10px; border-left:4px solid var(--orange);}
.payment-box h5{font-size:7.5pt; font-weight:800; color:var(--navy); text-transform:uppercase; margin-bottom:8px;}
.payment-box table{width:100%; font-size:8pt;}
.payment-box td{padding:1px 0; color:var(--text-muted);}
.payment-box td:first-child{font-weight:700; color:var(--navy); width:90px;}

.summary-box{text-align:right;}
.summary-table{width:100%; margin-left:auto;}
.summary-table td{padding:4px 0; font-size:8.5pt;}
.summary-table td:last-child{text-align:right; font-weight:700; color:var(--navy); width:110px; padding-left:12px;}
.summary-table .grand-total{border-top:2px solid var(--navy); padding-top:8px; margin-top:8px;}
.summary-table .grand-total td{font-size:14pt; font-weight:800; color:var(--orange);}

.notes-area{margin-top:8mm; padding:12px; border-top:1px dashed #cbd5e1;}
.notes-area h6{font-size:7.5pt; font-weight:800; color:var(--navy); margin-bottom:4px; text-transform:uppercase;}
.notes-area p{font-size:7.5pt; color:var(--text-muted); line-height:1.5;}

/* Page Footer Strip */
.page-footer{position:absolute; bottom:0; left:0; width:100%; background:var(--navy); padding:12px 15mm; display:flex; justify-content:space-between; align-items:center;}
.page-footer .contact-info{display:flex; gap:15px; font-size:7.5pt; color:#94a3b8;}
.page-footer .thanks{font-size:7.5pt; font-weight:700; color:var(--orange); text-transform:uppercase; letter-spacing:1px;}

@media print{
  body{background:#fff;}
  .print-bar{display:none;}
  .page{margin:0; box-shadow:none; width:100%;}
  .accent-line{ -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
  .corner-accent{ -webkit-print-color-adjust: exact !important; print-color-adjust: exact !important; }
  @page{size:A4 portrait; margin:0;}
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2pdf.js/0.10.1/html2pdf.bundle.min.js"></script>
<script>
function downloadPDF() {
    const element = document.getElementById('invoice-page');
    // Ensure element is visible and margins are zero for capture
    const originalMargin = element.style.margin;
    const originalShadow = element.style.boxShadow;
    element.style.margin = '0';
    element.style.boxShadow = 'none';

    const opt = {
        margin:       0,
        filename:     'Invoice_<?= $inv['invoice_number'] ?>.pdf',
        image:        { type: 'jpeg', quality: 0.98 },
        html2canvas:  { 
            scale: 2, 
            useCORS: true, 
            scrollY: 0, 
            height: 1122, // Force exact height to stay under A4 limit
            windowHeight: 1122
        },
        jsPDF:        { unit: 'px', format: [793, 1122], orientation: 'portrait' },
        pagebreak:    { mode: 'avoid-all' }
    };
    
    html2pdf().set(opt).from(element).save().then(() => {
        element.style.margin = originalMargin;
        element.style.boxShadow = originalShadow;
    });
}
</script>
<style>
    /* Strict clamping for single page export */
    .page { height: 1122px !important; overflow: hidden !important; border:none !important; }
</style>
<style>
    @media print {
        .page { margin: 0 !important; box-shadow: none !important; width: 100% !important; }
        .print-bar { display: none !important; }
    }
</style>
</head>
<body style="background:#e2e8f0; margin:0; padding:0;">

<div class="print-bar">
    <button class="btn-cls" onclick="window.close()">✕ Close</button>
    <button class="btn-pdf" onclick="downloadPDF()">⬇ Download as PDF</button>
    <button class="btn-pdf" style="background:#475569" onclick="window.print()">🖨 Print</button>
</div>

<div class="page" id="invoice-page" style="margin: 60px auto; background:#fff;">
    <div class="accent-line"></div>
    <div class="corner-accent"></div>

    <?php if ($watermark): ?>
    <div style="position:absolute; inset:0; display:flex; align-items:center; justify-content:center; pointer-events:none; z-index:0; opacity:0.04;">
        <img src="/uploads/<?= e($watermark) ?>" style="width:400px; height:auto; filter:grayscale(100%);">
    </div>
    <?php endif; ?>

    <div class="inner">
        <!-- HEADER -->
        <div class="header-grid">
            <div class="brand-area">
                <div class="logo-box">
                    <?php if ($logo): ?>
                    <img id="main-logo" src="/uploads/<?= e($logo) ?>" alt="<?= e($co) ?>">
                    <?php else: ?>
                    <h2 style="font-size:22pt; font-weight:900; color:var(--navy);"><?= e($co) ?></h2>
                    <?php endif; ?>
                </div>
                <div class="co-details">
                    <div><?= e($coAddr) ?></div>
                    <div><?= e($coPhone) ?> | <?= e($coEmail) ?></div>
                    <?php if ($coNTN): ?><div>NTN: <?= e($coNTN) ?></div><?php endif; ?>
                </div>
            </div>
            <div class="title-area">
                <div class="doc-type">IN<span>VOICE</span></div>
                <div class="doc-id">#<?= e($inv['invoice_number']) ?></div>
            </div>
        </div>

        <!-- CLIENT & META INFO -->
        <div class="info-section">
            <div class="info-block">
                <h4>Bill To</h4>
                <p><?= e($billName) ?></p>
                <div class="sub-text">
                    <?= nl2br(e($inv['cust_address'] ?: 'N/A')) ?><br>
                    <?= e($inv['cust_phone']) ?>
                </div>
            </div>
            <div class="info-block">
                <h4>Document Details</h4>
                <div class="details-row" style="display:flex; justify-content:space-between; font-size:8.5pt; margin-bottom:3px;">
                    <span style="color:var(--text-muted)">Issued Date:</span>
                    <span style="font-weight:700"><?= date('d M Y', strtotime($inv['created_at'])) ?></span>
                </div>
                <div class="details-row" style="display:flex; justify-content:space-between; font-size:8.5pt;">
                    <span style="color:var(--text-muted)">Due Date:</span>
                    <span style="font-weight:700"><?= $inv['due_date'] ? date('d M Y', strtotime($inv['due_date'])) : 'On Receipt' ?></span>
                </div>
            </div>
            <div class="info-block">
                <h4>Status</h4>
                <div style="margin-top:6px;">
                     <span style="background:<?= $inv['status']==='paid'?'#10b981':'#f59e0b' ?>; color:#fff; padding:3px 10px; border-radius:50px; font-size:7.5pt; font-weight:800; text-transform:uppercase;"><?= e($inv['status']) ?></span>
                </div>
            </div>
        </div>

        <!-- ITEMS TABLE -->
        <div class="table-container">
            <table class="items-table">
                <thead>
                    <tr>
                        <th>Item Description</th>
                        <th style="width:70px; text-align:center;">Qty</th>
                        <th style="width:110px;" class="right">Unit Price</th>
                        <th style="width:120px;" class="right">Amount</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($items as $item): ?>
                    <tr>
                        <td>
                            <span class="description-main"><?= e($item['description']) ?></span>
                            <?php if ($item['unit']): ?><span class="description-sub">Unit: <?= e($item['unit']) ?></span><?php endif; ?>
                        </td>
                        <td style="text-align:center; font-weight:700;"><?= number_format($item['quantity'], 2) ?></td>
                        <td class="right"><?= number_format($item['unit_price'], 2) ?></td>
                        <td class="right"><?= number_format($item['total_price'], 2) ?></td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>

        <!-- FOOTER SECTION -->
        <div class="footer-grid">
            <div class="payment-area">
                <div class="payment-box">
                    <h5>Payment Information</h5>
                    <table>
                        <?php if ($bankName): ?><tr><td>Bank:</td><td><?= e($bankName) ?></td></tr><?php endif; ?>
                        <?php if ($bankAccount): ?><tr><td>Account:</td><td><?= e($bankAccount) ?></td></tr><?php endif; ?>
                        <?php if ($bankIban): ?><tr><td>IBAN:</td><td><?= e($bankIban) ?></td></tr><?php endif; ?>
                    </table>
                </div>
                
                <?php if ($inv['notes'] || setting('invoice_terms')): ?>
                <div class="notes-area">
                    <h6>Notes & Conditions</h6>
                    <p><?= nl2br(e($inv['notes'] ?: setting('invoice_terms'))) ?></p>
                </div>
                <?php endif; ?>
            </div>

            <div class="summary-area">
                <table class="summary-table">
                    <tr>
                        <td style="color:var(--text-muted)">Sub Total</td>
                        <td><?= number_format($inv['subtotal'], 2) ?></td>
                    </tr>
                    <?php if ($inv['tax_amount'] > 0): ?>
                    <tr>
                        <td style="color:var(--text-muted)">Tax GST (<?= $inv['tax_rate'] ?>%)</td>
                        <td><?= number_format($inv['tax_amount'], 2) ?></td>
                    </tr>
                    <?php endif; ?>
                    <tr class="grand-total">
                        <td>Total Amount</td>
                        <td>PKR <?= number_format($inv['total'], 2) ?></td>
                    </tr>
                </table>

                <div style="margin-top:15mm; text-align:center;">
                    <div style="width:160px; border-bottom:1.5px solid var(--navy); margin-left:auto; margin-bottom:4px;"></div>
                    <div style="font-size:7pt; color:var(--text-muted); text-transform:uppercase; font-weight:700;">Authorized Signature</div>
                </div>
            </div>
        </div>
    </div>

    <!-- PAGE FOOTER STRIP -->
    <div class="page-footer">
        <div class="contact-info">
            <span>📞 <?= e($coPhone) ?></span>
            <span>✉ <?= e($coEmail) ?></span>
            <span>🌐 RigNDig.com</span>
        </div>
        <div class="thanks">Industrial Excellence</div>
    </div>
</div>

<script>
// Auto-print disabled for user choice
</script>
</body>
</html>
