<?php
requirePermission($conn, 'occasions', 'view');
if (!tableExists($conn, 'occasions')) { echo '<div class="alert alert-error">Occasions table not found. Run latest migration first.</div>'; return; }
function occasionReturnUrl(){ $q=$_GET; $q['page']='occasions'; unset($q['occasion_action'],$q['id'],$q['edit']); return 'index.php?'.http_build_query($q); }
$returnUrl = $_POST['return_to'] ?? occasionReturnUrl();
$action = $_POST['occasion_action'] ?? $_GET['occasion_action'] ?? '';
if ($_SERVER['REQUEST_METHOD']==='POST' && $action==='save') {
  $id=crmId($_POST['id']??0); $customer_id=crmId($_POST['customer_id']??0); $name=sanitize($conn,$_POST['name']??''); $date=sanitize($conn,$_POST['occasion_date']??''); $notes=sanitize($conn,$_POST['notes']??'');
  if(!$customer_id || !$name){ flash('error','Customer and occasion name are required'); redirect($returnUrl); }
  $dateSql=$date?"'$date'":'NULL';
  if($id){ $conn->query("UPDATE occasions SET customer_id=$customer_id,name='$name',occasion_date=$dateSql,notes='$notes' WHERE id=$id AND account_id=$account_id"); flash('success','Occasion updated'); }
  else { $conn->query("INSERT INTO occasions (account_id,customer_id,name,occasion_date,notes,added_by,date_created) VALUES ($account_id,$customer_id,'$name',$dateSql,'$notes',$user_id,NOW())"); flash('success','Occasion added'); }
  redirect($returnUrl);
}
if($action==='delete'){ $id=crmId($_GET['id']??0); if($id)$conn->query("DELETE FROM occasions WHERE id=$id AND account_id=$account_id"); flash('success','Occasion deleted'); redirect(occasionReturnUrl()); }
$search=trim($_GET['search']??''); $date_from=trim($_GET['date_from']??''); $date_to=trim($_GET['date_to']??'');
$where="o.account_id=$account_id";
if($search!==''){ $safe=sanitize($conn,$search); $where.=" AND (o.name LIKE '%$safe%' OR o.notes LIKE '%$safe%' OR c.customer_name LIKE '%$safe%' OR c.phone LIKE '%$safe%' OR c.email LIKE '%$safe%')"; }
if($date_from!==''){ $safe=sanitize($conn,$date_from); $where.=" AND o.occasion_date >= '$safe'"; }
if($date_to!==''){ $safe=sanitize($conn,$date_to); $where.=" AND o.occasion_date <= '$safe'"; }
$page_num=max(1,(int)($_GET['p']??1)); $per_page=25; $offset=($page_num-1)*$per_page;
$tq=$conn->query("SELECT COUNT(*) cnt FROM occasions o LEFT JOIN customers c ON c.id=o.customer_id WHERE $where"); $total=$tq?(int)$tq->fetch_assoc()['cnt']:0; $pages=max(1,(int)ceil($total/$per_page));
$list=$conn->query("SELECT o.*,c.customer_name,c.phone,c.email,u.name added_by_name FROM occasions o LEFT JOIN customers c ON c.id=o.customer_id LEFT JOIN users u ON u.id=o.added_by WHERE $where ORDER BY o.occasion_date IS NULL,o.occasion_date ASC,o.id DESC LIMIT $offset,$per_page");
$customers=$conn->query("SELECT id,customer_name,phone FROM customers WHERE account_id=$account_id ORDER BY customer_name ASC");
$customer_options=[];
if($customers){ while($c=$customers->fetch_assoc()){ $customer_options[]=$c; } }
$return_to=htmlspecialchars(occasionReturnUrl(), ENT_QUOTES);
?>
<div class="fade-in occasions-page">
  <div class="toolbar" style="justify-content:space-between;gap:12px;flex-wrap:wrap"><div><span class="card-title">Occasions</span><div class="text-xs text-muted">Customer birthdays / events / special dates</div></div><button class="btn btn-primary" onclick="openOccasionModal()">+ Add Occasion</button></div>
  <div class="card" style="padding:14px 16px;margin-bottom:16px"><form method="get" class="occasions-filter"><input type="hidden" name="page" value="occasions"><div class="form-group"><label class="form-label">Search</label><input class="form-control" name="search" value="<?= htmlspecialchars($search) ?>" placeholder="Search customer, phone, occasion..."></div><div class="form-group"><label class="form-label">From</label><input class="form-control" type="date" name="date_from" value="<?= htmlspecialchars($date_from) ?>"></div><div class="form-group"><label class="form-label">To</label><input class="form-control" type="date" name="date_to" value="<?= htmlspecialchars($date_to) ?>"></div><div class="form-group"><button class="btn btn-primary">Search</button> <a class="btn btn-secondary" href="index.php?page=occasions">Clear</a></div></form></div>
  <div class="card"><div class="table-wrapper"><table class="crm-table"><thead><tr><th>Customer</th><th>Phone</th><th>Occasion</th><th>Date</th><th>Notes</th><th>Added By</th><th>Actions</th></tr></thead><tbody><?php if(!$list||!$list->num_rows): ?><tr><td colspan="7" class="text-center text-muted" style="padding:32px">No occasions found</td></tr><?php else: while($o=$list->fetch_assoc()): ?><tr><td><?= htmlspecialchars($o['customer_name']?:'—') ?></td><td><?= htmlspecialchars($o['phone']?:'—') ?></td><td><strong><?= htmlspecialchars($o['name']) ?></strong></td><td><?= htmlspecialchars($o['occasion_date']?:'—') ?></td><td><?= htmlspecialchars($o['notes']?:'—') ?></td><td><?= htmlspecialchars($o['added_by_name'] ?: '—') ?></td><td><button class="btn btn-warning btn-sm" onclick="openOccasionModal('<?= crmEid($o['id']) ?>','<?= crmEid($o['customer_id']) ?>','<?= htmlspecialchars(($o['customer_name']?:'') . ($o['phone']?' - '.$o['phone']:''),ENT_QUOTES) ?>','<?= htmlspecialchars($o['name'],ENT_QUOTES) ?>','<?= htmlspecialchars($o['occasion_date'],ENT_QUOTES) ?>','<?= htmlspecialchars($o['notes'],ENT_QUOTES) ?>')">Edit</button> <a class="btn btn-danger btn-sm" onclick="return confirm('Delete this occasion?')" href="index.php?page=occasions&occasion_action=delete&id=<?= crmEid($o['id']) ?>&<?= http_build_query(array_diff_key($_GET,['page'=>1,'occasion_action'=>1,'id'=>1])) ?>">Delete</a></td></tr><?php endwhile; endif; ?></tbody></table></div><div class="list-footer"><div class="list-count">Showing <?= $total?($offset+1).' - '.min($offset+($list?$list->num_rows:0),$total):'0' ?> of <?= $total ?></div><div class="pagination"><?php if($page_num>1): $q=$_GET; $q['p']=$page_num-1; ?><a class="btn btn-secondary btn-sm" href="?<?= http_build_query($q) ?>">‹</a><?php endif; ?><span class="btn btn-primary btn-sm"><?= $page_num ?> / <?= $pages ?></span><?php if($page_num<$pages): $q=$_GET; $q['p']=$page_num+1; ?><a class="btn btn-secondary btn-sm" href="?<?= http_build_query($q) ?>">›</a><?php endif; ?></div></div></div>
