<?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/Quotation.php';

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

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

$quotationId = isset($_GET['quotation_id']) ? (int)$_GET['quotation_id'] : ($_SESSION['quotation_data']['quotation_id'] ?? null);
if (!$quotationId) {
    header('Location: create_quotation.php?error=' . urlencode('No quotation data found.'));
    exit();
}

$quotationData = $quotation->getQuotationById($quotationId);
if (!$quotationData) {
    header('Location: create_quotation.php?error=' . urlencode('Quotation not found.'));
    exit();
}

$creatorId   = $quotationData['created_by'] ?? null;
$creatorName = $creatorId ? ($auth->getUserName($creatorId) ?: 'Unknown') : 'Unknown';

$formattedDate       = (new DateTime($quotationData['created_at']))->format('d M Y');
$formattedValidUntil = (new DateTime($quotationData['valid_until']))->format('d M Y');

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

/* ── Letterhead variables ── */
$docType      = 'QUOTATION';
$docNumber    = $quotationData['quotation_number'];
$docPageTitle = htmlspecialchars(Branding::pageTitle('Quotation #' . $docNumber));
$docNewLink   = ($quotationData['branch_id'] == $auth->getUserBranch($_SESSION['user_id']))
                ? 'create_quotation.php' : '';
$docNewLabel  = 'New Quotation';

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

    <!-- ══ DOCUMENT TITLE ══ -->
    <div class="lh-doc-title">
        <div class="lh-doc-type">Quotation</div>
        <div class="lh-doc-refs">
            <div class="lh-doc-ref-row">
                <span class="lh-doc-ref-lbl">Quotation No</span>
                <span class="lh-doc-ref-val"><?php echo htmlspecialchars($quotationData['quotation_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>

    <!-- ══ QUOTE FOR ══ -->
    <div class="lh-parties">
        <div class="lh-party lh-pto">
            <div class="lh-plabel">Quote For</div>
            <div class="lh-pname"><?php echo htmlspecialchars($quotationData['customer_name']); ?></div>
            <?php if (!empty($quotationData['customer_contact'])): ?>
            <div class="lh-pline">
                <i class="fas fa-phone-alt"></i>
                <span><?php echo htmlspecialchars($quotationData['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 ($quotationData['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($quotationData['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($quotationData['surtax'], 2); ?></span>
            </div>
            <div class="lh-tr grand">
                <span>
                    <span class="g-sub">Quoted Total</span>
                    Total
                </span>
                <span><?php echo $currency; ?>&nbsp;<?php echo number_format($quotationData['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($quotationData['notes'])
                    ? nl2br(htmlspecialchars($quotationData['notes']))
                    : 'Prices are valid for the period stated. Contact us to confirm availability before placing an order.'; ?>
            </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">Subject to stock availability.</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 Acceptance</div>
        </div>
    </div>

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