<?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');

$quotation_search = isset($_GET['quotation_search']) ? sanitize($conn, $_GET['quotation_search']) : '';
$status_filter = isset($_GET['status']) ? sanitize($conn, $_GET['status']) : '';
$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");
$whereQ = "q.account_id=$account_id";
if ($quotation_search) $whereQ .= " AND (c.customer_name LIKE '%$quotation_search%' OR i.name LIKE '%$quotation_search%' OR q.notes LIKE '%$quotation_search%')";
if ($status_filter) $whereQ .= " AND q.status='$status_filter'";
$totalQ = $conn->query("SELECT COUNT(*) total FROM quotations q LEFT JOIN customers c ON c.id=q.customer_id LEFT JOIN items i ON i.id=q.item_id WHERE $whereQ");
$total_rows = $totalQ ? (int)$totalQ->fetch_assoc()['total'] : 0;
$q = $conn->query("SELECT q.*, c.customer_name, i.name item_name, u.name added_by_name FROM quotations q LEFT JOIN customers c ON c.id=q.customer_id LEFT JOIN items i ON i.id=q.item_id LEFT JOIN users u ON u.id=q.created_by WHERE $whereQ ORDER BY q.id DESC LIMIT 300");
?>
<div class="fade-in quotations-page">
  <div class="toolbar" style="gap:10px;flex-wrap:wrap">
    <span class="card-title">Quotations</span>
    <form method="get" class="d-flex gap-8" style="flex-wrap:wrap;margin-left:auto"><input type="hidden" name="page" value="quotations"><input type="text" name="quotation_search" class="form-control" style="width:220px" placeholder="Search quotations..." value="<?= htmlspecialchars($quotation_search) ?>"><select name="status" class="form-control" style="width:140px"><option value="">All Status</option><?php foreach(['draft','sent','accepted','rejected'] as $st): ?><option value="<?= $st ?>" <?= $status_filter===$st?'selected':'' ?>><?= ucfirst($st) ?></option><?php endforeach; ?></select><button class="btn btn-primary">Search</button><a href="index.php?page=quotations" class="btn btn-secondary">Clear</a></form>
    <?php if($canAdd): ?><button class="btn btn-primary" 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">Customer Details</label><textarea name="customer_details" id="quotation_customer_details" class="form-control" rows="2" placeholder="Address, phone, company info..."></textarea></div><div class="form-group"><label class="form-label">Reminder Date</label><input type="date" name="reminder_date" id="quotation_reminder_date" class="form-control"></div><div class="form-group"><label class="form-label">Reminder Time</label><input type="time" name="reminder_time" id="quotation_reminder_time" class="form-control"></div><div class="form-group span-2"><label class="form-label">Reminder Note</label><textarea name="reminder_note" id="quotation_reminder_note" class="form-control" rows="2" placeholder="Follow up with customer..."></textarea></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="text-xs text-muted" style="margin:8px 0 12px;">Total quotations: <strong><?= number_format($total_rows) ?></strong></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>Added By</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><?= htmlspecialchars($row['added_by_name'] ?: '—') ?></td><td><?= formatDate($row['date_created']) ?></td><td style="display:flex;gap:6px;flex-wrap:wrap">
          <?php if($canOpen): ?><a class="btn btn-secondary btn-sm" href="index.php?page=quotation_invoice&id=<?= $row['id'] ?>">Open</a><?php endif; ?>
          <?php if($canEdit): ?><button class="btn btn-warning btn-sm" onclick="editQuotation(<?= $row['id'] ?>)">Edit</button><?php endif; ?>
          <?php if($canPrint): ?><a class="btn btn-primary btn-sm" target="_blank" href="index.php?page=quotation_invoice&id=<?= $row['id'] ?>&print=1">Print</a><?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','customer_details','reminder_date','reminder_time','reminder_note'].forEach(k=>{let el=document.getElementById('quotation_'+k); if(el) el.value=d[k]||'';}); calcQuotationTotal();}
function viewQuotation(id){ window.location.href='index.php?page=quotation_invoice&id='+id; }
function printQuotation(id){ window.open('index.php?page=quotation_invoice&id='+id+'&print=1','_blank'); }
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>
