<?php
$pageTitle = 'Quotation History';
require_once __DIR__ . '/../../app/includes/header.php';
$id = (int)($_GET['id'] ?? 0);
if ($id <= 0):
    if (current_user()['role'] === 'admin') {
        $rows = db()->query('SELECT q.*, c.customer_name FROM quotations q JOIN customers c ON c.id=q.customer_id ORDER BY q.id DESC')->fetchAll();
    } else {
        $rows = db()->prepare('SELECT q.*, c.customer_name FROM quotations q JOIN customers c ON c.id=q.customer_id WHERE q.created_by=? ORDER BY q.id DESC');
        $rows->execute([current_user()['id']]);
        $rows = $rows->fetchAll();
    }
?>
<div class="page-head"><div><h1>Quotation History</h1><p>Saved drafts, sent quotes, and closed sales.</p></div><a class="btn btn-primary" href="<?= APP_BASE ?>/quotations/create.php"><i class="bi bi-plus-lg me-1"></i>New Quotation</a></div>
<div class="card app-card"><div class="table-responsive"><table class="table align-middle mb-0">
<thead><tr><th>Quotation No</th><th>Customer</th><th>System Type</th><th>Total</th><th>Status</th><th>Date</th><th>Action</th></tr></thead><tbody>
<?php foreach ($rows as $row): ?><tr><td><?= e($row['quotation_no']) ?></td><td><?= e($row['customer_name']) ?></td><td><?= e($row['system_type']) ?></td><td><?= money((float)$row['grand_total']) ?></td><td><?= status_badge($row['status']) ?></td><td><?= e(date('Y-m-d', strtotime($row['created_at']))) ?></td><td><a class="btn btn-sm btn-outline-primary" href="<?= APP_BASE ?>/quotations/view.php?id=<?= (int)$row['id'] ?>">View</a> <a class="btn btn-sm btn-outline-secondary" href="<?= APP_BASE ?>/quotations/edit.php?id=<?= (int)$row['id'] ?>">Edit</a></td></tr><?php endforeach; ?>
<?php if (!$rows): ?><tr><td colspan="7" class="text-center text-muted py-4">No quotations found.</td></tr><?php endif; ?>
</tbody></table></div></div>
<?php else:
$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 || (current_user()['role'] !== 'admin' && (int)$q['created_by'] !== current_user()['id'])) { 
    http_response_code(403);
    exit('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();
$canSeeInternalCosting = in_array(current_user()['role'] ?? '', ['admin', 'sales'], true);
?>
<?php
$protocol = isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? 'https://' : 'http://';
$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$fullBaseUrl = $protocol . $host . APP_BASE;

$waPhone = preg_replace('/[^0-9]/', '', $q['phone'] ?? '');
if (strlen($waPhone) === 11 && str_starts_with($waPhone, '0')) {
    $waPhone = '88' . $waPhone;
}

// Generate public share link
$shareHash = substr(hash('sha256', $q['id'] . $q['created_at'] . 'FQS_SHARE'), 0, 16);
$shareUrl = $fullBaseUrl . '/quotations/share.php?id=' . $id . '&h=' . $shareHash;

$waMsg = "Dear " . ($q['customer_name'] ?? 'Customer') . ",\n\nPlease find your solar quotation *" . ($q['quotation_no'] ?? '') . "* ready for review.\n\nView & download here:\n" . $shareUrl . "\n\nThank you.";
?>
<div class="page-head"><div><h1><?= e($q['quotation_no']) ?></h1><p><?= e($q['customer_name']) ?> - <?= e($q['system_type']) ?></p></div><div><a class="btn btn-outline-secondary" href="<?= APP_BASE ?>/quotations/edit.php?id=<?= $id ?>"><i class="bi bi-pencil me-1"></i>Edit</a> <?php if ($canSeeInternalCosting): ?><a class="btn btn-outline-secondary" target="_blank" href="<?= APP_BASE ?>/quotations/print.php?id=<?= $id ?>&mode=internal"><i class="bi bi-printer me-1"></i>Print Internal Costing</a><?php endif; ?> <a class="btn btn-outline-secondary" target="_blank" href="<?= APP_BASE ?>/quotations/print.php?id=<?= $id ?>&mode=customer"><i class="bi bi-printer me-1"></i>Print Customer Quotation</a> <a class="btn btn-success" href="<?= APP_BASE ?>/quotations/download.php?id=<?= $id ?>"><i class="bi bi-download me-1"></i>Download Customer PDF</a> <button type="button" id="btnShareWa" class="btn btn-outline-success" data-id="<?= $id ?>" data-phone="<?= e($waPhone) ?>" data-msg="<?= e($waMsg) ?>"><i class="bi bi-whatsapp me-1"></i>Send via WhatsApp</button></div></div>
<div class="row g-4">
<div class="col-lg-8">
    <?php if (!empty($q['has_imported_materials']) && $canSeeInternalCosting): ?><div class="card app-card p-4 mb-4"><h2>Imported Materials</h2><div class="table-responsive"><table class="table align-middle"><thead><tr><th>SL</th><th>Item / Job Head</th><th>Specification</th><th>Brand</th><th>Model</th><th>Qty</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']) ?> <?= 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></div></div><?php endif; ?>
    <div class="card app-card p-4 mb-4"><h2>Products</h2><div class="table-responsive"><table class="table align-middle"><thead><tr><th>SL</th><th>Category</th><th>Product</th><th>Brand</th><th>Model</th><th>Qty</th><th>Unit Price</th><th>Total</th></tr></thead><tbody><?php foreach ($items as $i=>$it): ?><tr><td><?= $i+1 ?></td><td><?= e($it['product_category']) ?></td><td><?= e($it['product_name']) ?><div class="small text-muted"><?= e($it['description']) ?></div></td><td><?= e($it['brand']) ?></td><td><?= e($it['model']) ?></td><td><?= e((string)$it['qty']) ?> <?= e($it['unit']) ?></td><td><?= money((float)$it['unit_price']) ?></td><td><?= money((float)$it['total']) ?></td></tr><?php endforeach; ?></tbody></table></div></div>
    <?php if ($loads && $q['calculation_method'] === 'Load Calculation'): ?><div class="card app-card p-4"><h2>Load Calculation</h2><div class="table-responsive"><table class="table align-middle"><thead><tr><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 $l): ?><tr><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></div></div><?php endif; ?>
    <?php if ($q['calculation_method'] === 'Water Pumping'): ?><div class="card app-card p-4 mt-4"><h2>Water Pumping Calculation</h2><div class="suggest-grid"><div><span>Pump HP</span><strong><?= e((string)$q['pump_hp']) ?> HP</strong></div><div><span>Head</span><strong><?= e((string)$q['pump_head']) ?> ft</strong></div><div><span>Water Demand</span><strong><?= e((string)$q['water_demand']) ?> L/day</strong></div><div><span>Daily Pumping Energy</span><strong><?= money((float)($q['daily_pumping_energy_kwh'] ?? 0)) ?> kWh</strong></div><div><span>Suggested Solar Panel Capacity</span><strong><?= money((float)($q['system_capacity_kw'] ?? 0)) ?> kW</strong></div><div><span>Suggested Inverter/VFD Size</span><strong><?= money((float)($q['suggested_inverter_kw'] ?? 0)) ?> kW</strong></div></div></div><?php endif; ?>
</div>
<div class="col-lg-4">
    <div class="card app-card p-4 mb-4"><h2>Customer</h2><p class="mb-1"><strong><?= e($q['customer_name']) ?></strong></p><p class="text-muted mb-0"><?= e($q['phone']) ?><br><?= e($q['email']) ?><br><?= e($q['location']) ?><br><?= nl2br(e($q['address'])) ?></p></div>
    <div class="card app-card p-4 mb-4"><h2>Site Data</h2><div class="summary-row"><span>Site Type</span><strong><?= e($q['site_type']) ?></strong></div><div class="summary-row"><span>Installation Area</span><strong><?= e($q['installation_area']) ?></strong></div><div class="summary-row"><span>Panel Mounting</span><strong><?= e($q['panel_mounting']) ?></strong></div></div>
    <div class="card app-card p-4 mb-4"><h2>Suggested System</h2><div class="summary-row"><span>Inverter Needed</span><strong><?= money((float)($q['suggested_inverter_kw'] ?? 0)) ?> kW</strong></div><div class="summary-row"><span>Battery Needed</span><strong><?= e($q['battery_spec'] ?? 'Not Required') ?></strong></div><div class="summary-row"><span>Solar Panel Capacity</span><strong><?= money((float)($q['system_capacity_kw'] ?? 0)) ?> kW</strong></div><div class="summary-row"><span>Structure & Accessories</span><strong>As per site</strong></div></div>
    <?php if (!empty($q['has_imported_materials']) && $canSeeInternalCosting): ?><div class="card app-card p-4 mb-4"><h2>Import Cost Summary</h2><div class="summary-row"><span>Import Subtotal USD</span><strong><?= money((float)$q['import_subtotal_usd']) ?></strong></div><div class="summary-row"><span>LC Fee</span><strong><?= money((float)$q['lc_fee_usd']) ?> USD</strong></div><div class="summary-row"><span>Total Import USD</span><strong><?= money((float)$q['total_import_cost_usd']) ?></strong></div><div class="summary-row"><span>Dollar Rate</span><strong><?= money((float)$q['dollar_rate']) ?></strong></div><div class="summary-row"><span>Total Import BDT</span><strong><?= money((float)$q['total_import_cost_bdt']) ?></strong></div></div><div class="card app-card p-4 mb-4"><h2>Final Project Summary</h2><div class="summary-row"><span>Local AIT</span><strong><?= money((float)$q['ait_amount']) ?></strong></div><div class="summary-row"><span>Local VAT</span><strong><?= money((float)$q['vat_amount']) ?></strong></div><div class="summary-row"><span>Total Excluding VAT & AIT</span><strong><?= money((float)$q['total_excluding_vat_ait']) ?></strong></div><div class="summary-row"><span>Total Including VAT & AIT</span><strong><?= money((float)$q['total_including_vat_ait']) ?></strong></div><div class="summary-row"><span>Margin</span><strong><?= money((float)$q['margin_amount']) ?></strong></div><div class="summary-row total"><span>Final Quotation Amount</span><strong><?= money((float)$q['final_quotation_amount']) ?></strong></div></div><div class="card app-card p-4 mb-4"><h2>Cost per Watt / kW</h2><div class="summary-row"><span>DC Capacity</span><strong><?= money((float)$q['dc_capacity_kwp']) ?> kWp</strong></div><div class="summary-row"><span>AC Capacity</span><strong><?= money((float)$q['ac_capacity_kw']) ?> kW</strong></div><div class="summary-row"><span>Cost/W Excluding Tax</span><strong><?= (float)($q['cost_per_watt_excluding_tax'] ?? 0) > 0 ? money((float)$q['cost_per_watt_excluding_tax']) : 'N/A' ?></strong></div><div class="summary-row"><span>Cost/W Including Tax</span><strong><?= (float)($q['cost_per_watt_including_tax'] ?? 0) > 0 ? money((float)$q['cost_per_watt_including_tax']) : 'N/A' ?></strong></div><div class="summary-row"><span>Cost/kW Excluding Tax</span><strong><?= (float)($q['cost_per_kw_excluding_tax'] ?? 0) > 0 ? money((float)$q['cost_per_kw_excluding_tax']) : 'N/A' ?></strong></div><div class="summary-row"><span>Cost/kW Including Tax</span><strong><?= (float)($q['cost_per_kw_including_tax'] ?? 0) > 0 ? money((float)$q['cost_per_kw_including_tax']) : 'N/A' ?></strong></div></div><?php endif; ?>
    <div class="card app-card p-4 mb-4"><h2>Energy & Savings Analysis</h2><div class="suggest-grid"><div><span>Annual Energy Generated</span><strong><?= money((float)($q['annual_energy_kwh'] ?? 0)) ?> kWh/year</strong></div><div><span>Carbon Emission Reduced</span><strong><?= money((float)($q['carbon_reduced_kg'] ?? 0)) ?> kg CO2/year</strong></div><div><span>Coal Reduced</span><strong><?= money((float)($q['coal_reduced_kg'] ?? 0)) ?> kg/year</strong></div><div><span>Payback Period</span><strong><?= (float)($q['payback_period_years'] ?? 0) > 0 ? money((float)$q['payback_period_years']) . ' years' : 'N/A' ?></strong></div></div></div>
    <div class="card app-card p-4"><h2>Summary</h2><div class="summary-row"><span>Subtotal</span><strong><?= money((float)$q['subtotal']) ?></strong></div><div class="summary-row"><span>VAT</span><strong><?= money((float)$q['vat_amount']) ?></strong></div><div class="summary-row"><span>Discount</span><strong><?= money((float)$q['discount_amount']) ?></strong></div><div class="summary-row total"><span>Grand Total</span><strong><?= money((float)$q['grand_total']) ?></strong></div><div class="summary-row"><span>Status</span><strong><?= status_badge($q['status']) ?></strong></div></div>
</div>
</div>
<?php endif; require_once __DIR__ . '/../../app/includes/footer.php'; ?>

<script nonce="<?= $cspNonce ?? '' ?>">
document.addEventListener('DOMContentLoaded', () => {
    const btnShareWa = document.getElementById('btnShareWa');
    if (btnShareWa) {
        btnShareWa.addEventListener('click', async () => {
            const btn = btnShareWa;
            const id = btn.getAttribute('data-id');
            const phone = btn.getAttribute('data-phone');
            const msg = btn.getAttribute('data-msg');
            const originalHtml = btn.innerHTML;
            
            try {
                btn.innerHTML = '<i class="bi bi-hourglass-split me-1"></i>Preparing...';
                btn.disabled = true;

                const response = await fetch(`<?= APP_BASE ?>/quotations/download.php?id=${id}`);
                if (!response.ok) throw new Error('Failed to download PDF');
                
                const blob = await response.blob();
                const file = new File([blob], `Quotation_${id}.pdf`, { type: 'application/pdf' });

                if (navigator.canShare && navigator.canShare({ files: [file] })) {
                    await navigator.share({
                        title: 'Solar Quotation',
                        text: msg,
                        files: [file]
                    });
                } else {
                    const encodedMsg = encodeURIComponent(msg);
                    const waUrl = phone ? `https://wa.me/${phone}?text=${encodedMsg}` : `https://wa.me/?text=${encodedMsg}`;
                    window.open(waUrl, '_blank');
                }
            } catch (err) {
                console.error(err);
                alert('Could not share the file automatically. You can still download the PDF and attach it manually, or the customer can use the public link in the message text.');
                const encodedMsg = encodeURIComponent(msg);
                const waUrl = phone ? `https://wa.me/${phone}?text=${encodedMsg}` : `https://wa.me/?text=${encodedMsg}`;
                window.open(waUrl, '_blank');
            } finally {
                btn.innerHTML = originalHtml;
                btn.disabled = false;
            }
        });
    }
});
</script>
