<?php
if (basename(__FILE__) === basename($_SERVER['SCRIPT_FILENAME'] ?? '')) { http_response_code(403); exit('Forbidden'); }
$products = db()->query("SELECT * FROM products WHERE status='active' ORDER BY product_category, product_name")->fetchAll();
if (current_user()['role'] === 'admin') {
    $customers = db()->query('SELECT * FROM customers ORDER BY customer_name')->fetchAll();
} else {
    $customers = db()->prepare('SELECT * FROM customers WHERE created_by = ? ORDER BY customer_name');
    $customers->execute([current_user()['id']]);
    $customers = $customers->fetchAll();
}
$categories = array_values(array_unique(array_column($products, 'product_category')));
$importRows = $importItems ?? [];
?>
<script nonce="<?= $cspNonce ?? '' ?>">
    window.FQS_PRODUCTS = <?= json_encode($products, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT) ?>;
    window.FQS_NEW_QUOTATION = <?= empty($quotation['id']) ? 'true' : 'false' ?>;

    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>
<div class="page-head">
    <div><h1><?= isset($quotation['id']) ? 'Edit Quotation' : 'New Quotation' ?></h1><p>Create, calculate, save, print, and download a professional solar quotation.</p></div>
</div>
<form id="quotationForm" method="post" action="<?= e($action) ?>">
<?= csrf_field() ?>
<div class="row g-4">
<div class="col-xl-8">
    <section class="card app-card p-4 mb-4">
        <h2>Select System Type</h2>
        <div class="row g-3">
            <div class="col-md-6"><label class="form-label">System Type</label><select class="form-select" name="system_type" id="systemType">
                <?php foreach (['On-Grid Solar System','Off-Grid Solar System','Hybrid Solar System','Solar Water Pumping System'] as $v): ?><option <?= ($quotation['system_type'] ?? '')===$v?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?>
            </select></div>
            <div class="col-md-6"><label class="form-label">Calculation Method</label><select class="form-select" name="calculation_method" id="calculationMethod" data-current="<?= e($quotation['calculation_method'] ?? '') ?>"></select></div>
            <div class="col-12"><div class="form-check form-switch"><input class="form-check-input" type="checkbox" role="switch" name="has_imported_materials" id="hasImportedMaterials" value="1" <?= !empty($quotation['has_imported_materials']) ? 'checked' : '' ?>><label class="form-check-label fw-semibold" for="hasImportedMaterials">Imported Materials Included</label></div></div>
        </div>
    </section>

    <section class="card app-card p-4 mb-4 calc-block" data-method="Load Calculation">
        <div class="section-title"><h2>Load Calculation</h2><button type="button" class="btn btn-sm btn-outline-primary" id="addLoad"><i class="bi bi-plus"></i>Add More Load</button></div>
        <div class="table-responsive"><table class="table table-sm align-middle" id="loadTable"><thead><tr><th>SL</th><th>Load</th><th>Qty</th><th>Watt Rating</th><th>Backup When No Sun</th><th>Total Watt</th><th>Watt Hour</th><th>Action</th></tr></thead><tbody>
            <?php $loadRows = $loads ?: [['load_name'=>'Ceiling Fan','qty'=>1,'watt_rating'=>90,'backup_when_no_sun'=>2]]; foreach ($loadRows as $i=>$l): ?><tr>
                <td class="sl"></td><td><input class="form-control form-control-sm" name="loads[<?= $i ?>][load_name]" value="<?= e($l['load_name'] ?? '') ?>"></td>
                <td><input class="form-control form-control-sm load-num" name="loads[<?= $i ?>][qty]" type="number" step="0.01" value="<?= e((string)($l['qty'] ?? 1)) ?>"></td>
                <td><input class="form-control form-control-sm load-num" name="loads[<?= $i ?>][watt_rating]" type="number" step="0.01" value="<?= e((string)($l['watt_rating'] ?? 0)) ?>"></td>
                <td><input class="form-control form-control-sm load-num" name="loads[<?= $i ?>][backup_when_no_sun]" type="number" step="0.01" value="<?= e((string)($l['backup_when_no_sun'] ?? 0)) ?>"></td>
                <td class="total-watt">0</td><td class="watt-hour">0</td><td><button class="btn btn-sm btn-outline-danger remove-row" type="button"><i class="bi bi-trash"></i></button></td>
            </tr><?php endforeach; ?>
        </tbody></table></div>
        <div class="suggest-grid"><div><span>Total Connected Load</span><strong id="connectedLoad">0 W</strong></div><div><span>Total Energy Requirement</span><strong id="energyNeed">0 Wh</strong></div><div><span>Suggested Inverter Size</span><strong id="loadInverter">0 VA</strong></div><div><span>Suggested Battery Bank</span><strong id="loadBattery">0 Ah</strong></div><div><span>Suggested Solar Panel Capacity</span><strong id="loadPanel">0 W</strong></div></div>
    </section>

    <section class="card app-card p-4 mb-4 calc-block" data-method="Monthly Electricity Bill">
        <h2>Monthly Electricity Bill</h2>
        <div class="row g-3">
            <div class="col-md-4"><label class="form-label">Monthly Bill Amount</label><input class="form-control bill-calc" name="monthly_bill" id="monthlyBill" type="number" step="0.01" value="<?= e((string)($quotation['monthly_bill'] ?? 0)) ?>"></div>
            <div class="col-md-4"><label class="form-label">Electricity Rate per Unit</label><input class="form-control bill-calc energy-calc" name="electricity_rate" id="electricityRate" type="number" step="0.01" value="<?= e((string)($quotation['electricity_rate'] ?? 10)) ?>"></div>
            <div class="col-md-4"><label class="form-label">Average Sun Hour</label><input class="form-control bill-calc pump-calc energy-calc" name="average_sun_hour" id="sunHour" type="number" step="0.01" value="<?= e((string)($quotation['average_sun_hour'] ?? 4.5)) ?>"></div>
        </div>
        <div class="suggest-grid mt-3"><div><span>Estimated Monthly Unit</span><strong id="monthlyUnits">0</strong></div><div><span>Estimated Daily Unit</span><strong id="dailyUnits">0</strong></div><div><span>Suggested Solar Capacity</span><strong id="billSolar">0 kW</strong></div></div>
    </section>

    <section class="card app-card p-4 mb-4 calc-block" data-method="Peak Load">
        <h2>Peak Load</h2>
        <div class="row g-3">
            <div class="col-md-6"><label class="form-label">Peak Load in kW</label><input class="form-control peak-calc" name="peak_load_kw" id="peakLoad" type="number" step="0.01" value="<?= e((string)($quotation['peak_load_kw'] ?? 0)) ?>"></div>
            <div class="col-md-6"><label class="form-label">Safety Factor Percent</label><input class="form-control peak-calc" id="safetyFactor" type="number" step="0.01" value="25"></div>
        </div>
        <div class="suggest-grid mt-3"><div><span>Suggested Inverter Size</span><strong id="peakInverter">0 kW</strong></div><div><span>Suggested Solar Panel Capacity</span><strong id="peakPanel">0 kW</strong></div></div>
    </section>

    <section class="card app-card p-4 mb-4 calc-block" data-method="Water Pumping">
        <h2>Water Pumping</h2>
        <div class="row g-3">
            <div class="col-md-3"><label class="form-label">Pump HP</label><input class="form-control pump-calc" name="pump_hp" id="pumpHp" type="number" step="0.01" value="<?= e((string)($quotation['pump_hp'] ?? 0)) ?>"></div>
            <div class="col-md-3"><label class="form-label">Pump Type</label><select class="form-select pump-calc" name="pump_type" id="pumpType"><option <?= ($quotation['pump_type'] ?? 'AC')==='AC'?'selected':'' ?>>AC</option><option <?= ($quotation['pump_type'] ?? '')==='DC'?'selected':'' ?>>DC</option></select></div>
            <div class="col-md-3"><label class="form-label">Phase</label><select class="form-select" name="pump_phase"><option <?= ($quotation['pump_phase'] ?? 'Single Phase')==='Single Phase'?'selected':'' ?>>Single Phase</option><option <?= ($quotation['pump_phase'] ?? '')==='Three Phase'?'selected':'' ?>>Three Phase</option></select></div>
            <div class="col-md-3"><label class="form-label">Head in Feet</label><input class="form-control pump-calc" name="pump_head" id="pumpHead" type="number" step="0.01" value="<?= e((string)($quotation['pump_head'] ?? 0)) ?>"></div>
            <div class="col-md-4"><label class="form-label">Pipe Diameter</label><input class="form-control" name="pipe_diameter" value="<?= e($quotation['pipe_diameter'] ?? '') ?>"></div>
            <div class="col-md-4"><label class="form-label">Water Demand per Day (L)</label><input class="form-control pump-calc" name="water_demand" id="waterDemand" type="number" step="0.01" value="<?= e((string)($quotation['water_demand'] ?? 0)) ?>"></div>
            <div class="col-md-4"><label class="form-label">Running Hours per Day</label><input class="form-control pump-calc" name="running_hours_per_day" id="runningHours" type="number" step="0.01" value="<?= e((string)($quotation['running_hours_per_day'] ?? 0)) ?>"></div>
            <div class="col-md-6"><label class="form-label">Pump Efficiency</label><input class="form-control pump-calc" name="pump_efficiency" id="pumpEfficiency" type="number" step="0.01" value="<?= e((string)($quotation['pump_efficiency'] ?? 0.55)) ?>"></div>
            <div class="col-md-6"><label class="form-label">System Efficiency</label><input class="form-control pump-calc" name="system_efficiency" id="systemEfficiency" type="number" step="0.01" value="<?= e((string)($quotation['system_efficiency'] ?? 0.75)) ?>"></div>
        </div>
        <div class="suggest-grid mt-3"><div><span>Pump Power</span><strong id="pumpPower">0 kW</strong></div><div><span>Total Dynamic Head</span><strong id="pumpHeadView">0 ft</strong></div><div><span>Daily Water Demand</span><strong id="pumpDemandView">0 L/day</strong></div><div><span>Daily Pumping Energy</span><strong id="pumpEnergy">0 kWh</strong></div><div><span>Suggested Panel Size</span><strong id="pumpPanel">0 kW</strong></div><div><span>Suggested Inverter/VFD Size</span><strong id="pumpInverter">0 kW</strong></div></div>
    </section>

    <section class="card app-card p-4 mb-4">
        <h2>Energy & Savings Analysis</h2>
        <div class="row g-3 mb-3">
            <div class="col-md-4"><label class="form-label">Performance Ratio</label><input class="form-control energy-calc" name="performance_ratio" id="performanceRatio" type="number" step="0.01" value="<?= e((string)($quotation['performance_ratio'] ?? 0.75)) ?>"></div>
            <div class="col-md-4"><label class="form-label">Grid Emission Factor kg CO2/kWh</label><input class="form-control energy-calc" name="grid_emission_factor" id="gridEmissionFactor" type="number" step="0.01" value="<?= e((string)($quotation['grid_emission_factor'] ?? 0.62)) ?>"></div>
            <div class="col-md-4"><label class="form-label">Coal Factor kg/kWh</label><input class="form-control energy-calc" name="coal_factor" id="coalFactor" type="number" step="0.01" value="<?= e((string)($quotation['coal_factor'] ?? 0.4)) ?>"></div>
        </div>
        <div class="suggest-grid">
            <div><span>Annual Energy Generated</span><strong id="annualEnergy">0 kWh/year</strong></div>
            <div><span>Carbon Emission Reduced</span><strong id="carbonReduced">0 kg CO2/year</strong></div>
            <div><span>Coal Reduced</span><strong id="coalReduced">0 kg/year</strong></div>
            <div><span>Payback Period</span><strong id="paybackPeriod">N/A</strong></div>
        </div>
    </section>

    <section class="card app-card p-4 mb-4 import-section">
        <div class="section-title"><h2>Imported Materials</h2><button type="button" class="btn btn-sm btn-outline-primary" id="addImportItem"><i class="bi bi-plus"></i>Add Imported Item</button></div>
        <div class="table-responsive"><table class="table table-sm align-middle import-table" id="importTable"><thead><tr><th>SL</th><th>Item / Job Head</th><th>Specification Details</th><th>Brand</th><th>Model</th><th>Qty</th><th>Unit</th><th>FOB Rate USD</th><th>FOB Total USD</th><th>Action</th></tr></thead><tbody>
            <?php $rows = $importRows ?: [[]]; foreach ($rows as $i=>$it): ?><tr>
                <td class="sl" data-label="SL"></td>
                <td data-label="Item / Job Head"><input class="form-control form-control-sm" name="import_items[<?= $i ?>][item_head]" value="<?= e($it['item_head'] ?? '') ?>" placeholder="Item Head"></td>
                <td data-label="Specification Details"><input class="form-control form-control-sm" name="import_items[<?= $i ?>][specification]" value="<?= e($it['specification'] ?? '') ?>" placeholder="Specification"></td>
                <td data-label="Brand"><input class="form-control form-control-sm" name="import_items[<?= $i ?>][brand]" value="<?= e($it['brand'] ?? '') ?>" placeholder="Brand"></td>
                <td data-label="Model"><input class="form-control form-control-sm" name="import_items[<?= $i ?>][model]" value="<?= e($it['model'] ?? '') ?>" placeholder="Model"></td>
                <td data-label="Qty"><input class="form-control form-control-sm import-num import-qty" name="import_items[<?= $i ?>][qty]" type="number" step="0.01" value="<?= e((string)($it['qty'] ?? 1)) ?>" placeholder="Qty"></td>
                <td data-label="Unit"><input class="form-control form-control-sm" name="import_items[<?= $i ?>][unit]" value="<?= e($it['unit'] ?? 'pcs') ?>" placeholder="Unit"></td>
                <td data-label="FOB Rate USD"><input class="form-control form-control-sm import-num fob-rate" name="import_items[<?= $i ?>][fob_rate_usd]" type="number" step="0.01" value="<?= e((string)($it['fob_rate_usd'] ?? 0)) ?>" placeholder="FOB Rate"></td>
                <td class="fob-total" data-label="FOB Total USD">0</td>
                <td data-label="Action"><button class="btn btn-sm btn-outline-danger remove-row" type="button"><i class="bi bi-trash"></i></button></td>
            </tr><?php endforeach; ?>
        </tbody></table></div>
    </section>

    <section class="card app-card p-4 mb-4">
        <div class="section-title"><h2>Local Materials / Local Works</h2><div><button type="button" class="btn btn-sm btn-info text-white" id="addProduct"><i class="bi bi-plus"></i>Add Product</button> <button type="button" class="btn btn-sm btn-dark" id="addCustom"><i class="bi bi-pencil"></i>Add Custom Item</button></div></div>
        <div class="table-responsive" id="productScrollBody"><table class="table table-sm align-middle product-table" id="productTable"><thead><tr><th>SL</th><th>Product Category</th><th>Product Search / Dropdown</th><th>Description</th><th>Brand</th><th>Model</th><th>Qty</th><th>Unit</th><th>Unit Price BDT</th><th>Total BDT</th><th>Action</th></tr></thead><tbody>
        <?php $rows = $items ?: [[]]; foreach ($rows as $i=>$it): ?>
            <tr data-custom="<?= !empty($it['is_custom_item']) ? 1 : 0 ?>">
                <td class="sl" data-label="SL"></td>
                <td data-label="Category"><select class="form-select form-select-sm category" name="items[<?= $i ?>][product_category]"><option value="">Select</option><?php foreach ($categories as $cat): ?><option <?= ($it['product_category'] ?? '')===$cat?'selected':'' ?>><?= e($cat) ?></option><?php endforeach; ?></select></td>
                <td data-label="Product Name"><select class="form-select form-select-sm product-select" name="items[<?= $i ?>][product_id]"><option value="">Custom / Select</option><?php foreach ($products as $p): ?><option value="<?= (int)$p['id'] ?>" <?= (int)($it['product_id'] ?? 0)===(int)$p['id']?'selected':'' ?>><?= e($p['product_name']) ?></option><?php endforeach; ?></select><input class="form-control form-control-sm mt-1 product-name" name="items[<?= $i ?>][product_name]" value="<?= e($it['product_name'] ?? '') ?>" placeholder="Custom product name"></td>
                <td data-label="Description">
                    <input type="hidden" class="description" name="items[<?= $i ?>][description]" value="<?= e($it['description'] ?? '') ?>">
                    <input type="text" class="form-control form-control-sm desc-trigger<?= !empty($it['description']) ? ' has-value' : '' ?>" readonly
                           value="<?= e($it['description'] ?? '') ?>"
                           title="<?= e($it['description'] ?? '') ?>"
                           placeholder="Click to edit...">
                </td>
                <td data-label="Brand"><input class="form-control form-control-sm brand" name="items[<?= $i ?>][brand]" value="<?= e($it['brand'] ?? '') ?>" placeholder="Brand"></td>
                <td data-label="Model"><input class="form-control form-control-sm model" name="items[<?= $i ?>][model]" value="<?= e($it['model'] ?? '') ?>" placeholder="Model"></td>
                <td data-label="Qty"><input class="form-control form-control-sm item-num qty" name="items[<?= $i ?>][qty]" type="number" step="0.01" value="<?= e((string)($it['qty'] ?? 1)) ?>" placeholder="Qty"></td>
                <td data-label="Unit"><input class="form-control form-control-sm unit" name="items[<?= $i ?>][unit]" value="<?= e($it['unit'] ?? 'pcs') ?>" placeholder="Unit"></td>
                <td data-label="Unit Price"><input class="form-control form-control-sm item-num unit-price" name="items[<?= $i ?>][unit_price]" type="number" step="0.01" value="<?= e((string)($it['unit_price'] ?? 0)) ?>" placeholder="Price"></td>
                <td class="item-total" data-label="Total BDT">0</td>
                <td data-label="Action"><input type="hidden" class="custom-flag" name="items[<?= $i ?>][is_custom_item]" value="<?= e((string)($it['is_custom_item'] ?? 0)) ?>"><button class="btn btn-sm btn-outline-danger remove-row" type="button"><i class="bi bi-trash"></i></button></td>
            </tr>
        <?php endforeach; ?>
        </tbody></table></div>
    </section>

    <section class="card app-card p-4 mb-4 import-section">
        <h2>Import Cost Summary</h2>
        <div class="row g-3">
            <div class="col-md-4"><label class="form-label">Imported Materials Subtotal USD</label><strong class="form-control bg-light" id="importSubtotalUsd">0.00</strong></div>
            <div class="col-md-4"><label class="form-label">Master LC Processing Fee %</label><input class="form-control import-cost" name="lc_fee_percent" id="lcFeePercent" type="number" step="0.01" value="<?= e((string)($quotation['lc_fee_percent'] ?? 7)) ?>"></div>
            <div class="col-md-4"><label class="form-label">Master LC Processing Fee USD</label><strong class="form-control bg-light" id="lcFeeUsd">0.00</strong></div>
            <div class="col-md-4"><label class="form-label">Freight Charge USD</label><input class="form-control import-cost" name="freight_usd" id="freightUsd" type="number" step="0.01" value="<?= e((string)($quotation['freight_usd'] ?? 0)) ?>"></div>
            <div class="col-md-4"><label class="form-label">Insurance USD</label><input class="form-control import-cost" name="insurance_usd" id="insuranceUsd" type="number" step="0.01" value="<?= e((string)($quotation['insurance_usd'] ?? 0)) ?>"></div>
            <div class="col-md-4"><label class="form-label">Other Import Cost USD</label><input class="form-control import-cost" name="other_import_cost_usd" id="otherImportCostUsd" type="number" step="0.01" value="<?= e((string)($quotation['other_import_cost_usd'] ?? 0)) ?>"></div>
            <div class="col-md-4"><label class="form-label">Total Import Cost USD</label><strong class="form-control bg-light" id="totalImportUsd">0.00</strong></div>
            <div class="col-md-4"><label class="form-label">Dollar Rate BDT</label><input class="form-control import-cost" name="dollar_rate" id="dollarRate" type="number" step="0.01" value="<?= e((string)($quotation['dollar_rate'] ?? 125)) ?>"></div>
            <div class="col-md-4"><label class="form-label">Total Import Cost BDT</label><strong class="form-control bg-light" id="totalImportBdt">0.00</strong></div>
        </div>
        <div class="form-check mt-3"><input class="form-check-input" type="checkbox" id="importTaxNoteChecked" <?= ($quotation['import_tax_note'] ?? 'No VAT & AIT for Import Part') !== '' ? 'checked' : '' ?>><label class="form-check-label" for="importTaxNoteChecked">No VAT & AIT for Import Part</label></div>
        <input class="form-control mt-2" name="import_tax_note" id="importTaxNote" value="<?= e($quotation['import_tax_note'] ?? 'No VAT & AIT for Import Part') ?>">
    </section>

    <section class="card app-card p-4 mb-4 import-section">
        <h2>Local Cost Summary</h2>
        <div class="suggest-grid">
            <div><span>Local Subtotal Excluding VAT & AIT</span><strong id="localSubtotalExTax">0</strong></div>
            <div><span>AIT %</span><input class="form-control form-control-sm import-cost" name="ait_percent" id="aitPercent" type="number" step="0.01" value="<?= e((string)($quotation['ait_percent'] ?? 5)) ?>"></div>
            <div><span>AIT Amount</span><strong id="aitAmount">0</strong></div>
            <div><span>VAT %</span><strong id="localVatPercentView">0</strong></div>
            <div><span>VAT Amount</span><strong id="localVatAmount">0</strong></div>
            <div><span>Local Subtotal Including VAT & AIT</span><strong id="localTotalWithTax">0</strong></div>
        </div>
    </section>

    <section class="card app-card p-4 mb-4 import-section">
        <h2>Final Project Cost Summary</h2>
        <div class="suggest-grid">
            <div><span>Total Import Cost BDT</span><strong id="finalImportBdt">0</strong></div>
            <div><span>Local Subtotal Excluding VAT & AIT</span><strong id="finalLocalSubtotal">0</strong></div>
            <div><span>Local AIT</span><strong id="finalAit">0</strong></div>
            <div><span>Local VAT</span><strong id="finalVat">0</strong></div>
            <div><span>Local Total Including VAT & AIT</span><strong id="finalLocalWithTax">0</strong></div>
            <div><span>Total Import + Local Excluding VAT & AIT</span><strong id="totalExcludingTax">0</strong></div>
            <div><span>Total Import + Local Including VAT & AIT</span><strong id="totalIncludingTax">0</strong></div>
            <div><span>Margin %</span><input class="form-control form-control-sm import-cost" name="margin_percent" id="marginPercent" type="number" step="0.01" value="<?= e((string)($quotation['margin_percent'] ?? 0)) ?>"></div>
            <div><span>Margin Amount</span><strong id="marginAmount">0</strong></div>
            <div><span>Final Quotation Amount</span><strong id="finalQuotationAmount">0</strong></div>
        </div>
    </section>

    <section class="card app-card p-4 mb-4 import-section">
        <h2>Cost per Watt / Cost per kW</h2>
        <div class="row g-3 mb-3">
            <div class="col-md-6"><label class="form-label">DC Capacity kWp</label><input class="form-control import-cost" name="dc_capacity_kwp" id="dcCapacityKwp" type="number" step="0.01" value="<?= e((string)($quotation['dc_capacity_kwp'] ?? 0)) ?>"></div>
            <div class="col-md-6"><label class="form-label">AC Capacity kW</label><input class="form-control import-cost" name="ac_capacity_kw" id="acCapacityKw" type="number" step="0.01" value="<?= e((string)($quotation['ac_capacity_kw'] ?? 0)) ?>"></div>
        </div>
        <div class="suggest-grid">
            <div><span>Cost per Watt Excluding VAT & AIT</span><strong id="cpwExTax">N/A</strong></div>
            <div><span>Cost per Watt Including VAT & AIT</span><strong id="cpwWithTax">N/A</strong></div>
            <div><span>Cost per kW Excluding VAT & AIT</span><strong id="cpkwExTax">N/A</strong></div>
            <div><span>Cost per kW Including VAT & AIT</span><strong id="cpkwWithTax">N/A</strong></div>
        </div>
        <div class="form-check mt-3"><input class="form-check-input" type="checkbox" name="show_cost_per_watt_on_pdf" id="showCostPerWattOnPdf" value="1" <?= !empty($quotation['show_cost_per_watt_on_pdf']) ? 'checked' : '' ?>><label class="form-check-label" for="showCostPerWattOnPdf">Show Cost per Watt / kW on Customer PDF</label></div>
    </section>

    <section class="card app-card p-4 mb-4">
        <h2>Quotation Actions</h2>
        <p class="text-muted">Finalize your quotation and share it with the customer.</p>
        <input type="hidden" name="subtotal" id="subtotalInput"><input type="hidden" name="vat_amount" id="vatAmountInput"><input type="hidden" name="grand_total" id="grandTotalInput">
        <button class="btn btn-primary" type="submit"><i class="bi bi-save me-1"></i>Save Quotation</button>
        <?php if (!empty($quotation['id'])): ?>
            <a class="btn btn-outline-secondary" target="_blank" href="<?= APP_BASE ?>/quotations/print.php?id=<?= (int)$quotation['id'] ?>&mode=internal"><i class="bi bi-printer me-1"></i>Print Internal Costing</a>
            <a class="btn btn-outline-secondary" target="_blank" href="<?= APP_BASE ?>/quotations/print.php?id=<?= (int)$quotation['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=<?= (int)$quotation['id'] ?>"><i class="bi bi-download me-1"></i>Download Customer PDF</a>
            <?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]/', '', $quotation['phone'] ?? '');
                if (strlen($waPhone) === 11 && str_starts_with($waPhone, '0')) {
                    $waPhone = '88' . $waPhone;
                }
                $shareHash = substr(hash('sha256', $quotation['id'] . $quotation['created_at'] . 'FQS_SHARE'), 0, 16);
                $shareUrl = $fullBaseUrl . '/quotations/share.php?id=' . $quotation['id'] . '&h=' . $shareHash;
                $waMsg = "Dear " . ($quotation['customer_name'] ?? 'Customer') . ",\n\nPlease find your solar quotation *" . ($quotation['quotation_no'] ?? '') . "* ready for review.\n\nView & download here:\n" . $shareUrl . "\n\nThank you.";
            ?>
            <button type="button" id="btnShareWa" class="btn btn-outline-success" data-id="<?= (int)$quotation['id'] ?>" data-phone="<?= e($waPhone) ?>" data-msg="<?= e($waMsg) ?>"><i class="bi bi-whatsapp me-1"></i>Send via WhatsApp</button>
        <?php endif; ?>
    </section>
