<?php
if (basename(__FILE__) === basename($_SERVER['SCRIPT_FILENAME'] ?? '')) { http_response_code(403); exit('Forbidden'); }
function render_quotation(int $id, bool $pdf = false, string $mode = 'customer', bool $isPublicShare = false): string
{
    $user = current_user();
    $internal = !$isPublicShare && $mode === 'internal' && in_array($user['role'] ?? '', ['admin', 'sales'], true);
    $stmt = db()->prepare('SELECT q.*, c.customer_name, c.phone, c.email, c.address, c.location, u.name prepared_by, u.role as creator_role FROM quotations q JOIN customers c ON c.id=q.customer_id JOIN users u ON u.id=q.created_by WHERE q.id=?');
    $stmt->execute([$id]); $q = $stmt->fetch();
    if (!$q || (!$isPublicShare && (($user['role'] ?? '') !== 'admin' && (int)$q['created_by'] !== ($user['id'] ?? 0)))) { 
        http_response_code(403); return 'Quotation not found or permission denied.'; 
    }
    $stmt = db()->prepare('SELECT * FROM quotation_items WHERE quotation_id=? ORDER BY id'); $stmt->execute([$id]); $items = $stmt->fetchAll();
    $stmt = db()->prepare('SELECT * FROM quotation_loads WHERE quotation_id=? ORDER BY id'); $stmt->execute([$id]); $loads = $stmt->fetchAll();
    $stmt = db()->prepare('SELECT * FROM quotation_import_items WHERE quotation_id=? ORDER BY id'); $stmt->execute([$id]); $importItems = $stmt->fetchAll();
    $company = get_company_info();
    $logoSrc = get_quotation_logo_url($pdf);
    if (!$internal && !empty($q['has_imported_materials'])) {
        return render_imported_customer_quotation($q, $items, $importItems, $company, $logoSrc, $pdf);
    }
    ob_start();
?>
<!doctype html><html><head><meta charset="utf-8"><title><?= e($q['quotation_no']) ?></title>
<style>
@page{size:A4;margin:10mm}
body{font-family:Arial,sans-serif;color:#1f2937;margin:0;background:#f3f6f4;font-size:12px;line-height:1.35}.sheet{position:relative;width:210mm;min-height:297mm;margin:20px auto;background:#fff;padding:14mm;box-sizing:border-box}.head{display:table;width:100%;border-bottom:3px solid #0b7a34;padding-bottom:12px}.company{display:table-cell;vertical-align:middle}.logo{width:54px;height:54px;border-radius:10px;background:#fff;border:1px solid #dfe7e2;text-align:center;line-height:54px;float:left;margin-right:10px;overflow:hidden}.logo img{max-width:54px;max-height:54px;vertical-align:middle}.logo-fallback{background:#0b7a34;color:#fff;font-size:26px;font-weight:700}.meta{display:table-cell;text-align:right;vertical-align:top}.grid{display:table;width:100%;border-spacing:10px;margin:12px -10px}.grid .box{display:table-cell;width:50%;vertical-align:top}.box{border:1px solid #dfe7e2;border-radius:8px;padding:10px;page-break-inside:avoid}.mini-grid{display:table;width:100%;border-spacing:8px;margin:8px -8px}.mini-grid .mini{display:table-cell;width:25%;border:1px solid #dfe7e2;background:#f8faf9;padding:8px;vertical-align:top}.mini span{display:block;color:#6b7280;font-size:9px}.mini strong{font-size:12px}h1,h2,h3{margin:0 0 6px;color:#0b7a34}h1{font-size:24px}h2{font-size:19px}h3{font-size:14px}table{width:100%;border-collapse:collapse;margin-top:8px;table-layout:fixed;page-break-inside:auto}tr{page-break-inside:avoid;page-break-after:auto}th,td{border:1px solid #dfe7e2;padding:5px 4px;font-size:9px;text-align:left;vertical-align:top;overflow-wrap:break-word;word-wrap:break-word}th{background:#eaf6ee}.items-table th:nth-child(1),.items-table td:nth-child(1){width:5%}.items-table th:nth-child(2),.items-table td:nth-child(2){width:11%}.items-table th:nth-child(3),.items-table td:nth-child(3){width:16%}.items-table th:nth-child(4),.items-table td:nth-child(4){width:20%}.items-table th:nth-child(5),.items-table td:nth-child(5){width:9%}.items-table th:nth-child(6),.items-table td:nth-child(6){width:10%}.items-table th:nth-child(7),.items-table td:nth-child(7){width:6%}.items-table th:nth-child(8),.items-table td:nth-child(8){width:6%}.items-table th:nth-child(9),.items-table td:nth-child(9){width:9%}.items-table th:nth-child(10),.items-table td:nth-child(10){width:8%}.summary{margin-left:auto;width:70mm;page-break-inside:avoid}.summary th,.summary td{font-size:11px;padding:6px}.sign{display:table;width:100%;border-spacing:25px;margin-top:35px;page-break-inside:avoid}.sign>div{display:table-cell;width:50%}.line{border-top:1px solid #111;padding-top:8px;text-align:center}.actions{position:sticky;top:0;background:#fff;padding:12px;text-align:center;box-shadow:0 4px 16px rgba(0,0,0,.08)}.btn{background:#0b7a34;color:#fff;padding:10px 16px;border-radius:8px;text-decoration:none;border:0}.pdf body,.pdf .sheet{background:#fff}.pdf .sheet{width:auto;min-height:auto;margin:0;padding:0}.pdf .actions{display:none}@media print{.actions{display:none}body{background:#fff}.sheet{width:auto;min-height:auto;margin:0;padding:0;box-shadow:none}}
.watermark{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%) rotate(-45deg);font-size:120px;font-weight:bold;color:#e2e8f0;z-index:0;pointer-events:none;white-space:nowrap;user-select:none;opacity:0.6}
</style></head><body class="<?= $pdf ? 'pdf' : '' ?>">
<?php 
$showBranding = (($q['creator_role'] ?? '') === 'visitor' && get_setting('visitor_branding', '1') === '1');
if (!$pdf): ?><div class="actions"><button class="btn" onclick="window.print()">Print <?= $internal ? 'Internal Costing' : 'Customer Quotation' ?></button></div><?php endif; ?>
<div class="sheet">
<?php if ($showBranding): ?><div class="watermark">EMS SOFTZ</div><?php endif; ?>
<div class="head"><div class="company"><div class="logo <?= $logoSrc === '' ? 'logo-fallback' : '' ?>"><?php if ($logoSrc !== ''): ?><img src="<?= e($logoSrc) ?>" alt="<?= e($company['name']) ?>"><?php else: ?>F<?php endif; ?></div><div><h1><?= e($company['name']) ?></h1><div><?= e($company['address']) ?><br><?= e($company['phone']) ?> | <?= e($company['email']) ?></div></div></div><div class="meta"><h2>Quotation</h2><strong><?= e($q['quotation_no']) ?></strong><br>Date: <?= e(date('Y-m-d', strtotime($q['created_at']))) ?><br>Status: <?= e(ucfirst($q['status'])) ?></div></div>
<div class="grid"><div class="box"><h3>Customer Information</h3><strong><?= e($q['customer_name']) ?></strong><br><?= e($q['phone']) ?><br><?= e($q['email']) ?><br><?= e($q['location']) ?><br><?= nl2br(e($q['address'])) ?></div><div class="box"><h3>Site & System</h3>System Type: <?= e($q['system_type']) ?><br>Calculation Method: <?= e($q['calculation_method']) ?><br>Site Type: <?= e($q['site_type']) ?><br>Installation Area: <?= e($q['installation_area']) ?><br>Panel Mounting: <?= e($q['panel_mounting']) ?></div></div>
<?php if ($loads && $q['calculation_method'] === 'Load Calculation'): ?><h3>Load Calculation Details</h3><table><thead><tr><th>SL</th><th>Load</th><th>Qty</th><th>Watt</th><th>Backup</th><th>Total Watt</th><th>Watt Hour</th></tr></thead><tbody><?php foreach ($loads as $i=>$l): ?><tr><td><?= $i+1 ?></td><td><?= e($l['load_name']) ?></td><td><?= e((string)$l['qty']) ?></td><td><?= e((string)$l['watt_rating']) ?></td><td><?= e((string)$l['backup_when_no_sun']) ?></td><td><?= e((string)$l['total_watt']) ?></td><td><?= e((string)$l['watt_hour']) ?></td></tr><?php endforeach; ?></tbody></table><?php endif; ?>
<?php if ($internal && !empty($q['has_imported_materials']) && $importItems): ?><h3>Imported Materials</h3><table><thead><tr><th>SL</th><th>Item / Job Head</th><th>Specification</th><th>Brand</th><th>Model</th><th>Qty</th><th>Unit</th><th>FOB Rate USD</th><th>FOB Total USD</th></tr></thead><tbody><?php foreach ($importItems as $i=>$it): ?><tr><td><?= $i+1 ?></td><td><?= e($it['item_head']) ?></td><td><?= e($it['specification']) ?></td><td><?= e($it['brand']) ?></td><td><?= e($it['model']) ?></td><td><?= e((string)$it['qty']) ?></td><td><?= e($it['unit']) ?></td><td><?= money((float)$it['fob_rate_usd']) ?></td><td><?= money((float)$it['fob_total_usd']) ?></td></tr><?php endforeach; ?></tbody></table><?php endif; ?>
<h3>BOQ Item List</h3><table class="items-table"><thead><tr><th>SL</th><th>Product Category</th><th>Product</th><th>Description / Specification</th><th>Brand</th><th>Model</th><th>Qty</th><th>Unit</th><th>Rate</th><th>Total</th></tr></thead><tbody><?php $sl=1; foreach ($items as $it): ?><tr><td><?= $sl++ ?></td><td><?= e($it['product_category']) ?></td><td><?= e($it['product_name']) ?></td><td><?= e($it['description']) ?></td><td><?= e($it['brand']) ?></td><td><?= e($it['model']) ?></td><td><?= e((string)$it['qty']) ?></td><td><?= e($it['unit']) ?></td><td><?= money((float)$it['unit_price']) ?></td><td><?= money((float)$it['total']) ?></td></tr><?php endforeach; ?></tbody></table>
<?php if (!empty($q['has_imported_materials'])): ?>
    <?php if ($internal): ?>
        <div class="box" style="margin-top:20px"><h3>Import Cost Summary</h3>Imported Materials Subtotal USD: <?= money((float)$q['import_subtotal_usd']) ?><br>Master LC Processing Fee (<?= e((string)$q['lc_fee_percent']) ?>%): <?= money((float)$q['lc_fee_usd']) ?> USD<br>Freight Charge USD: <?= money((float)$q['freight_usd']) ?><br>Insurance USD: <?= money((float)$q['insurance_usd']) ?><br>Other Import Cost USD: <?= money((float)$q['other_import_cost_usd']) ?><br>Total Import Cost USD: <?= money((float)$q['total_import_cost_usd']) ?><br>Dollar Rate BDT: <?= money((float)$q['dollar_rate']) ?><br>Total Import Cost BDT: <?= money((float)$q['total_import_cost_bdt']) ?></div>
        <div class="box" style="margin-top:20px"><h3>Local Cost Summary</h3>Local Subtotal Excluding VAT & AIT: <?= money((float)$q['local_subtotal_excluding_tax']) ?><br>AIT (<?= e((string)$q['ait_percent']) ?>%): <?= money((float)$q['ait_amount']) ?><br>VAT (<?= e((string)$q['vat_percent']) ?>%): <?= money((float)$q['vat_amount']) ?><br>Local Total Including VAT & AIT: <?= money((float)$q['local_total_including_tax']) ?></div>
        <div class="box" style="margin-top:20px"><h3>Final Project Summary</h3>Total Import + Local Excluding VAT & AIT: <?= money((float)$q['total_excluding_vat_ait']) ?><br>Total Import + Local Including VAT & AIT: <?= money((float)$q['total_including_vat_ait']) ?><br>Margin (<?= e((string)$q['margin_percent']) ?>%): <?= money((float)$q['margin_amount']) ?><br>Final Quotation Amount: <strong><?= money((float)$q['final_quotation_amount']) ?></strong><br><?= e($q['import_tax_note'] ?? '') ?></div>
        <div class="box" style="margin-top:20px"><h3>Cost per Watt / kW</h3>DC Capacity: <?= money((float)$q['dc_capacity_kwp']) ?> kWp<br>AC Capacity: <?= money((float)$q['ac_capacity_kw']) ?> kW<br>Cost per Watt Excluding VAT & AIT: <?= (float)($q['cost_per_watt_excluding_tax'] ?? 0) > 0 ? money((float)$q['cost_per_watt_excluding_tax']) : 'N/A' ?><br>Cost per Watt Including VAT & AIT: <?= (float)($q['cost_per_watt_including_tax'] ?? 0) > 0 ? money((float)$q['cost_per_watt_including_tax']) : 'N/A' ?><br>Cost per kW Excluding VAT & AIT: <?= (float)($q['cost_per_kw_excluding_tax'] ?? 0) > 0 ? money((float)$q['cost_per_kw_excluding_tax']) : 'N/A' ?><br>Cost per kW Including VAT & AIT: <?= (float)($q['cost_per_kw_including_tax'] ?? 0) > 0 ? money((float)$q['cost_per_kw_including_tax']) : 'N/A' ?></div>
    <?php else: ?>
        <table class="summary"><tr><th>Subtotal</th><td><?= money((float)$q['local_subtotal_excluding_tax']) ?></td></tr><?php if ((float)$q['ait_amount'] > 0): ?><tr><th>AIT (<?= e((string)$q['ait_percent']) ?>%)</th><td><?= money((float)$q['ait_amount']) ?></td></tr><?php endif; ?><tr><th>VAT (<?= e((string)$q['vat_percent']) ?>%)</th><td><?= money((float)$q['vat_amount']) ?></td></tr><tr><th>Grand Total</th><td><strong><?= money((float)$q['grand_total']) ?></strong></td></tr></table>
        <?php if (!empty($q['show_cost_per_watt_on_pdf'])): ?><div class="box" style="margin-top:20px"><h3>Cost per Watt / kW</h3>DC Capacity: <?= money((float)$q['dc_capacity_kwp']) ?> kWp<br>AC Capacity: <?= money((float)$q['ac_capacity_kw']) ?> kW<br>Cost per Watt Excluding VAT & AIT: <?= (float)($q['cost_per_watt_excluding_tax'] ?? 0) > 0 ? money((float)$q['cost_per_watt_excluding_tax']) : 'N/A' ?><br>Cost per Watt Including VAT & AIT: <?= (float)($q['cost_per_watt_including_tax'] ?? 0) > 0 ? money((float)$q['cost_per_watt_including_tax']) : 'N/A' ?><br>Cost per kW Excluding VAT & AIT: <?= (float)($q['cost_per_kw_excluding_tax'] ?? 0) > 0 ? money((float)$q['cost_per_kw_excluding_tax']) : 'N/A' ?><br>Cost per kW Including VAT & AIT: <?= (float)($q['cost_per_kw_including_tax'] ?? 0) > 0 ? money((float)$q['cost_per_kw_including_tax']) : 'N/A' ?></div><?php endif; ?>
    <?php endif; ?>
<?php else: ?>
<table class="summary"><tr><th>Subtotal</th><td><?= money((float)$q['subtotal']) ?></td></tr><tr><th>VAT (<?= e((string)$q['vat_percent']) ?>%)</th><td><?= money((float)$q['vat_amount']) ?></td></tr><tr><th>Discount</th><td><?= money((float)$q['discount_amount']) ?></td></tr><tr><th>Grand Total</th><td><strong><?= money((float)$q['grand_total']) ?></strong></td></tr></table>
<?php endif; ?>
<div class="box" style="margin-top:20px"><h3>Suggested System</h3>Inverter Needed: <?= money((float)($q['suggested_inverter_kw'] ?? 0)) ?> kW<br>Battery Needed: <?= e($q['battery_spec'] ?? 'Not Required') ?><br>Solar Panel Capacity: <?= money((float)($q['system_capacity_kw'] ?? 0)) ?> kW<br>Structure & Accessories: As per site survey<br>Estimated Cost: <?= money((float)$q['grand_total']) ?></div>
<div class="box" style="margin-top:20px"><h3>Energy & Savings Analysis</h3><div class="mini-grid"><div class="mini"><span>Annual Energy Generated</span><strong><?= money((float)($q['annual_energy_kwh'] ?? 0)) ?> kWh/year</strong></div><div class="mini"><span>Carbon Emission Reduced</span><strong><?= money((float)($q['carbon_reduced_kg'] ?? 0)) ?> kg CO2/year</strong></div><div class="mini"><span>Coal Consumption Reduced</span><strong><?= money((float)($q['coal_reduced_kg'] ?? 0)) ?> kg/year</strong></div><div class="mini"><span>Estimated Payback Period</span><strong><?= (float)($q['payback_period_years'] ?? 0) > 0 ? money((float)$q['payback_period_years']) . ' years' : 'N/A' ?></strong></div></div></div>
<?php if ($q['calculation_method'] === 'Water Pumping'): ?><div class="box" style="margin-top:20px"><h3>Water Pumping Calculation</h3>Pump HP: <?= e((string)$q['pump_hp']) ?> HP<br>Head: <?= e((string)$q['pump_head']) ?> ft<br>Water Demand: <?= e((string)$q['water_demand']) ?> L/day<br>Daily Pumping Energy: <?= money((float)($q['daily_pumping_energy_kwh'] ?? 0)) ?> kWh<br>Suggested Solar Panel Capacity: <?= money((float)($q['system_capacity_kw'] ?? 0)) ?> kW<br>Suggested Inverter/VFD Size: <?= money((float)($q['suggested_inverter_kw'] ?? 0)) ?> kW</div><?php endif; ?>
<div class="box" style="margin-top:20px"><h3>Terms and Conditions</h3><?= nl2br(e($q['terms_conditions'])) ?><br><br><strong>Warranty note:</strong> Product warranty will follow manufacturer policy and Fortunes installation terms.</div>
<div class="sign"><div><div class="line">Prepared by: <?= e($q['prepared_by']) ?></div></div><div><div class="line">Customer Signature</div></div></div>
<div class="sign"><div></div><div><div class="line">Company Authorized Signature</div></div></div>
<?php if ($showBranding): ?>
<div style="text-align:right; font-size:12px; color:#9ca3af; margin-top:24px; font-weight:bold;">Powered by EMS SOFTZ<br><span style="font-size:10px;font-weight:normal">Custom ERP & Business Solutions</span></div>
<?php endif; ?>
</div></body></html>
<?php
    return (string)ob_get_clean();
}

function render_imported_customer_quotation(array $q, array $items, array $importItems, array $company, string $logoSrc, bool $pdf): string
{
    $dcCapacity = (float)($q['dc_capacity_kwp'] ?? 0);
    $totalImportBdt = (float)($q['total_import_cost_bdt'] ?? 0);
    $localExcluding = (float)($q['local_subtotal_excluding_tax'] ?? $q['subtotal'] ?? 0);
    $localIncluding = (float)($q['local_total_including_tax'] ?? 0);
    $projectExcluding = $totalImportBdt + $localExcluding;
    $projectIncluding = $totalImportBdt + $localIncluding;
    $perWattWithout = $dcCapacity > 0 ? $projectExcluding / ($dcCapacity * 1000) : null;
    $perWattWith = $dcCapacity > 0 ? $projectIncluding / ($dcCapacity * 1000) : null;
    $backup = trim((string)($q['battery_spec'] ?? ''));
    $siteCapacity = money($dcCapacity) . ' kWp / ' . (string)$q['system_type'];
    if ($backup !== '' && !in_array(strtolower($backup), ['not required', 'n/a'], true)) {
        $siteCapacity .= ' / Backup: ' . $backup;
    }
    ob_start();
?>
<!doctype html><html><head><meta charset="utf-8"><title><?= e($q['quotation_no']) ?></title>
<style>
@page{size:A4 portrait;margin:10mm}
body{font-family:Arial,sans-serif;color:#1f2937;margin:0;background:#eef3f0;font-size:11px;line-height:1.35}.sheet{position:relative;width:210mm;min-height:297mm;margin:18px auto;background:#fff;padding:12mm;box-sizing:border-box}.pdf body,.pdf .sheet{background:#fff}.pdf .sheet{width:auto;min-height:auto;margin:0;padding:0}.actions{position:sticky;top:0;background:#fff;padding:12px;text-align:center;box-shadow:0 4px 16px rgba(0,0,0,.08)}.btn{background:#0b7a34;color:#fff;padding:10px 16px;border-radius:8px;text-decoration:none;border:0}.head{display:table;width:100%;border-bottom:4px solid #0b7a34;padding-bottom:10px;margin-bottom:10px}.company{display:table-cell;vertical-align:middle}.logo{width:58px;height:58px;border:1px solid #d9e4dd;border-radius:8px;text-align:center;line-height:58px;float:left;margin-right:10px;overflow:hidden;background:#fff}.logo img{max-width:58px;max-height:58px;vertical-align:middle}.logo-fallback{background:#0b7a34;color:#fff;font-size:28px;font-weight:700}.meta{display:table-cell;text-align:right;vertical-align:top}.meta h1{font-size:18px;margin:0 0 6px;color:#0b7a34}.title{background:#f6d85f;border:1px solid #c9a900;padding:8px 10px;font-weight:700;font-size:16px;text-align:center;margin:10px 0 6px}.capacity{border:1px solid #d6e1da;background:#f8faf9;padding:7px 10px;margin-bottom:10px}.section-title{background:#0b7a34;color:#fff;font-weight:700;text-align:center;padding:7px;border:1px solid #0b7a34;margin-top:12px}table{width:100%;border-collapse:collapse;table-layout:fixed}thead{display:table-header-group}tr{page-break-inside:avoid}th,td{border:1px solid #4b5563;padding:5px 4px;vertical-align:top;word-wrap:break-word;overflow-wrap:break-word}th{background:#f6d85f;color:#111827;text-align:center;font-size:9px}.num{text-align:right}.center{text-align:center}.total-row td,.total-row th{font-weight:700;background:#fff8d6}.note{border:1px solid #d6e1da;background:#f8faf9;padding:7px;margin-top:6px}.summary{margin-top:8px;margin-left:auto;width:88mm}.summary th{width:62%;text-align:left}.summary td{text-align:right}.final-summary{margin-top:10px}.final-summary th{background:#0b7a34;color:#fff;text-align:left}.final-summary td{font-weight:700;text-align:right}.final-summary .highlight th,.final-summary .highlight td{background:#f6d85f;color:#111827}.page-break-soft{page-break-before:auto}.sign{display:table;width:100%;border-spacing:24px;margin-top:35px;page-break-inside:avoid}.sign>div{display:table-cell;width:50%}.line{border-top:1px solid #111;padding-top:7px;text-align:center}@media print{.actions{display:none}body{background:#fff}.sheet{width:auto;min-height:auto;margin:0;padding:0}}
.watermark{position:fixed;top:50%;left:50%;transform:translate(-50%,-50%) rotate(-45deg);font-size:120px;font-weight:bold;color:#e2e8f0;z-index:0;pointer-events:none;white-space:nowrap;user-select:none;opacity:0.6}
</style></head><body class="<?= $pdf ? 'pdf' : '' ?>">
<?php 
$showBranding = (($q['creator_role'] ?? '') === 'visitor' && get_setting('visitor_branding', '1') === '1');
if (!$pdf): ?><div class="actions"><button class="btn" onclick="window.print()">Print Customer Quotation</button></div><?php endif; ?>
<div class="sheet">
<?php if ($showBranding): ?><div class="watermark">EMS SOFTZ</div><?php endif; ?>
    <div class="head"><div class="company"><div class="logo <?= $logoSrc === '' ? 'logo-fallback' : '' ?>"><?php if ($logoSrc !== ''): ?><img src="<?= e($logoSrc) ?>" alt="<?= e($company['name']) ?>"><?php else: ?>F<?php endif; ?></div><div><strong style="font-size:20px;color:#0b7a34"><?= e($company['name']) ?></strong><br><?= e($company['address']) ?><br><?= e($company['phone']) ?> | <?= e($company['email']) ?></div></div><div class="meta"><h1>Quotation</h1><strong><?= e($q['quotation_no']) ?></strong><br>Date: <?= e(date('Y-m-d', strtotime((string)$q['created_at']))) ?><br>Status: <?= e(ucfirst((string)$q['status'])) ?></div></div>
    <div class="title">Breakdown Cost For - <?= e($q['customer_name']) ?></div>
    <div class="capacity"><strong>Site Capacity:</strong> <?= e($siteCapacity) ?><br><strong>Customer:</strong> <?= e($q['customer_name']) ?>, <?= e($q['location'] ?? '') ?></div>

    <div class="section-title">Import Part</div>
    <table>
        <thead><tr><th style="width:5%">S/N</th><th style="width:17%">Item / Job Head</th><th style="width:25%">Specification Details</th><th style="width:10%">Brand</th><th style="width:10%">Model</th><th style="width:7%">Qty</th><th style="width:7%">Unit</th><th style="width:9%">FOB Rate<br>(Per Unit USD)</th><th style="width:10%">FOB Total<br>(USD)</th></tr></thead>
        <tbody><?php foreach ($importItems as $i => $it): ?><tr><td class="center"><?= $i + 1 ?></td><td><?= e($it['item_head']) ?></td><td><?= e($it['specification']) ?></td><td><?= e($it['brand']) ?></td><td><?= e($it['model']) ?></td><td class="num"><?= e((string)$it['qty']) ?></td><td class="center"><?= e($it['unit']) ?></td><td class="num"><?= money((float)$it['fob_rate_usd']) ?></td><td class="num"><?= money((float)$it['fob_total_usd']) ?></td></tr><?php endforeach; ?></tbody>
    </table>
    <table class="summary">
        <tr class="total-row"><th>Sub Total</th><td><?= money((float)$q['import_subtotal_usd']) ?> USD</td></tr>
        <tr><th>Master L/C Processing Fee <?= e((string)$q['lc_fee_percent']) ?>%</th><td><?= money((float)$q['lc_fee_usd']) ?> USD</td></tr>
        <tr><th>Freight Charge</th><td><?= money((float)$q['freight_usd']) ?> USD</td></tr>
        <tr class="total-row"><th>Total USD for Import Part Excluding VAT & AIT</th><td><?= money((float)$q['total_import_cost_usd']) ?> USD</td></tr>
        <tr><th>Dollar Rate</th><td><?= money((float)$q['dollar_rate']) ?> BDT/USD</td></tr>
        <tr class="total-row"><th>Total BDT for Import Part</th><td><?= money($totalImportBdt) ?> BDT</td></tr>
    </table>
    <div class="note"><strong>Note:</strong> Import L/C will be opened by the customer under their own company name. Fortunes International will provide full documentation and supplier support.</div>

    <div class="section-title page-break-soft">Local Part</div>
    <table>
        <thead><tr><th style="width:5%">S/N</th><th style="width:17%">Item / Job Head</th><th style="width:25%">Specification Details</th><th style="width:10%">Brand</th><th style="width:10%">Model</th><th style="width:7%">Qty</th><th style="width:7%">Unit</th><th style="width:9%">Rate<br>(BDT)</th><th style="width:10%">Total<br>(BDT)</th></tr></thead>
        <tbody><?php foreach ($items as $i => $it): ?><tr><td class="center"><?= $i + 1 ?></td><td><?= e($it['product_name']) ?></td><td><?= e($it['description']) ?></td><td><?= e($it['brand']) ?></td><td><?= e($it['model']) ?></td><td class="num"><?= e((string)$it['qty']) ?></td><td class="center"><?= e($it['unit']) ?></td><td class="num"><?= money((float)$it['unit_price']) ?></td><td class="num"><?= money((float)$it['total']) ?></td></tr><?php endforeach; ?></tbody>
    </table>
    <table class="summary">
        <tr class="total-row"><th>Sub Total Excluding VAT & AIT</th><td><?= money($localExcluding) ?> BDT</td></tr>
        <tr><th>AIT <?= e((string)$q['ait_percent']) ?>%</th><td><?= money((float)$q['ait_amount']) ?> BDT</td></tr>
        <tr><th>VAT <?= e((string)$q['vat_percent']) ?>%</th><td><?= money((float)$q['vat_amount']) ?> BDT</td></tr>
        <tr class="total-row"><th>Sub Total Including VAT & AIT</th><td><?= money($localIncluding) ?> BDT</td></tr>
    </table>

    <div class="section-title">Final Cost Summary</div>
    <table class="final-summary">
        <tr><th>Total Amount for Import Part in BDT</th><td><?= money($totalImportBdt) ?> BDT</td></tr>
        <tr><th>Total Import + Total Local Excluding VAT & AIT</th><td><?= money($projectExcluding) ?> BDT</td></tr>
        <tr><th>Total Import + Total Local Including VAT & AIT</th><td><?= money($projectIncluding) ?> BDT</td></tr>
        <tr><th>Note</th><td><?= e($q['import_tax_note'] ?: 'No VAT & AIT For Import Part') ?></td></tr>
        <tr class="highlight"><th>Per Watt Without VAT & AIT</th><td><?= $perWattWithout === null ? 'N/A' : money($perWattWithout) . ' BDT/W' ?></td></tr>
        <tr class="highlight"><th>Per Watt Including VAT & AIT</th><td><?= $perWattWith === null ? 'N/A' : money($perWattWith) . ' BDT/W' ?></td></tr>
    </table>

    <div class="note"><strong>Terms and Conditions:</strong><br><?= nl2br(e($q['terms_conditions'])) ?></div>
    <div class="sign"><div><div class="line">Prepared by: <?= e($q['prepared_by']) ?></div></div><div><div class="line">Customer Signature</div></div></div>
    <div class="sign"><div></div><div><div class="line">Company Authorized Signature</div></div></div>
    <?php if ($showBranding): ?>
    <div style="text-align:right; font-size:12px; color:#9ca3af; margin-top:24px; font-weight:bold;">Powered by EMS SOFTZ<br><span style="font-size:10px;font-weight:normal">Custom ERP & Business Solutions</span></div>
    <?php endif; ?>
</div></body></html>
<?php
    return (string)ob_get_clean();
}
