<?php
require_once __DIR__ . '/../../classes/Branding.php';
$companyLogo   = Branding::logoUrl();
$settings      = Branding::settings();
$vatPercentage = (float)($settings['vat_percentage'] ?? 17.5);
$currency      = htmlspecialchars($settings['currency_code'] ?? 'MWK');

session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../config/database.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Branch.php';
require_once __DIR__ . '/../../classes/Invoice.php';

$database = new Database();
$conn     = $database->getConnection();
$branch   = new Branch($conn);
$auth     = new Auth($conn);
$invoice  = new invoice($conn);

if (!isset($_SESSION['user_id'])) {
    header('Location: ../../login.php');
    exit();
}

$invoiceId = isset($_GET['invoice_id']) ? (int)$_GET['invoice_id'] : ($_SESSION['invoice_data']['invoice_id'] ?? null);
if (!$invoiceId) {
    header('Location: create_invoice.php?error=' . urlencode('No invoice data found.'));
    exit();
}

$invoiceData = $invoice->getinvoiceById($invoiceId);
if (!$invoiceData) {
    header('Location: create_invoice.php?error=' . urlencode('Invoice not found.'));
    exit();
}

$isProforma = ($_GET['document_type'] ?? '') === 'proforma';
$documentHeading = $isProforma ? 'Proforma Invoice' : 'Invoice';

$creatorId           = $invoiceData['created_by'] ?? null;
$creatorName         = $creatorId ? ($auth->getUserName($creatorId) ?: 'Unknown') : 'Unknown';
$formattedDate       = (new DateTime($invoiceData['created_at']))->format('d M Y');
$formattedValidUntil = (new DateTime($invoiceData['valid_until']))->format('d M Y');

$documentBranch = $branch->getBranchById((int)($invoiceData['branch_id'] ?? 0));
$co = Branding::documentDetailsForBranch($documentBranch);

/* ── Letterhead variables ── */
$docType      = strtoupper($documentHeading);
$docNumber    = $invoiceData['invoice_number'];
$docPageTitle = htmlspecialchars(Branding::pageTitle($documentHeading . ' #' . $docNumber));
$docNewLink   = ($invoiceData['branch_id'] == $auth->getUserBranch($_SESSION['user_id']))
                ? 'create_invoice.php' : '';
$docNewLabel  = 'New Invoice';

require __DIR__ . '/_lh_top.php';
?>

    <!-- ══ DOCUMENT TITLE ══ -->
    <div class="lh-doc-title">
        <div class="lh-doc-type"><?php echo htmlspecialchars($documentHeading); ?></div>
        <div class="lh-doc-refs">
            <div class="lh-doc-ref-row">
                <span class="lh-doc-ref-lbl">Invoice No</span>
                <span class="lh-doc-ref-val"><?php echo htmlspecialchars($invoiceData['invoice_number']); ?></span>
            </div>
            <div class="lh-doc-ref-row">
                <span class="lh-doc-ref-lbl">Date Issued</span>
                <span class="lh-doc-ref-val"><?php echo $formattedDate; ?></span>
            </div>
        </div>
    </div>

    <!-- ══ BILL TO ══ -->
    <div class="lh-parties">
        <div class="lh-party lh-pto">
            <div class="lh-plabel">Bill To</div>
            <div class="lh-pname"><?php echo htmlspecialchars($invoiceData['customer_name']); ?></div>
            <?php if (!empty($invoiceData['customer_contact'])): ?>
            <div class="lh-pline">
                <i class="fas fa-phone-alt"></i>
                <span><?php echo htmlspecialchars($invoiceData['customer_contact']); ?></span>
            </div>
            <?php endif; ?>
        </div>
    </div>


    <!-- ══ LINE ITEMS ══ -->
    <div class="lh-table-wrap">
        <table class="lh-table">
            <thead>
                <tr>
                    <th style="width:34px">#</th>
                    <th>Item / Description</th>
                    <th class="c" style="width:64px">Qty</th>
                    <th class="r" style="width:130px">Unit Price (<?php echo $currency; ?>)</th>
                    <th class="r" style="width:130px">Amount (<?php echo $currency; ?>)</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($invoiceData['items'] as $i => $item):
                    $lineTotal = $item['quantity'] * $item['unit_price'];
                ?>
                <tr>
                    <td><span class="lh-rn"><?php echo $i + 1; ?></span></td>
                    <td class="desc"><?php echo htmlspecialchars($item['item_name']); ?></td>
                    <td class="c"><?php echo htmlspecialchars($item['quantity']); ?></td>
                    <td class="r"><?php echo number_format($item['unit_price'], 2); ?></td>
                    <td class="r amt"><?php echo number_format($lineTotal, 2); ?></td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- ══ TOTALS ══ -->
    <div class="lh-totals-wrap">
        <div class="lh-totals">
            <div class="lh-tr">
                <span>Subtotal</span>
                <span><?php echo $currency; ?>&nbsp;<?php echo number_format($invoiceData['subtotal'], 2); ?></span>
            </div>
            <div class="lh-tr">
                <span>VAT (<?php echo number_format($vatPercentage, 2); ?>%)</span>
                <span><?php echo $currency; ?>&nbsp;<?php echo number_format($invoiceData['surtax'], 2); ?></span>
            </div>
            <div class="lh-tr grand">
                <span>
                    <span class="g-sub">Amount Due</span>
                    Total
                </span>
                <span><?php echo $currency; ?>&nbsp;<?php echo number_format($invoiceData['total_amount'], 2); ?></span>
            </div>
        </div>
    </div>

    <!-- ══ NOTES + VALIDITY ══ -->
    <div class="lh-bottom">
        <div class="lh-notes">
            <div class="lh-notes-lbl">Notes &amp; Terms</div>
            <div class="lh-notes-txt">
                <?php echo !empty($invoiceData['notes'])
                    ? nl2br(htmlspecialchars($invoiceData['notes']))
                    : 'Thank you for choosing our services. Payment is due by the date indicated above.'; ?>
            </div>
        </div>
        <div class="lh-validity">
            <div class="lh-validity-lbl">Valid Until</div>
            <div class="lh-validity-date"><?php echo $formattedValidUntil; ?></div>
            <div class="lh-validity-note">Terms &amp; conditions apply.</div>
        </div>
    </div>

    <!-- ══ SIGNATURES ══ -->
    <div class="lh-sig">
        <div class="lh-sig-slot">
            <div class="lh-sig-line"></div>
            <div class="lh-sig-lbl">Authorised Signature</div>
        </div>
        <div class="lh-sig-slot">
            <div class="lh-sig-line"></div>
            <div class="lh-sig-lbl">Customer Acknowledgement</div>
        </div>
    </div>

<?php if ($isProforma && isset($_GET['print'])): ?>
<script>
    window.addEventListener('load', function () {
        window.print();
    });
</script>
<?php endif; ?>

<?php require __DIR__ . '/_lh_bottom.php'; ?>