</div>

<div class="col-xl-4">
    <section class="card app-card p-4 mb-4"><h2>Customer Info</h2>
        <label class="form-label">Existing Customer</label><select class="form-select mb-3" name="customer_id" id="customerSelect"><option value="">Create new customer inline</option><?php foreach ($customers as $c): ?><option value="<?= (int)$c['id'] ?>" <?= (int)($quotation['customer_id'] ?? 0)===(int)$c['id']?'selected':'' ?>><?= e($c['customer_name']) ?> - <?= e($c['phone']) ?></option><?php endforeach; ?></select>
        <div class="row g-3"><div class="col-12"><label class="form-label">Customer Name</label><input class="form-control" name="customer_name" value="<?= e($quotation['customer_name'] ?? '') ?>"></div><div class="col-12"><label class="form-label">Phone</label><input class="form-control" name="phone" value="<?= e($quotation['phone'] ?? '') ?>"></div><div class="col-12"><label class="form-label">Email</label><input class="form-control" type="email" name="email" value="<?= e($quotation['email'] ?? '') ?>"></div><div class="col-12"><label class="form-label">Location</label><input class="form-control" name="location" value="<?= e($quotation['location'] ?? '') ?>"></div><div class="col-12"><label class="form-label">Address</label><textarea class="form-control" name="address" rows="3"><?= e($quotation['address'] ?? '') ?></textarea></div></div>
    </section>
    <section class="card app-card p-4 mb-4"><h2>Site Data</h2>
        <label class="form-label">Site Type</label><select class="form-select mb-3" name="site_type"><?php foreach (['Residential','Commercial','Industrial','Irrigation','Other'] as $v): ?><option <?= ($quotation['site_type'] ?? '')===$v?'selected':'' ?>><?= e($v) ?></option><?php endforeach; ?></select>
        <label class="form-label">Installation Area</label><input class="form-control mb-3" name="installation_area" value="<?= e($quotation['installation_area'] ?? '') ?>">
        <label class="form-label">Panel Mounting</label><div class="pill-group"><?php foreach (['Shade','Rooftop','Ground Mounting'] as $v): ?><label><input type="radio" name="panel_mounting" value="<?= e($v) ?>" <?= ($quotation['panel_mounting'] ?? 'Rooftop')===$v?'checked':'' ?>><span><?= e($v) ?></span></label><?php endforeach; ?></div>
    </section>
    <section class="card app-card p-4 mb-4 sticky-summary"><h2>Quotation Summary</h2>
        <div class="summary-row"><span>Quotation No</span><strong><?= e($quotation['quotation_no']) ?></strong><input type="hidden" name="quotation_no" value="<?= e($quotation['quotation_no']) ?>"></div>
        <div class="summary-row"><span>Date</span><strong><?= e(date('Y-m-d')) ?></strong></div>
        <div class="summary-row"><span>System Type</span><strong id="sumSystem"></strong></div>
        <div class="summary-row"><span>Calculation Method</span><strong id="sumMethod"></strong></div>
        <div class="summary-row"><span>Subtotal</span><strong id="subtotalView">0</strong></div>
        <div class="summary-row"><span>VAT %</span><input class="form-control form-control-sm w-50 text-end" name="vat_percent" id="vatPercent" type="number" step="0.01" value="<?= e((string)($quotation['vat_percent'] ?? 0)) ?>"></div>
        <div class="summary-row"><span>VAT</span><strong id="vatView">0</strong></div>
        <div class="summary-row"><span>Discount</span><input class="form-control form-control-sm w-50 text-end" name="discount_amount" id="discountAmount" type="number" step="0.01" value="<?= e((string)($quotation['discount_amount'] ?? 0)) ?>"></div>
        <div class="summary-row total"><span>Total</span><strong id="grandView">0</strong></div>
        <label class="form-label mt-3">Status</label><select class="form-select" name="status"><?php foreach (['draft','final','sent','accepted','rejected'] as $v): ?><option value="<?= e($v) ?>" <?= ($quotation['status'] ?? '')===$v?'selected':'' ?>><?= e(ucfirst($v)) ?></option><?php endforeach; ?></select>
    </section>
    <section class="card app-card p-4"><h2>Suggested System Output</h2><div class="summary-row"><span>Inverter Needed</span><strong id="suggestInverter">0</strong></div><div class="summary-row"><span>Battery Needed</span><strong id="suggestBattery">N/A</strong></div><div class="summary-row"><span>Solar Panel Capacity</span><strong id="suggestPanel">0</strong></div><div class="summary-row"><span>Structure & Accessories</span><strong>As per site</strong></div><div class="summary-row"><span>Estimated Cost</span><strong id="suggestCost">0</strong></div><label class="form-label mt-3">Notes</label><textarea class="form-control" name="notes" rows="3"><?= e($quotation['notes'] ?? '') ?></textarea><label class="form-label mt-3">Terms & Conditions</label><textarea class="form-control" name="terms_conditions" rows="4"><?= e($quotation['terms_conditions'] ?? '') ?></textarea></section>