</div>
<div class="modal-overlay" id="occasionModal"><div class="modal"><div class="modal-header"><span class="modal-title" id="occasionModalTitle">Add Occasion</span><button class="modal-close" type="button" onclick="closeModal('occasionModal')">✕</button></div><form method="post" onsubmit="return syncOccasionCustomerId()"><div class="modal-body"><input type="hidden" name="occasion_action" value="save"><input type="hidden" name="return_to" value="<?= $return_to ?>"><input type="hidden" name="id" id="occ_id"><input type="hidden" name="customer_id" id="occ_customer_id"><div class="form-grid"><div class="form-group span-2"><label class="form-label">Customer *</label><input list="occ_customer_list" id="occ_customer_text" class="form-control" required placeholder="Type customer name or phone"><datalist id="occ_customer_list"><?php foreach($customer_options as $c): $label=$c['customer_name'].($c['phone']?' - '.$c['phone']:''); ?><option value="<?= htmlspecialchars($label, ENT_QUOTES) ?>" data-id="<?= crmEid($c['id']) ?>"></option><?php endforeach; ?></datalist><div class="text-xs text-muted" style="margin-top:5px">Start typing and choose customer from the list.</div></div><div class="form-group"><label class="form-label">Occasion Name *</label><input class="form-control" name="name" id="occ_name" required placeholder="Birthday / Renewal"></div><div class="form-group"><label class="form-label">Date</label><input class="form-control" type="date" name="occasion_date" id="occ_date"></div><div class="form-group span-2"><label class="form-label">Notes</label><input class="form-control" name="notes" id="occ_notes" placeholder="Notes..."></div></div></div><div class="modal-footer"><button type="button" class="btn btn-secondary" onclick="closeModal('occasionModal')">Cancel</button><button class="btn btn-primary" id="occ_save_btn">Save</button></div></form></div></div>
<script>
function openOccasionModal(id='',customer='',customerText='',name='',date='',notes=''){
  document.getElementById('occasionModalTitle').textContent = id ? 'Edit Occasion' : 'Add Occasion';
  document.getElementById('occ_id').value = id || '';
  document.getElementById('occ_customer_id').value = customer || '';
  document.getElementById('occ_customer_text').value = customerText || '';
  document.getElementById('occ_name').value = name || '';
  document.getElementById('occ_date').value = date || '';
  document.getElementById('occ_notes').value = notes || '';
  openModal('occasionModal');
}
function syncOccasionCustomerId(){
  const input = document.getElementById('occ_customer_text');
  const hidden = document.getElementById('occ_customer_id');
  const options = document.querySelectorAll('#occ_customer_list option');
  let found = '';
  options.forEach(o => { if(o.value === input.value) found = o.dataset.id || ''; });
  if(found) hidden.value = found;
  if(!hidden.value){ showToast('Please choose customer from the list', 'warning'); return false; }
  return true;
}
document.getElementById('occ_customer_text')?.addEventListener('input', syncOccasionCustomerId);
</script>
