<?php
require_once __DIR__ . '/../lib/audience_rules.php';
$isEdit = ($_GET['page'] ?? '') === 'audience_edit';
$id = crmId($_GET['id'] ?? 0);
$aud = ['name'=>'','description'=>'','statuss'=>1,'rules_json'=>''];
if ($isEdit) { $q=$conn->query("SELECT * FROM audience WHERE id=$id AND account_id=$account_id LIMIT 1"); if($q&&$q->num_rows)$aud=$q->fetch_assoc(); else { echo '<div class="alert alert-error">Audience not found</div>'; return; } }
$rules = crm_decode_rules($aud['rules_json'] ?? '');
$countries=$conn->query("SELECT c.id,c.name FROM country_account ca INNER JOIN countries c ON c.id=ca.country_id WHERE ca.account_id=$account_id ORDER BY c.name");
$labels=$conn->query("SELECT id,name,color FROM customer_lable WHERE account_id=$account_id AND status=1 ORDER BY name");
$sources=tableExists($conn,'customer_sources') ? $conn->query("SELECT id,name FROM customer_sources WHERE account_id=$account_id AND datetime_deleted IS NULL ORDER BY name") : (tableExists($conn,'source') ? $conn->query("SELECT id,name FROM source WHERE account_id=$account_id ORDER BY name") : false);
$items=$conn->query("SELECT id,name FROM items WHERE account_id=$account_id ORDER BY name");
$manualCustomers=$conn->query("SELECT id,customer_name,business_name,phone FROM customers WHERE account_id=$account_id ORDER BY customer_name ASC");
function checkedIn($arr,$id){ return in_array((int)$id, array_map('intval',$arr??[])) ? 'checked' : ''; }
?>
<div class="fade-in audience-form-page">
  <div class="toolbar"><a href="index.php?page=audience" class="btn btn-secondary">← Back</a></div>
  <div class="card" style="padding:20px;max-width:1100px;">
    <h3 style="margin-top:0"><?= $isEdit?'Edit':'Add' ?> Audience</h3>
    <form id="audienceForm">
      <input type="hidden" name="action" value="save"><input type="hidden" name="id" value="<?= crmEid($id) ?>"><input type="hidden" name="return_to" value="<?= htmlspecialchars($_GET['return_to'] ?? 'index.php?page=audience') ?>">
      <div class="form-grid">
        <div class="form-group"><label class="form-label">Audience Name *</label><input name="name" required class="form-control" value="<?= htmlspecialchars($aud['name']) ?>"></div>
        <div class="form-group"><label class="form-label">Status</label><select name="statuss" class="form-control"><option value="1" <?= (int)$aud['statuss']?'selected':'' ?>>Active</option><option value="0" <?= !(int)$aud['statuss']?'selected':'' ?>>Inactive</option></select></div>
      </div>
      <div class="form-group"><label class="form-label">Description</label><textarea name="description" class="form-control" rows="2"><?= htmlspecialchars($aud['description']) ?></textarea></div>
      <div class="hr"></div>
      <h4>Audience Filters</h4><div class="alert alert-info" style="margin-bottom:12px">Choose filters then save the audience.</div><input type="text" class="form-control" placeholder="Quick search inside open filter lists..." oninput="quickFilterChecks(this.value)" style="margin-bottom:12px">
      <div class="filter-accordion">
        <div class="filter-card"><button type="button" class="filter-head" onclick="toggleFilterBox(this)"><span>🌍 By Country</span><small>Lebanon / Qatar / ...</small></button><div class="filter-body"><div class="check-list"><?php while($r=$countries->fetch_assoc()): ?><label><input type="checkbox" name="country_ids[]" value="<?= $r['id'] ?>" <?= checkedIn($rules['country_ids']??[],$r['id']) ?>> <?= htmlspecialchars($r['name']) ?></label><?php endwhile; ?></div></div></div>
        <div class="filter-card"><button type="button" class="filter-head" onclick="toggleFilterBox(this)"><span>⭐ By Priority</span><small>1 to 5 stars</small></button><div class="filter-body"><div class="check-list"><?php for($i=1;$i<=5;$i++): ?><label><input type="checkbox" name="priority[]" value="<?= $i ?>" <?= checkedIn($rules['priority']??[],$i) ?>> <?= str_repeat('★',$i) ?></label><?php endfor; ?></div></div></div>

        <div class="filter-card"><button type="button" class="filter-head" onclick="toggleFilterBox(this)"><span>🧭 By Source</span><small>Customer source</small></button><div class="filter-body"><div class="check-list"><?php if($sources): while($r=$sources->fetch_assoc()): ?><label><input type="checkbox" name="source_ids[]" value="<?= $r['id'] ?>" <?= checkedIn($rules['source_ids']??[],$r['id']) ?>> <?= htmlspecialchars($r['name']) ?></label><?php endwhile; else: ?><span class="text-muted text-xs">No sources found.</span><?php endif; ?></div></div></div>
        <div class="filter-card"><button type="button" class="filter-head" onclick="toggleFilterBox(this)"><span>🏷️ By Labels</span><small>Website / App / Pending</small></button><div class="filter-body"><div class="check-list"><?php while($r=$labels->fetch_assoc()): ?><label><input type="checkbox" name="label_ids[]" value="<?= $r['id'] ?>" <?= checkedIn($rules['label_ids']??[],$r['id']) ?>> <span class="label-dot" style="background:<?= htmlspecialchars($r['color']) ?>"></span><?= htmlspecialchars($r['name']) ?></label><?php endwhile; ?></div></div></div>
        <div class="filter-card"><button type="button" class="filter-head" onclick="toggleFilterBox(this)"><span>📌 By Leads / Items</span><small>Has leads or leads on specific items</small></button><div class="filter-body"><div class="check-list"><label><input type="checkbox" name="has_leads" value="1" <?= !empty($rules['has_leads'])?'checked':'' ?>> Customers who have leads</label></div><label class="form-label" style="margin-top:12px">Lead Items</label><div class="check-list"><?php while($r=$items->fetch_assoc()): ?><label><input type="checkbox" name="item_ids[]" value="<?= $r['id'] ?>" <?= checkedIn($rules['item_ids']??[],$r['id']) ?>> <?= htmlspecialchars($r['name']) ?></label><?php endwhile; ?></div></div></div>
        <div class="filter-card"><button type="button" class="filter-head" onclick="toggleFilterBox(this)"><span>👥 Pick Customers Manually</span><small>Add specific people even if filters do not match</small></button><div class="filter-body"><input type="text" class="form-control" placeholder="Search customer..." oninput="filterManualCustomers(this.value)" style="margin-bottom:10px"><div class="check-list manual-customers" id="manualCustomersList"><?php while($r=$manualCustomers->fetch_assoc()): ?><label data-text="<?= strtolower(htmlspecialchars($r['customer_name'].' '.$r['business_name'].' '.$r['phone'])) ?>"><input type="checkbox" name="customer_ids[]" value="<?= $r['id'] ?>" <?= checkedIn($rules['customer_ids']??[],$r['id']) ?>> <strong><?= htmlspecialchars($r['customer_name']) ?></strong><span class="text-muted text-xs"><?= htmlspecialchars($r['business_name'] ?: $r['phone'] ?: '') ?></span></label><?php endwhile; ?></div></div></div>
      </div>
      <div class="hr"></div><div class="d-flex gap-8"><button type="button" class="btn btn-primary" onclick="saveAudience()">Save Audience</button></div>
    </form>
  </div>