</div>
</div>
</form>

<!-- Description Edit Modal (Bootstrap) -->
<div class="modal fade" id="descModal" tabindex="-1" aria-labelledby="descModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-centered">
        <div class="modal-content" style="border-radius:16px;border:none;box-shadow:0 24px 60px rgba(0,0,0,.18)">
            <div class="modal-header" style="background:linear-gradient(135deg,#f0faf3,#e8f5ed);border-bottom:1px solid #d4edda;border-radius:16px 16px 0 0">
                <h5 class="modal-title fw-bold" id="descModalLabel"><i class="bi bi-file-text-fill text-success me-2"></i>Description / Specification</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body p-4">
                <p class="text-muted small mb-3"><i class="bi bi-info-circle me-1"></i>Write the full technical specification for this item. It will appear on the quotation PDF.</p>
                <textarea id="descModalTextarea" class="form-control" rows="9"
                    style="font-size:13.5px;line-height:1.7;resize:vertical;border-radius:10px"
                    placeholder="e.g. Supply, installation, testing & commissioning of mono-crystalline N-type bifacial PV modules; Capacity ≥590Wp; Efficiency ≥21%; IEC 61215/61730 compliant; 30-year performance warranty..."></textarea>
                <div class="d-flex justify-content-between align-items-center mt-2">
                    <small class="text-muted" id="descCharCount">0 characters</small>
                    <small class="text-muted"><kbd>Ctrl</kbd>+<kbd>Enter</kbd> to save</small>
                </div>
            </div>
            <div class="modal-footer" style="border-top:1px solid #e5ece8">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Cancel</button>
                <button type="button" class="btn btn-primary px-4" id="descModalSave"><i class="bi bi-check-lg me-1"></i>Save Description</button>
            </div>
        </div>
    </div>
</div>
