<?php
requirePermission($conn, 'quotations', 'view');
$canAdd = userCan($conn,'quotations','add');
$canEdit = userCan($conn,'quotations','edit');
$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']) : '';
$page_num=max(1,(int)($_GET['p']??1)); $per_page=25; $offset=($page_num-1)*$per_page;
$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, currency 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;
$total_pages=max(1,(int)ceil($total_rows/$per_page));
$q = $conn->query("SELECT q.*, c.customer_name, i.name item_name, u.name added_by_name, a.currency account_currency 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 LEFT JOIN accounts a ON a.id=q.account_id WHERE $whereQ ORDER BY q.id DESC LIMIT $offset,$per_page");
?>
<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>
  <style>.qitem-row{padding:12px!important}.qitem-row .form-grid{grid-template-columns:2fr .6fr .8fr auto}.qitem-row label{font-size:11px;color:var(--text-muted);font-weight:700}.quotation-note-help{background:#f8fafc;border:1px solid var(--border);border-radius:12px;padding:10px 12px;margin-top:6px;color:var(--text-muted);font-size:12px}.quotation-total-box{background:#eff6ff;border:1px solid #bfdbfe;color:#1d4ed8;border-radius:12px;padding:10px 14px;font-weight:800}.crm-table.quotation-items-table th,.crm-table.quotation-items-table td{padding:10px 12px}</style>
  <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 span-2"><label class="form-label">Items *</label><div id="quotationItemsRows"></div><button type="button" class="btn btn-secondary btn-sm" onclick="addQuotationItemRow()">+ Add Item</button><input type="hidden" name="items_json" id="quotation_items_json"></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">Notes</label><textarea name="notes" id="quotation_notes" class="form-control" rows="3"></textarea><div class="quotation-note-help">Write short internal note here. It has more padding now so it does not stick to card edge.</div></div>
      </div><div style="display:flex;justify-content:space-between;align-items:center;margin-top:14px;gap:10px;flex-wrap:wrap"><div class="quotation-total-box">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>
    <?php if(!$q || $q->num_rows===0): ?><tr><td colspan="7" class="text-center text-muted" style="padding:34px">No quotations found</td></tr><?php else: 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'] ?: 'Multiple items') ?></td><td><?= crmMoney($row['total'], $row['account_currency'] ?: 'USD') ?></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): ?><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; ?></td></tr>
    <?php endwhile; endif; ?></tbody></table></div><div class="list-footer"><div class="list-count">Showing <strong><?= $total_rows ? number_format($offset + 1) : 0 ?> – <?= number_format(min($offset + ($q?$q->num_rows:0), $total_rows)) ?></strong> of <strong><?= number_format($total_rows) ?></strong> quotations</div><div class="pagination"><?php if($total_pages>1): $baseParams=$_GET; $baseParams['page']='quotations'; unset($baseParams['p']); if($page_num>1): $baseParams['p']=$page_num-1; ?><a class="btn btn-secondary btn-sm" href="?<?= http_build_query($baseParams) ?>">‹</a><?php endif; ?><span class="btn btn-primary btn-sm">Page <?= $page_num ?> / <?= $total_pages ?></span><?php if($page_num<$total_pages): $baseParams['p']=$page_num+1; ?><a class="btn btn-secondary btn-sm" href="?<?= http_build_query($baseParams) ?>">›</a><?php endif; endif; ?></div></div></div>
</div>
<script>
const quotationItems = <?= json_encode($items->fetch_all(MYSQLI_ASSOC)) ?>;
const PRICE_DECIMALS = Number(window.CRM_PRICE_DECIMALS ?? 2);
function escapeHtml(t){const d=document.createElement('div');d.textContent=t||'';return d.innerHTML;}
function formatMoney(amount,currency){ const n=parseFloat(amount||0); const out=n.toLocaleString(undefined,{minimumFractionDigits:PRICE_DECIMALS,maximumFractionDigits:PRICE_DECIMALS}); currency=(currency||'USD').toUpperCase(); return currency==='USD'?'$'+out:out+' '+currency; }
function qItemOptions(){ return '<option value="">Select item</option>'+quotationItems.map(it=>`<option value="${it.id}" data-price="${it.price}" data-currency="${it.currency||'USD'}">${escapeHtml(it.name)} - ${formatMoney(it.price,it.currency||'USD')}</option>`).join(''); }
function addQuotationItemRow(data={}){ const wrap=document.getElementById('quotationItemsRows'); const div=document.createElement('div'); div.className='muted-box qitem-row'; div.style.marginBottom='8px'; div.innerHTML=`<div class="form-grid"><div class="form-group"><label>Item Name / Description</label><select class="form-control qi-item" onchange="this.closest('.qitem-row').querySelector('.qi-price').value=this.selectedOptions[0]?.dataset.price||0; calcQuotationTotal()">${qItemOptions()}</select></div><div class="form-group"><label>Qty</label><input type="number" class="form-control qi-qty" min="1" step="1" value="${data.quantity||1}" oninput="calcQuotationTotal()"></div><div class="form-group"><label>Unit Price</label><input type="number" class="form-control qi-price" min="0" step="0.01" value="${data.unit_price||0}" oninput="calcQuotationTotal()"></div><div class="form-group"><label>&nbsp;</label><button type="button" class="btn btn-danger btn-sm" onclick="this.closest('.qitem-row').remove();calcQuotationTotal()">Remove</button></div></div>`; wrap.appendChild(div); if(data.item_id){ div.querySelector('.qi-item').value=data.item_id; } calcQuotationTotal(); }
function collectQuotationItems(){ const rows=[...document.querySelectorAll('.qitem-row')].map(r=>({item_id:r.querySelector('.qi-item').value, quantity:r.querySelector('.qi-qty').value, unit_price:r.querySelector('.qi-price').value})).filter(x=>x.item_id); document.getElementById('quotation_items_json').value=JSON.stringify(rows); return rows; }
function openQuotationForm(){document.getElementById('quotationFormCard').style.display='block';document.getElementById('quotationFormTitle').textContent='New Quotation';document.getElementById('quotationForm').reset();document.getElementById('quotation_id').value=0;document.getElementById('quotationItemsRows').innerHTML='';addQuotationItemRow();calcQuotationTotal();window.scrollTo({top:0,behavior:'smooth'});} function closeQuotationForm(){document.getElementById('quotationFormCard').style.display='none';}
function calcQuotationTotal(){let sub=0; document.querySelectorAll('.qitem-row').forEach(r=>{sub+=(parseFloat(r.querySelector('.qi-qty').value)||0)*(parseFloat(r.querySelector('.qi-price').value)||0)}); let d=parseFloat(document.getElementById('quotation_discount').value)||0, t=parseFloat(document.getElementById('quotation_tva_percent').value)||0; let after=Math.max(0,sub-d); let total=after+(after*t/100); document.getElementById('quotation_total_preview').textContent=formatMoney(total,'USD');}
async function saveQuotation(){collectQuotationItems(); 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('quotationItemsRows').innerHTML=''; (res.items&&res.items.length?res.items:[{item_id:d.item_id,quantity:d.quantity,unit_price:d.unit_price}]).forEach(addQuotationItemRow); document.getElementById('quotationFormTitle').textContent='Edit Quotation'; ['id','customer_id','discount','tva_percent','status','valid_until','notes','customer_details','reminder_date','reminder_time'].forEach(k=>{let el=document.getElementById('quotation_'+k); if(el) el.value=d[k]||'';}); calcQuotationTotal();}
</script>
