<?php
requirePermission($conn, 'quotations', 'view');
$canAdd = userCan($conn,'quotations','add');
$canEdit = userCan($conn,'quotations','edit');
$canDelete = userCan($conn,'quotations','delete');
$canOpen = userCan($conn,'quotations','open');
$canPrint = userCan($conn,'quotations','print');

$customers = $conn->query("SELECT id, customer_name, business_name FROM customers WHERE account_id=$account_id ORDER BY customer_name ASC");
$items = $conn->query("SELECT id, name, price FROM items WHERE account_id=$account_id ORDER BY name ASC");
$q = $conn->query("SELECT q.*, c.customer_name, i.name item_name FROM quotations q LEFT JOIN customers c ON c.id=q.customer_id LEFT JOIN items i ON i.id=q.item_id WHERE q.account_id=$account_id ORDER BY q.id DESC");
?>
<div class="fade-in quotations-page">
  <div class="toolbar" style="gap:10px;flex-wrap:wrap">
    <span class="card-title">Quotations</span>
    <?php if($canAdd): ?><button class="btn btn-primary" style="margin-left:auto" onclick="openQuotationForm()">+ New Quotation</button><?php endif; ?>
  </div>
  <div class="card" id="quotationFormCard" style="display:none;padding:18px;margin-bottom:18px">
    <h3 id="quotationFormTitle" style="margin-top:0">New Quotation</h3>
    <form id="quotationForm">
      <input type="hidden" name="id" id="quotation_id" value="0">
      <div class="form-grid">
        <div class="form-group"><label class="form-label">Customer *</label><select name="customer_id" id="quotation_customer_id" class="form-control" required><option value="">Select customer</option><?php while($c=$customers->fetch_assoc()): ?><option value="<?= $c['id'] ?>"><?= htmlspecialchars($c['customer_name'].($c['business_name']?' - '.$c['business_name']:'')) ?></option><?php endwhile; ?></select></div>
        <div class="form-group"><label class="form-label">Item *</label><select name="item_id" id="quotation_item_id" class="form-control" required onchange="fillItemPrice()"><option value="">Select item</option><?php $items->data_seek(0); while($it=$items->fetch_assoc()): ?><option value="<?= $it['id'] ?>" data-price="<?= $it['price'] ?>"><?= htmlspecialchars($it['name']) ?> - <?= number_format((float)$it['price'],2) ?></option><?php endwhile; ?></select></div>
        <div class="form-group"><label class="form-label">Quantity</label><input type="number" step="1" min="1" name="quantity" id="quotation_quantity" class="form-control" value="1" oninput="calcQuotationTotal()"></div>
        <div class="form-group"><label class="form-label">Unit Price</label><input type="number" step="0.01" min="0" name="unit_price" id="quotation_unit_price" class="form-control" value="0" oninput="calcQuotationTotal()"></div>
        <div class="form-group"><label class="form-label">Discount</label><input type="number" step="0.01" min="0" name="discount" id="quotation_discount" class="form-control" value="0" oninput="calcQuotationTotal()"></div>
        <div class="form-group"><label class="form-label">TVA %</label><input type="number" step="0.01" min="0" name="tva_percent" id="quotation_tva_percent" class="form-control" value="0" oninput="calcQuotationTotal()"></div>
        <div class="form-group"><label class="form-label">Status</label><select name="status" id="quotation_status" class="form-control"><option value="draft">Draft</option><option value="sent">Sent</option><option value="accepted">Accepted</option><option value="rejected">Rejected</option></select></div>
        <div class="form-group"><label class="form-label">Valid Until</label><input type="date" name="valid_until" id="quotation_valid_until" class="form-control"></div>
        <div class="form-group span-2"><label class="form-label">Notes</label><textarea name="notes" id="quotation_notes" class="form-control" rows="3"></textarea></div>
      </div>
      <div style="display:flex;justify-content:space-between;align-items:center;margin-top:14px;gap:10px;flex-wrap:wrap">
        <div class="badge badge-blue" style="font-size:15px">Total: <span id="quotation_total_preview">0.00</span></div>
        <div style="display:flex;gap:8px"><button type="button" class="btn btn-secondary" onclick="closeQuotationForm()">Cancel</button><button type="button" class="btn btn-primary" onclick="saveQuotation()">Save Quotation</button></div>
      </div>
    </form>
  </div>
  <div class="card"><div class="table-wrapper"><table class="crm-table"><thead><tr><th>#</th><th>Customer</th><th>Item</th><th>Total</th><th>Status</th><th>Date</th><th>Actions</th></tr></thead><tbody id="quotationsTbody">
    <?php while($row=$q->fetch_assoc()): ?>
      <tr id="quotation_<?= $row['id'] ?>">
        <td>QT-<?= str_pad($row['id'],5,'0',STR_PAD_LEFT) ?></td><td><?= htmlspecialchars($row['customer_name'] ?: '—') ?></td><td><?= htmlspecialchars($row['item_name'] ?: '—') ?></td><td><?= number_format((float)$row['total'],2) ?></td><td><span class="badge badge-blue"><?= htmlspecialchars(ucfirst($row['status'])) ?></span></td><td><?= formatDate($row['date_created']) ?></td><td style="display:flex;gap:6px;flex-wrap:wrap">
          <?php if($canOpen): ?><button class="btn btn-secondary btn-sm" onclick="viewQuotation(<?= $row['id'] ?>)">Open</button><?php endif; ?>
          <?php if($canEdit): ?><button class="btn btn-warning btn-sm" onclick="editQuotation(<?= $row['id'] ?>)">Edit</button><?php endif; ?>
          <?php if($canPrint): ?><button class="btn btn-primary btn-sm" onclick="printQuotation(<?= $row['id'] ?>)">Print</button><?php endif; ?>
          <?php if($canDelete): ?><button class="btn btn-danger btn-sm" onclick="deleteQuotation(<?= $row['id'] ?>)">Del</button><?php endif; ?>
        </td></tr>
    <?php endwhile; ?>
  </tbody></table></div></div>
