<?php
requirePermission($conn, 'customers', 'add');
$countries = $conn->query("SELECT c.id,c.name,c.phone_code,ca.is_default FROM country_account ca INNER JOIN countries c ON c.id=ca.country_id WHERE ca.account_id=$account_id ORDER BY ca.is_default DESC,c.name ASC");
$countriesList=[]; $defaultCountryId=''; $defaultPhoneCode='';
while($r=$countries->fetch_assoc()){ if((int)$r['is_default']===1){$defaultCountryId=$r['id'];$defaultPhoneCode=$r['phone_code'];} $countriesList[]=$r; }
if(!$defaultCountryId && count($countriesList)){ $defaultCountryId=$countriesList[0]['id']; $defaultPhoneCode=$countriesList[0]['phone_code']; }
?>
<div class="fade-in">
  <div class="toolbar" style="justify-content:space-between">
    <div><h3 style="margin:0">Add Customer</h3><div class="text-xs text-muted">Create a new customer</div></div>
    <a href="index.php?page=customers" class="btn btn-secondary">← Back</a>
  </div>
  <div class="card" style="padding:20px;max-width:980px">
    <form id="customerPageForm">
      <div class="form-grid">
        <div class="form-group"><label class="form-label">Customer Name *</label><input type="text" name="customer_name" class="form-control" required></div>
        <div class="form-group"><label class="form-label">Business Name</label><input type="text" name="business_name" class="form-control"></div>
        <div class="form-group"><label class="form-label">Phone</label><div class="d-flex" style="gap:8px"><select name="phone_code" id="phone_code" class="form-control" style="width:120px"><?php if(!count($countriesList)): ?><option value="">Select</option><?php endif; ?><?php foreach($countriesList as $country): ?><option value="<?= htmlspecialchars($country['phone_code']) ?>" data-country-id="<?= $country['id'] ?>" <?= ($defaultPhoneCode==$country['phone_code'])?'selected':'' ?>><?= htmlspecialchars($country['phone_code']) ?></option><?php endforeach; ?></select><input type="text" name="phone" id="phone_number" class="form-control" placeholder="Phone number"></div></div>
        <div class="form-group"><label class="form-label">Email</label><input type="email" name="email" class="form-control"></div>
        <div class="form-group"><label class="form-label">Country</label><select name="country_id" id="customer_country_id" class="form-control"><option value="">Select</option><?php foreach($countriesList as $country): ?><option value="<?= $country['id'] ?>" <?= ($defaultCountryId==$country['id'])?'selected':'' ?>><?= htmlspecialchars($country['name']) ?></option><?php endforeach; ?></select></div>
        <div class="form-group"><label class="form-label">Priority</label><select name="priority" class="form-control"><option value="1">★ 1</option><option value="2">★★ 2</option><option value="3" selected>★★★ 3</option><option value="4">★★★★ 4</option><option value="5">★★★★★ 5</option></select></div>
      </div>
      <div class="form-grid"><div class="form-group"><label class="form-label">Address</label><textarea name="address" class="form-control" rows="3"></textarea></div><div class="form-group"><label class="form-label">Notes</label><textarea name="notes" class="form-control" rows="3"></textarea></div></div>
      <div class="hr"></div><div class="d-flex justify-between align-center mb-12"><label class="form-label mb-0">Contacts</label><button type="button" class="btn btn-secondary btn-sm" onclick="addContactRowPage()">+ Add Contact</button></div><div id="contactsContainer"></div>
      <div class="d-flex gap-8" style="justify-content:flex-end;margin-top:18px"><a href="index.php?page=customers" class="btn btn-secondary">Cancel</a><button type="submit" class="btn btn-primary">Save Customer</button></div>
    </form>
  </div>
</div>
<script>
const countriesList = <?= json_encode($countriesList) ?>; let contactCount=0;
document.getElementById('phone_code').addEventListener('change',function(){ const opt=this.options[this.selectedIndex]; if(opt && opt.dataset.countryId) document.getElementById('customer_country_id').value=opt.dataset.countryId; });
document.getElementById('customer_country_id').addEventListener('change',function(){ const c=countriesList.find(x=>String(x.id)===String(this.value)); if(c) document.getElementById('phone_code').value=c.phone_code; });
function addContactRowPage(){contactCount++;const i=contactCount;const div=document.createElement('div');div.id='contact_row_'+i;div.style.cssText='background:var(--bg-base);border:1px solid var(--border);border-radius:8px;padding:12px;margin-bottom:8px';div.innerHTML=`<div class="form-grid"><div class="form-group mb-0"><label class="form-label">Name</label><input type="text" name="contacts[${i}][name]" class="form-control"></div><div class="form-group mb-0"><label class="form-label">Job Title</label><input type="text" name="contacts[${i}][job_title]" class="form-control"></div><div class="form-group mb-0"><label class="form-label">Phone</label><input type="text" name="contacts[${i}][phone]" class="form-control"></div><div class="form-group mb-0"><label class="form-label">Email</label><input type="email" name="contacts[${i}][email]" class="form-control"></div></div><button type="button" class="btn btn-danger btn-sm" style="margin-top:8px" onclick="document.getElementById('contact_row_${i}').remove()">Remove</button>`;document.getElementById('contactsContainer').appendChild(div)}
document.getElementById('customerPageForm').addEventListener('submit',async function(e){e.preventDefault();const fd=new FormData(this);fd.append('action','add');const pn=(document.getElementById('phone_number').value||'').replace(/\D/g,''); if(pn){fd.set('phone',(document.getElementById('phone_code').value||'')+pn)} const res=await apiCall('handlers/customers.php',fd); if(res.success){showToast('Customer added','success'); setTimeout(()=>location.href='index.php?page=customers',500)} else showToast(res.message||'Error','error');});
</script>