</div>
<style>.filter-accordion{display:grid;gap:12px}.filter-card{border:1px solid var(--border);border-radius:14px;background:var(--bg-base);overflow:hidden}.filter-head{width:100%;display:flex;justify-content:space-between;align-items:center;padding:14px 16px;border:0;background:white;cursor:pointer;font-weight:700;color:var(--text-primary)}.filter-head small{font-weight:400;color:var(--text-muted)}.filter-body{display:none;padding:14px 16px;border-top:1px solid var(--border)}.filter-card.open .filter-body{display:block}.check-list{display:grid;gap:8px;max-height:240px;overflow:auto;padding:10px;border:1px solid var(--border);border-radius:10px;background:white}.check-list label{display:flex;gap:8px;align-items:center}.manual-customers label{justify-content:flex-start}.label-dot{display:inline-block;width:10px;height:10px;border-radius:50%}</style>
<script>
function toggleFilterBox(btn){btn.closest('.filter-card').classList.toggle('open')}
function filterManualCustomers(q){q=(q||'').toLowerCase();document.querySelectorAll('#manualCustomersList label').forEach(l=>{l.style.display=(!q||l.dataset.text.includes(q))?'flex':'none'});}
function quickFilterChecks(q){q=(q||'').toLowerCase();document.querySelectorAll('.check-list label').forEach(l=>{const t=(l.innerText||l.textContent||'').toLowerCase();l.style.display=(!q||t.includes(q))?'flex':'none'});}
async function previewAudience(){const fd=new FormData(document.getElementById('audienceForm'));fd.set('action','preview');const r=await apiCall('handlers/audience.php',fd);document.getElementById('audiencePreview').innerHTML=r.success?`<div class="alert alert-info"><strong>${r.count}</strong> customers match</div>`+(r.html||''):`<div class="alert alert-error">${r.message||'Error'}</div>`}
async function saveAudience(){const fd=new FormData(document.getElementById('audienceForm'));const r=await apiCall('handlers/audience.php',fd);if(r.success){showToast('Audience saved. '+r.count+' customers refreshed','success');setTimeout(()=>location.href=(r.redirect||'index.php?page=audience'),700)}else showToast(r.message||'Error','error')}
</script>