</div>

<div class="modal-overlay" id="quotationViewModal"><div class="modal modal-lg"><div class="modal-header"><span class="modal-title">Quotation Details</span><button class="modal-close">✕</button></div><div class="modal-body" id="quotationViewBody"></div><div class="modal-footer"><button class="btn btn-secondary" onclick="closeModal('quotationViewModal')">Close</button><button class="btn btn-primary" onclick="window.print()">Print</button></div></div></div>
<script>
function openQuotationForm(){document.getElementById('quotationFormCard').style.display='block';document.getElementById('quotationFormTitle').textContent='New Quotation';document.getElementById('quotationForm').reset();document.getElementById('quotation_id').value=0;calcQuotationTotal();window.scrollTo({top:0,behavior:'smooth'});} 
function closeQuotationForm(){document.getElementById('quotationFormCard').style.display='none';}
function fillItemPrice(){const opt=document.getElementById('quotation_item_id').selectedOptions[0]; if(opt && opt.dataset.price){document.getElementById('quotation_unit_price').value=opt.dataset.price;} calcQuotationTotal();}
function calcQuotationTotal(){let q=parseFloat(document.getElementById('quotation_quantity').value)||0, p=parseFloat(document.getElementById('quotation_unit_price').value)||0, d=parseFloat(document.getElementById('quotation_discount').value)||0, t=parseFloat(document.getElementById('quotation_tva_percent').value)||0; let sub=q*p; let after=Math.max(0,sub-d); let total=after+(after*t/100); document.getElementById('quotation_total_preview').textContent=total.toFixed(2);}
async function saveQuotation(){const fd=new FormData(document.getElementById('quotationForm')); fd.append('action','save'); const res=await apiCall('handlers/quotations.php',fd); if(res.success){showToast('Quotation saved','success'); setTimeout(()=>location.reload(),500);} else showToast(res.message||'Error','error');}
async function editQuotation(id){const res=await apiCall('handlers/quotations.php',{action:'get',id}); if(!res.success){showToast(res.message||'Not found','error');return;} const d=res.data; openQuotationForm(); document.getElementById('quotationFormTitle').textContent='Edit Quotation'; ['id','customer_id','item_id','quantity','unit_price','discount','tva_percent','status','valid_until','notes'].forEach(k=>{let el=document.getElementById('quotation_'+k); if(el) el.value=d[k]||'';}); calcQuotationTotal();}
async function viewQuotation(id){const res=await apiCall('handlers/quotations.php',{action:'get',id}); if(!res.success){showToast(res.message||'Not found','error');return;} const d=res.data; document.getElementById('quotationViewBody').innerHTML=`<div class="card" style="padding:18px"><h2>Quotation QT-${String(d.id).padStart(5,'0')}</h2><p><b>Customer:</b> ${d.customer_name||''}</p><p><b>Item:</b> ${d.item_name||''}</p><p><b>Qty:</b> ${d.quantity} &nbsp; <b>Unit:</b> ${parseFloat(d.unit_price).toFixed(2)}</p><p><b>Discount:</b> ${parseFloat(d.discount).toFixed(2)} &nbsp; <b>TVA:</b> ${parseFloat(d.tva_percent).toFixed(2)}%</p><h3>Total: ${parseFloat(d.total).toFixed(2)}</h3><p><b>Status:</b> ${d.status}</p><p>${d.notes||''}</p></div>`; openModal('quotationViewModal');}
function printQuotation(id){viewQuotation(id); setTimeout(()=>window.print(),400);}
async function deleteQuotation(id){confirmAction('Delete this quotation?',async()=>{const res=await apiCall('handlers/quotations.php',{action:'delete',id}); if(res.success){showToast('Deleted','success'); document.getElementById('quotation_'+id)?.remove();}else showToast(res.message||'Error','error');});}
</script>
