<?php
$canCustomerAdd = userCan($conn, 'customers', 'add');
$canCustomerEdit = userCan($conn, 'customers', 'edit');
$canCustomerDelete = userCan($conn, 'customers', 'delete');
$canCustomerMessage = userCan($conn, 'customers', 'message');

// =============================================
// SHARK CRM - Customers Page
// =============================================

$page = isset($_GET['page_num']) ? max(1, (int)$_GET['page_num']) : 1;
$limit = defined('CRM_DEFAULT_PER_PAGE') ? CRM_DEFAULT_PER_PAGE : 30;
$offset = ($page - 1) * $limit;

$search          = isset($_GET['search'])          ? sanitize($conn, $_GET['search'])          : '';
$filter_customer = isset($_GET['filter_customer']) ? sanitize($conn, $_GET['filter_customer']) : '';
$filter_business = isset($_GET['filter_business']) ? sanitize($conn, $_GET['filter_business']) : '';
$filter_phone    = isset($_GET['filter_phone'])    ? sanitize($conn, $_GET['filter_phone'])    : '';
$filter_email    = isset($_GET['filter_email'])    ? sanitize($conn, $_GET['filter_email'])    : '';
$filter_country  = isset($_GET['filter_country'])  ? (int)$_GET['filter_country'] : '';
$filter_priority = isset($_GET['filter_priority']) ? (int)$_GET['filter_priority'] : '';
$filter_source   = isset($_GET['filter_source']) && $_GET['filter_source'] !== '' ? (int)$_GET['filter_source'] : 0;
$date_from       = isset($_GET['date_from'])       ? sanitize($conn, $_GET['date_from']) : '';
$date_to         = isset($_GET['date_to'])         ? sanitize($conn, $_GET['date_to']) : '';
$date_exact      = isset($_GET['date_exact'])      ? sanitize($conn, $_GET['date_exact']) : '';
$filter_added_by  = isset($_GET['filter_added_by']) && $_GET['filter_added_by'] !== '' ? (int)$_GET['filter_added_by'] : 0;
$defaultCountryId = '';
$defaultPhoneCode = '';

$filter_leads_count = isset($_GET['filter_leads_count'])
    ? (int)$_GET['filter_leads_count']
    : '';
    
    

$where = "c.account_id = $account_id";

if ($filter_customer) $where .= " AND c.customer_name LIKE '%$filter_customer%'";
if ($filter_business) $where .= " AND c.business_name LIKE '%$filter_business%'";
if ($filter_phone)    $where .= " AND c.phone LIKE '%$filter_phone%'";
if ($filter_email)    $where .= " AND c.email LIKE '%$filter_email%'";
if ($filter_country)  $where .= " AND c.country_id = $filter_country";
if ($filter_priority) $where .= " AND c.priority = $filter_priority";
if ($filter_source)   $where .= " AND c.source_id = $filter_source";
if ($date_from)       $where .= " AND DATE(c.date_created) >= '$date_from'";
if ($date_to)         $where .= " AND DATE(c.date_created) <= '$date_to'";
if ($date_exact)      $where .= " AND DATE(c.date_created) = '$date_exact'";
if ($filter_added_by) $where .= " AND c.created_by_user_id = $filter_added_by";

if ($search && !$filter_customer && !$filter_business && !$filter_phone && !$filter_email) {
    $where .= " AND (c.customer_name LIKE '%$search%' OR c.business_name LIKE '%$search%' OR c.email LIKE '%$search%' OR c.phone LIKE '%$search%')";
}



$totalQuerySql = "
    SELECT COUNT(*) as total
    FROM (
        SELECT c.id
        FROM customers c
        LEFT JOIN `source` src ON src.id=c.source_id AND src.account_id=c.account_id
        LEFT JOIN leads l
            ON l.customer_id = c.id
           AND l.datetime_deleted IS NULL
        WHERE $where
        GROUP BY c.id
";

if ($filter_leads_count !== '') {
    $totalQuerySql .= "
        HAVING COUNT(l.id) >= $filter_leads_count
    ";
}

$totalQuerySql .= ") x";

$total_query = $conn->query($totalQuerySql);


// $total_query = $conn->query("SELECT COUNT(DISTINCT c.id) as total FROM customers c WHERE $where");
$total_rows = $total_query->fetch_assoc()['total'];
$total_pages = ceil($total_rows / $limit);



// Fetch countries for dropdown


$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 = [];
while ($row = $countries->fetch_assoc()) {
    if ((int)$row['is_default'] === 1) {
        $defaultCountryId = $row['id'];
        $defaultPhoneCode = $row['phone_code'];
    }
    $countriesList[] = $row;
}
if (!$defaultCountryId && count($countriesList)) {
    $defaultCountryId = $countriesList[0]['id'];
    $defaultPhoneCode = $countriesList[0]['phone_code'];
}

$having = '';

if ($filter_leads_count !== '') {
    $having = "HAVING COUNT(l.id) >= $filter_leads_count";
}

$sourcesFilter = $conn->query("SELECT id,name FROM `source` WHERE account_id=$account_id AND datetime_deleted IS NULL AND status=1 ORDER BY name");
$usersForFilter = $conn->query("SELECT id, name FROM users WHERE account_id = $account_id ORDER BY name");
$usersList = [];
if ($usersForFilter) { while ($ur = $usersForFilter->fetch_assoc()) $usersList[] = $ur; }

$customers = $conn->query("
  SELECT
    c.*,
    src.name AS source_name,
    COUNT(l.id) as leads_count,
    co.name as country_name,
    co.phone_code,
    u.name as created_by_name

  FROM customers c

  LEFT JOIN `source` src
    ON src.id = c.source_id
   AND src.account_id = c.account_id

  LEFT JOIN leads l
    ON l.customer_id = c.id
   AND l.datetime_deleted IS NULL

  LEFT JOIN countries co
    ON co.id = c.country_id

  LEFT JOIN users u
    ON u.id = c.created_by_user_id

  WHERE $where

  GROUP BY c.id

  $having

  ORDER BY c.date_created DESC

  LIMIT $offset, $limit
");
?>

<div class="fade-in">

  <!-- Toolbar -->
  <div class="toolbar" style="flex-wrap:wrap;gap:12px;justify-content: space-between;">
    <div class="search-wrap" style="flex:1;min-width:200px;">
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="11" cy="11" r="8"/><line x1="21" y1="21" x2="16.65" y2="16.65"/></svg>
      <input type="text" id="customerSearch" placeholder="Search in page..." value="<?= htmlspecialchars($search) ?>">
    </div>
    <div>
                <a href="index.php?page=customer_report"  class="btn btn-primary" >Customer report</a>
         <?php if ($canCustomerAdd): ?> <button type="button" class="btn btn-primary" onclick="openAddCustomerModal()">+ Add Customer</button>
<?php endif; ?>

      <button class="btn btn-secondary" onclick="toggleFilters()">🔍 Filters</button>
    </div>
  </div>

  <!-- Advanced Filters Panel -->
  <div id="filtersPanel" style="display:<?= ($filter_customer || $filter_business || $filter_phone || $filter_email || $filter_country || $filter_priority || $date_from || $date_to || $date_exact || $filter_added_by || $filter_source || $filter_leads_count !== '') ? 'block' : 'none' ?>;margin-bottom:20px;">
    <div class="card" style="padding:16px;">
      <div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;">
        <h4 style="margin:0;">Advanced Filters</h4>
        <div style="display:flex;gap:8px;align-items:center"><button class="btn btn-secondary btn-sm" onclick="clearFilters()">Clear</button><button class="btn btn-secondary btn-sm" onclick="toggleFilters()">Hide</button></div>
      </div>
      <div class="form-grid" style="grid-template-columns:repeat(auto-fit,minmax(200px,1fr));">
        <div class="form-group">
          <label class="form-label">Customer Name</label>
          <input type="text" id="filterCustomer" class="form-control" placeholder="Filter by customer..." value="<?= htmlspecialchars($filter_customer) ?>">
        </div>
        <div class="form-group">
          <label class="form-label">Business Name</label>
          <input type="text" id="filterBusiness" class="form-control" placeholder="Filter by business..." value="<?= htmlspecialchars($filter_business) ?>">
        </div>
        <div class="form-group">
          <label class="form-label">Phone</label>
          <input type="text" id="filterPhone" class="form-control" placeholder="Filter by phone..." value="<?= htmlspecialchars($filter_phone) ?>">
        </div>
        <div class="form-group">
          <label class="form-label">Email</label>
          <input type="text" id="filterEmail" class="form-control" placeholder="Filter by email..." value="<?= htmlspecialchars($filter_email) ?>">
        </div>
        
        <div class="form-group">
  <label class="form-label">Leads count</label>
  <input type="number"
         id="filterLeadsCount"
         class="form-control"
         placeholder="e.g. 5"
         min="0"
         value="<?= htmlspecialchars($_GET['filter_leads_count'] ?? '') ?>">
</div>


        <div class="form-group">
          <label class="form-label">Country</label>
          <select id="filterCountry" class="form-control">
            <option value="">All Countries</option>
            <?php foreach ($countriesList as $country): ?>
              <option value="<?= $country['id'] ?>" <?= $filter_country == $country['id'] ? 'selected' : '' ?>>
                <?= htmlspecialchars($country['name']) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label class="form-label">Priority</label>
          <select id="filterPriority" class="form-control">
            <option value="">All Priorities</option>
            <option value="1" <?= $filter_priority == 1 ? 'selected' : '' ?>>★ 1 Star</option>
            <option value="2" <?= $filter_priority == 2 ? 'selected' : '' ?>>★★ 2 Stars</option>
            <option value="3" <?= $filter_priority == 3 ? 'selected' : '' ?>>★★★ 3 Stars</option>
            <option value="4" <?= $filter_priority == 4 ? 'selected' : '' ?>>★★★★ 4 Stars</option>
            <option value="5" <?= $filter_priority == 5 ? 'selected' : '' ?>>★★★★★ 5 Stars</option>
          </select>
        </div>
        <div class="form-group">
          <label class="form-label">Source</label>
          <select id="filterSource" class="form-control">
            <option value="">All Sources</option>
            <?php if ($sourcesFilter) { $sourcesFilter->data_seek(0); while($src=$sourcesFilter->fetch_assoc()): ?>
              <option value="<?= $src['id'] ?>" <?= $filter_source == $src['id'] ? 'selected' : '' ?>><?= htmlspecialchars($src['name']) ?></option>
            <?php endwhile; } ?>
          </select>
        </div>
        
        <div class="form-group">
          <label class="form-label">Added By</label>
          <select id="filterAddedBy" class="form-control">
            <option value="">All users</option>
            <?php foreach ($usersList as $urow): ?>
              <option value="<?= $urow['id'] ?>" <?= ((int)$filter_added_by === (int)$urow['id']) ? 'selected' : '' ?>><?= htmlspecialchars($urow['name']) ?></option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label class="form-label">Date From</label>
          <input type="date" id="dateFrom" class="form-control" value="<?= htmlspecialchars($date_from) ?>">
        </div>
        <div class="form-group">
          <label class="form-label">Date To</label>
          <input type="date" id="dateTo" class="form-control" value="<?= htmlspecialchars($date_to) ?>">
        </div>
        <div class="form-group">
          <label class="form-label">Specified date</label>
          <input type="date" id="dateExact" class="form-control" value="<?= htmlspecialchars($date_exact) ?>">
        </div>
      </div>
      <div style="display:flex;gap:8px;margin-top:12px;justify-content:flex-end;">
        <button class="btn btn-primary btn-sm" onclick="applyFilters()">Apply</button>
        <button class="btn btn-secondary btn-sm" onclick="clearFilters()">Clear</button>
        <button class="btn btn-secondary btn-sm" onclick="toggleFilters()">Hide</button>
      </div>
    </div>
  </div>


  <!-- Table -->
  <div class="card">
    <div class="table-wrapper">
      <table class="crm-table" id="customersTable">
        <thead>
          <tr>
            <th><a href="#" onclick="sortTable('customer_name')">Customer ↕</a></th>
            <th><a href="#" onclick="sortTable('business_name')">Business ↕</a></th>
            <th><a href="#" onclick="sortTable('phone')">Phone ↕</a></th>
            <th><a href="#" onclick="sortTable('email')">Email ↕</a></th>
            <th>Country</th>
            <th>Source</th>
            <th><a href="#" onclick="sortTable('priority')">Priority ↕</a></th>
            <th>Leads</th>
            <th><a href="#" onclick="sortTable('date_created')">Since ↕</a></th>
            <th>Labels</th>
            <th>Contact</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($customers->num_rows === 0): ?>
            <tr><td colspan="12" class="text-center text-muted" style="padding:40px">No customers found</td></tr>
          <?php else: ?>
            <?php while ($c = $customers->fetch_assoc()): ?>
            <tr data-id="<?= crmEid($c['id']) ?>"
                data-customer-name="<?= strtolower(htmlspecialchars($c['customer_name'])) ?>"
                data-business-name="<?= strtolower(htmlspecialchars($c['business_name'] ?? '')) ?>"
                data-phone="<?= strtolower(htmlspecialchars($c['phone'] ?? '')) ?>"
                data-email="<?= strtolower(htmlspecialchars($c['email'] ?? '')) ?>"
                data-country="<?= strtolower(htmlspecialchars($c['country_name'] ?? '')) ?>"
                data-priority="<?= $c['priority'] ?>"
                data-date="<?= $c['date_created'] ?>">
              <td>
                <div class="d-flex align-center gap-8">
                  <div class="avatar avatar-sm"><?= strtoupper(substr($c['customer_name'], 0, 2)) ?></div>
                  <div class="font-bold"><?= htmlspecialchars($c['customer_name']) ?></div>
                </div>
              </td>
              <td><?= htmlspecialchars($c['business_name'] ?: '—') ?></td>
              <td><?= htmlspecialchars($c['phone'] ?: '—') ?></td>
              <td><?= htmlspecialchars($c['email'] ?: '—') ?></td>
              <td><?= htmlspecialchars($c['country_name'] ?: '—') ?></td>
              <td><?= htmlspecialchars($c['source_name'] ?: '—') ?></td>
              <td><span class="stars"><?= renderStars($c['priority']) ?></span></td>
              <td>
                <a href="index.php?page=leads&customer_id=<?= crmEid($c['id']) ?>">
                  <span class="badge badge-blue"><?= $c['leads_count'] ?></span>
                </a>
              </td>
              <td class="text-muted text-xs"><?= formatDate($c['date_created']) ?></td>
              <td>
                <button class="btn btn-secondary btn-sm" type="button" title="View labels" onclick="openCustomerLabelsModal('<?= crmEid($c['id']) ?>', '<?= addslashes($c['customer_name']) ?>')">🏷️</button>
              </td>
              <td>
                <?php if ($canCustomerMessage): ?><button class="btn btn-primary btn-sm" data-permission="message"
                  onclick="openContactModal('<?= crmEid($c['id']) ?>', '<?= addslashes($c['customer_name']) ?>', '<?= addslashes($c['phone']) ?>', '<?= addslashes($c['email']) ?>', '<?= addslashes($c['phone_code'] ?? '') ?>')">
                  <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-right:4px;vertical-align:middle"><path d="M22 2 11 13"/><path d="M22 2 15 22l-4-9-9-4 20-7z"/></svg>
                  Send
                </button><?php endif; ?>
                </td>
              <td>
                <div class="d-flex gap-8">

                  <a class="btn btn-secondary btn-sm" href="index.php?page=customer_view&id=<?= crmEid($c['id']) ?>">View</a>
                  
                  <?php
                  
                  if ($canCustomerEdit): ?><button class="btn btn-secondary btn-sm" data-permission="edit" onclick="editCustomer('<?= crmEid($c['id']) ?>')">Edit</button><?php endif; ?>
                  
                </div>
                </td>
              </tr>
            <?php endwhile; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
    
    <!-- List footer: count + pagination -->
    <div class="list-footer">
      <div class="list-count">
        Showing <strong><?= $total_rows ? number_format($offset + 1) : 0 ?> – <?= number_format(min($offset + $customers->num_rows, $total_rows)) ?></strong>
        of <strong><?= number_format($total_rows) ?></strong> customers
      </div>
      <div class="pagination">
        <?php if ($total_pages > 1): ?>
          <?php $baseParams = $_GET; $baseParams['page'] = 'customers'; unset($baseParams['page_num']); ?>
          <?php if ($page > 1): $baseParams['page_num'] = $page - 1; ?>
            <a href="?<?= http_build_query($baseParams) ?>" class="btn btn-secondary btn-sm">‹</a>
          <?php endif; ?>
          <?php for ($i = 1; $i <= $total_pages; $i++): $baseParams['page_num'] = $i; ?>
            <?php if ($i == $page): ?>
              <span class="btn btn-primary btn-sm"><?= $i ?></span>
            <?php else: ?>
              <a href="?<?= http_build_query($baseParams) ?>" class="btn btn-secondary btn-sm"><?= $i ?></a>
            <?php endif; ?>
          <?php endfor; ?>
          <?php if ($page < $total_pages): $baseParams['page_num'] = $page + 1; ?>
            <a href="?<?= http_build_query($baseParams) ?>" class="btn btn-secondary btn-sm">›</a>
          <?php endif; ?>
        <?php endif; ?>
      </div>
      <div class="footer-spacer"></div>
    </div>
  </div>
</div>

<!-- ===================== ADD / EDIT CUSTOMER MODAL ===================== -->
<div class="modal-overlay" id="addCustomerModal">
  <div class="modal modal-lg">
    <div class="modal-header">
      <span class="modal-title">Add Customer</span>
      <button class="modal-close">✕</button>
    </div>
    <div class="modal-body">
      <form id="addCustomerForm">
        <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:100px;">
                <?php foreach ($countriesList as $country): ?>
                  <option value="<?= $country['phone_code'] ?>" data-country-id="<?= $country['id'] ?>" <?= ($defaultPhoneCode == $country['phone_code']) ? 'selected' : '' ?>>
                    <?= $country['phone_code'] ?>
                  </option>
                <?php endforeach; ?>
              </select>
              <input type="text" name="phone" id="phone_number" class="form-control" placeholder="Phone number" style="flex:1">
            </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 Country</option>
              <?php foreach ($countriesList as $country): ?>
                <option value="<?= $country['id'] ?>" <?= ($defaultCountryId == $country['id']) ? 'selected' : '' ?>><?= htmlspecialchars($country['name']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
        </div>
         <div class="form-grid">
        <div class="form-group">
          <label class="form-label">Address</label>
          <textarea name="address" class="form-control" rows="2" placeholder="Street, city, etc..."></textarea>
        </div>
        <div class="form-group">
          <label class="form-label">Notes</label>
          <textarea name="notes" class="form-control" rows="3" placeholder="Additional notes about this customer..."></textarea>
        </div>
         </div>
        <div class="form-group">
          <label class="form-label">Source</label>
          <select name="source_id" class="form-control">
            <option value="">Select source</option>
            <?php if ($sourcesFilter) { $sourcesFilter->data_seek(0); while($src=$sourcesFilter->fetch_assoc()): ?>
              <option value="<?= $src['id'] ?>"><?= htmlspecialchars($src['name']) ?></option>
            <?php endwhile; } ?>
          </select>
        </div>
        <div class="form-group">
          <label class="form-label">Priority</label>
          <div class="star-rating-wrap d-flex align-center gap-8">
            <span class="star-input" data-value="1" style="font-size:22px;cursor:pointer;color:var(--text-muted)">★</span>
            <span class="star-input" data-value="2" style="font-size:22px;cursor:pointer;color:var(--text-muted)">★</span>
            <span class="star-input" data-value="3" style="font-size:22px;cursor:pointer;color:var(--text-muted)">★</span>
            <span class="star-input" data-value="4" style="font-size:22px;cursor:pointer;color:var(--text-muted)">★</span>
            <span class="star-input" data-value="5" style="font-size:22px;cursor:pointer;color:var(--text-muted)">★</span>
            <input type="hidden" name="priority" value="3">
          </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="addContactRow()">+ Add Contact</button>
        </div>
        <div id="contactsContainer"></div>
      </form>
    </div>
    <div class="modal-footer">
      <button class="btn btn-secondary" onclick="closeModal('addCustomerModal')">Cancel</button>
      <button class="btn btn-primary" onclick="submitAddCustomer()">Save Customer</button>
    </div>
  </div>
</div>

<!-- ===================== VIEW CUSTOMER MODAL ===================== -->
<div class="modal-overlay" id="viewCustomerModal">
  <div class="modal modal-lg">
    <div class="modal-header">
      <span class="modal-title" id="viewCustomerTitle">Customer</span>
      <button class="modal-close">✕</button>
    </div>
    <div class="modal-body" id="viewCustomerBody">
      <div class="text-center"><div class="spinner"></div></div>
    </div>
  </div>
</div>

<!-- ===================== CUSTOMER LABELS MODAL ===================== -->
<div class="modal-overlay" id="customerLabelsModal">
  <div class="modal">
    <div class="modal-header">
      <span class="modal-title" id="customerLabelsTitle">Customer Labels</span>
      <button class="modal-close" onclick="closeModal('customerLabelsModal')">✕</button>
    </div>
    <div class="modal-body">
      <input type="hidden" id="labels_customer_id">
      <div id="customerLabelsList" style="display:grid;gap:10px;"></div>
      <div class="hr"></div>
      <div class="form-grid" style="grid-template-columns:1fr 110px auto;align-items:end;">
        <div class="form-group mb-0">
          <label class="form-label">New Label</label>
          <input type="text" id="newCustomerLabelName" class="form-control" placeholder="Website, App, Pending...">
        </div>
        <div class="form-group mb-0">
          <label class="form-label">Color</label>
          <input type="color" id="newCustomerLabelColor" class="form-control" value="#1a3a6f" style="height:42px;">
        </div>
        <button type="button" class="btn btn-secondary" onclick="addCustomerLabelFromModal()">+ Add</button>
      </div>
    </div>
    <div class="modal-footer">
      <button class="btn btn-secondary" onclick="closeModal('customerLabelsModal')">Cancel</button>
      <button class="btn btn-primary" onclick="saveCustomerLabelsModal()">Save Labels</button>
    </div>
  </div>
</div>

<!-- ===================== CONTACT MODAL (Tabbed) ===================== -->
<div class="modal-overlay" id="contactModal">
  <div class="modal">
    <div class="modal-header">
      <span class="modal-title" id="contactModalTitle">Contact Customer</span>
      <button class="modal-close" onclick="closeModal('contactModal')">✕</button>
    </div>
    <div class="modal-body" style="padding-top:0">

      <!-- Tabs -->
      <div style="display:flex;border-bottom:2px solid var(--border);margin-bottom:20px;margin-left:-24px;margin-right:-24px;padding:0 24px">
        <button class="contact-tab" data-tab="whatsapp" onclick="switchContactTab('whatsapp')"
          style="flex:1;padding:12px 8px;border:none;background:transparent;cursor:pointer;font-size:13px;font-weight:600;color:var(--text-muted);border-bottom:2px solid transparent;margin-bottom:-2px;transition:all .2s">
          💬 WhatsApp
        </button>
        <button class="contact-tab" data-tab="sms" onclick="switchContactTab('sms')"
          style="flex:1;padding:12px 8px;border:none;background:transparent;cursor:pointer;font-size:13px;font-weight:600;color:var(--text-muted);border-bottom:2px solid transparent;margin-bottom:-2px;transition:all .2s">
          📱 SMS
        </button>
        <button class="contact-tab" data-tab="email" onclick="switchContactTab('email')"
          style="flex:1;padding:12px 8px;border:none;background:transparent;cursor:pointer;font-size:13px;font-weight:600;color:var(--text-muted);border-bottom:2px solid transparent;margin-bottom:-2px;transition:all .2s">
          ✉️ Email
        </button>
      </div>

      <form id="contactForm">
        <input type="hidden" name="customer_id" id="ct_customer_id">
        <input type="hidden" name="type"        id="ct_type" value="whatsapp">

        <div class="form-group">
          <label class="form-label">To:</label>
          <div id="ct_recipient" style="padding:8px 12px;background:var(--bg-base);border:1px solid var(--border);border-radius:8px;font-weight:600;color:var(--text-primary)"></div>
        </div>

        <div class="form-group" id="ct_subject_group" style="display:none">
          <label class="form-label">Subject</label>
          <input type="text" name="subject" id="ct_subject" class="form-control" placeholder="Email subject">
        </div>

        <div class="form-group">
          <label class="form-label">Message</label>
          <div id="emailEditor" style="display:none;">
            <div id="emailToolbar" style="border:1px solid var(--border);border-radius:8px 8px 0 0;padding:8px;background:var(--bg-base);display:flex;gap:8px;flex-wrap:wrap;">
              <button type="button" onclick="formatText('bold')" style="padding:4px 8px;border:1px solid var(--border);border-radius:4px;background:white;cursor:pointer;"><b>B</b></button>
              <button type="button" onclick="formatText('italic')" style="padding:4px 8px;border:1px solid var(--border);border-radius:4px;background:white;cursor:pointer;"><i>I</i></button>
              <button type="button" onclick="formatText('underline')" style="padding:4px 8px;border:1px solid var(--border);border-radius:4px;background:white;cursor:pointer;"><u>U</u></button>
              <select onchange="formatText('fontSize', this.value)" style="padding:4px 8px;border:1px solid var(--border);border-radius:4px;">
                <option value="12px">Small</option>
                <option value="14px" selected>Normal</option>
                <option value="18px">Large</option>
                <option value="24px">Huge</option>
              </select>
              <select onchange="formatText('color', this.value)" style="padding:4px 8px;border:1px solid var(--border);border-radius:4px;">
                <option value="#000000">Black</option>
                <option value="#ff0000">Red</option>
                <option value="#00ff00">Green</option>
                <option value="#0000ff">Blue</option>
              </select>
            </div>
            <div id="emailMessage" contenteditable="true" style="border:1px solid var(--border);border-top:none;border-radius:0 0 8px 8px;padding:12px;min-height:150px;background:white;color:#333;" placeholder="Type your email message..."></div>
          </div>
          <textarea name="message" id="ct_message" class="form-control" rows="5" placeholder="Type your message..." style="display:block;"></textarea>
        </div>

        <div class="form-group" id="ct_whatsapp_media_group" style="display:none;">
          <label class="form-label">Image optional</label>
          <input type="file" name="media" id="ct_media" class="form-control" accept="image/*">
          <div class="text-xs text-muted" style="margin-top:6px;">Choose an image to send with WhatsApp or Email message.</div>
          <div id="ct_media_preview" style="display:none;margin-top:10px;">
            <img id="ct_media_preview_img" src="" alt="Preview" style="max-width:180px;max-height:140px;border-radius:10px;border:1px solid var(--border);object-fit:cover;">
            <button type="button" class="btn btn-secondary btn-sm" style="margin-left:8px;vertical-align:top;" onclick="clearContactMedia()">Remove</button>
          </div>
        </div>
      </form>
    </div>
    <div class="modal-footer">
      <button class="btn btn-secondary" onclick="closeModal('contactModal')">Cancel</button>
      <button class="btn btn-primary" onclick="sendContactMessage()" id="ct_send_btn">Send</button>
    </div>
  </div>
</div>

<style>
  th a { text-decoration: none; color: var(--text-muted); }
  .pagination a, .pagination span { text-decoration: none; }
  [contenteditable="true"]:empty:before {
    content: attr(placeholder);
    color: #aaa;
  }
</style>

<script>
const CAN_CUSTOMER_ADD = <?= $canCustomerAdd ? 'true' : 'false' ?>;
const CAN_CUSTOMER_EDIT = <?= $canCustomerEdit ? 'true' : 'false' ?>;
const CAN_CUSTOMER_DELETE = <?= $canCustomerDelete ? 'true' : 'false' ?>;
const CAN_CUSTOMER_MESSAGE = <?= $canCustomerMessage ? 'true' : 'false' ?>;
// =============================================
// Filters & Sorting
// =============================================
let currentSort = { column: 'customer_name', direction: 'asc' };

function toggleFilters() {
  const panel = document.getElementById('filtersPanel');
  panel.style.display = panel.style.display === 'none' ? 'block' : 'none';
}

function applyFilters() {
  const params = new URLSearchParams();
  params.set('page', 'customers');
  const fc = document.getElementById('filterCustomer').value;
  const fb = document.getElementById('filterBusiness').value;
  const fp = document.getElementById('filterPhone').value;
  const fe = document.getElementById('filterEmail').value;
  const fco = document.getElementById('filterCountry').value;
  const fprio = document.getElementById('filterPriority').value;
  const fsource = document.getElementById('filterSource') ? document.getElementById('filterSource').value : '';
  const dfrom = document.getElementById('dateFrom').value;
  const dto = document.getElementById('dateTo').value;
  const dexact = document.getElementById('dateExact') ? document.getElementById('dateExact').value : '';
  const fab = document.getElementById('filterAddedBy') ? document.getElementById('filterAddedBy').value : '';
  const flc = document.getElementById('filterLeadsCount').value;

  if (flc) params.set('filter_leads_count', flc);
  if (fc) params.set('filter_customer', fc);
  if (fb) params.set('filter_business', fb);
  if (fp) params.set('filter_phone', fp);
  if (fe) params.set('filter_email', fe);
  if (fco) params.set('filter_country', fco);
  if (fprio) params.set('filter_priority', fprio);
  if (fsource) params.set('filter_source', fsource);
  if (dfrom) params.set('date_from', dfrom);
  if (dto) params.set('date_to', dto);
  if (dexact) params.set('date_exact', dexact);
  if (fab) params.set('filter_added_by', fab);
  window.location.href = '?' + params.toString();
}

function clearFilters() {
  window.location.href = '?page=customers';
}

function sortTable(column) {
  const tbody = document.querySelector('#customersTable tbody');
  const rows  = Array.from(tbody.querySelectorAll('tr'));

  if (currentSort.column === column) {
    currentSort.direction = currentSort.direction === 'asc' ? 'desc' : 'asc';
  } else {
    currentSort.column    = column;
    currentSort.direction = 'asc';
  }

  rows.sort((a, b) => {
    let aVal = '', bVal = '';
    switch (column) {
      case 'customer_name': aVal = a.querySelector('td:first-child .font-bold')?.textContent.trim() || ''; bVal = b.querySelector('td:first-child .font-bold')?.textContent.trim() || ''; break;
      case 'business_name': aVal = a.querySelector('td:nth-child(2)')?.textContent.trim() || ''; bVal = b.querySelector('td:nth-child(2)')?.textContent.trim() || ''; break;
      case 'phone':         aVal = a.querySelector('td:nth-child(3)')?.textContent.trim() || ''; bVal = b.querySelector('td:nth-child(3)')?.textContent.trim() || ''; break;
      case 'email':         aVal = a.querySelector('td:nth-child(4)')?.textContent.trim() || ''; bVal = b.querySelector('td:nth-child(4)')?.textContent.trim() || ''; break;
      case 'priority':      aVal = parseInt(a.dataset.priority) || 0; bVal = parseInt(b.dataset.priority) || 0; break;
      case 'date_created':  aVal = a.dataset.date || ''; bVal = b.dataset.date || ''; break;
    }
    if (aVal === '—') aVal = '';
    if (bVal === '—') bVal = '';
    return currentSort.direction === 'asc' ? (aVal > bVal ? 1 : -1) : (aVal < bVal ? 1 : -1);
  });

  rows.forEach(row => tbody.appendChild(row));
}

function applyQuickSearch(){
  const params = new URLSearchParams(window.location.search);
  params.set('page','customers');
  const q = document.getElementById('customerSearch').value.trim();
  if(q) params.set('search', q); else params.delete('search');
  params.delete('page_num');
  window.location.href='?' + params.toString();
}
document.querySelectorAll('#filtersPanel input,#filtersPanel select,#customerSearch').forEach(el=>{ el.addEventListener('keydown', e=>{ if(e.key==='Enter'){ e.preventDefault(); el.id==='customerSearch' ? applyQuickSearch() : applyFilters(); }}); });
document.getElementById('customerSearch').addEventListener('input', function () {
  const q = this.value.toLowerCase();
  document.querySelectorAll('#customersTable tbody tr').forEach(row => {
    const match = !q
      || (row.dataset.customerName || '').includes(q)
      || (row.dataset.businessName || '').includes(q)
      || (row.dataset.phone        || '').includes(q)
      || (row.dataset.email        || '').includes(q)
      || (row.dataset.country      || '').includes(q);
    row.style.display = match ? '' : 'none';
  });
});

let CUSTOMER_LABELS_CACHE = [];
let CUSTOMER_LABELS_ASSIGNED = [];

async function openCustomerLabelsModal(customerId, customerName) {
  document.getElementById('labels_customer_id').value = customerId;
  document.getElementById('customerLabelsTitle').textContent = 'Labels: ' + customerName;
  document.getElementById('customerLabelsList').innerHTML = '<div class="text-center text-muted" style="padding:20px">Loading...</div>';
  openModal('customerLabelsModal');
  const res = await apiCall('handlers/labels.php', {action:'customer_labels', customer_id:customerId});
  if (!res.success) { showToast(res.message || 'Error loading labels', 'error'); return; }
  CUSTOMER_LABELS_CACHE = res.labels || [];
  CUSTOMER_LABELS_ASSIGNED = (res.assigned || []).map(Number);
  renderCustomerLabelsModal();
}

function renderCustomerLabelsModal() {
  const wrap = document.getElementById('customerLabelsList');
  if (!CUSTOMER_LABELS_CACHE.length) {
    wrap.innerHTML = '<div class="text-muted text-sm">No labels yet. Add your first label below.</div>';
    return;
  }
  wrap.innerHTML = CUSTOMER_LABELS_CACHE.map(l => {
    const checked = CUSTOMER_LABELS_ASSIGNED.includes(Number(l.id)) ? 'checked' : '';
    return `<label style="display:flex;align-items:center;gap:10px;padding:10px;border:1px solid var(--border);border-radius:10px;background:var(--bg-base);cursor:pointer;">
      <input type="checkbox" class="customer-label-check" value="${l.id}" ${checked}>
      <span style="width:12px;height:12px;border-radius:999px;background:${escapeHtml(l.color || '#1a3a6f')};display:inline-block"></span>
      <span class="font-bold">${escapeHtml(l.name)}</span>
    </label>`;
  }).join('');
}

async function addCustomerLabelFromModal() {
  const name = document.getElementById('newCustomerLabelName').value.trim();
  const color = document.getElementById('newCustomerLabelColor').value || '#1a3a6f';
  const customerId = document.getElementById('labels_customer_id').value;
  if (!name) { showToast('Enter label name', 'error'); return; }
  const res = await apiCall('handlers/labels.php', {action:'add_label', name, color});
  if (!res.success) { showToast(res.message || 'Error', 'error'); return; }
  document.getElementById('newCustomerLabelName').value = '';
  const reload = await apiCall('handlers/labels.php', {action:'customer_labels', customer_id:customerId});
  CUSTOMER_LABELS_CACHE = reload.labels || [];
  CUSTOMER_LABELS_ASSIGNED = (reload.assigned || []).map(Number);
  renderCustomerLabelsModal();
}

async function saveCustomerLabelsModal() {
  const customerId = document.getElementById('labels_customer_id').value;
  const labelIds = Array.from(document.querySelectorAll('.customer-label-check:checked')).map(x => x.value);
  const res = await apiCall('handlers/labels.php', {action:'save_customer_labels', customer_id:customerId, label_ids:labelIds});
  if (res.success) { showToast('Labels saved', 'success'); closeModal('customerLabelsModal'); }
  else showToast(res.message || 'Error', 'error');
}

// =============================================
// Phone Validation
// =============================================
function validatePhone(phone, countryId) {
  // Remove any non-digit characters
  phone = phone.replace(/\D/g, '');
  
  // Get country phone code
  const phoneCodeSelect = document.getElementById('phone_code');
  const selectedCode = phoneCodeSelect.value;
  
  // Lebanese numbers should be 8 digits after 961
//   if (selectedCode === '+961') {
//     if (phone.length === 8 && /^[71][0-9]{7}$/.test(phone)) {
//       return true;
//     } else {
//       showToast('Lebanese number must be 8 digits starting with 71 or 76 or 78 or 81', 'error');
//       return false;
//     }
//   }
  
  // For other countries, basic validation (min 5 digits, max 15)
  if (phone.length >= 5 && phone.length <= 15) {
    return true;
  } else {
    showToast('Phone number must be between 5-15 digits', 'error');
    return false;
  }
}

// =============================================
// Star Rating
// =============================================
document.querySelectorAll('.star-input').forEach(star => {
  star.addEventListener('click', function() {
    const value = parseInt(this.dataset.value);
    const container = this.parentElement;
    const hiddenInput = container.querySelector('input[name="priority"]');
    const allStars = container.querySelectorAll('.star-input');
    
    hiddenInput.value = value;
    allStars.forEach((s, idx) => {
      s.style.color = idx < value ? 'var(--yellow)' : 'var(--text-muted)';
    });
  });
});

// =============================================
// Add Contact Row (inside Add/Edit modal)
// =============================================
let contactCount = 0;

function addContactRow() {
  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" placeholder="Contact name"></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" placeholder="CEO, Manager..."></div>
      <div class="form-group mb-0"><label class="form-label">Phone</label>     <input type="text"  name="contacts[${i}][phone]"     class="form-control" placeholder="Phone"></div>
      <div class="form-group mb-0"><label class="form-label">Email</label>     <input type="email" name="contacts[${i}][email]"     class="form-control" placeholder="Email"></div>
    </div>
    <button type="button" onclick="document.getElementById('contact_row_${i}').remove()" class="btn btn-danger btn-sm" style="margin-top:8px">Remove</button>`;
  document.getElementById('contactsContainer').appendChild(div);
}

// =============================================
// Add / Edit Customer
// =============================================
async function submitAddCustomer() {
  const form   = document.getElementById('addCustomerForm');
  const fd     = new FormData(form);
  const editId = document.getElementById('edit_customer_id')?.value;
  
  // Validate phone
  const phoneNumber = document.getElementById('phone_number').value;
  const countryId = document.getElementById('customer_country_id').value;
  
  if (phoneNumber) {
    let countryCode = document.getElementById('phone_code').value || '<?= addslashes($defaultPhoneCode ?: '+961') ?>'; // default
    for (const country of <?= json_encode($countriesList) ?>) {
      if (country.id == countryId) {
        countryCode = country.phone_code;
        break;
      }
    }
    
    if (!validatePhone(phoneNumber, countryId)) {
      return;
    }
    
    fd.set('phone', countryCode + phoneNumber.replace(/\D/g, ''));
  }
  
  fd.append('action', editId ? 'edit' : 'add');
  if (editId) fd.append('edit_id', editId);

  const res = await apiCall('handlers/customers.php', fd);
  if (res.success) {
    showToast(editId ? 'Customer updated!' : 'Customer added!', 'success');
    closeModal('addCustomerModal');
    setTimeout(() => location.reload(), 600);
  } else {
    showToast(res.message || 'Error', 'error');
  }
}

// =============================================
// View Customer
// =============================================
async function viewCustomer(id) {
  openModal('viewCustomerModal');
  document.getElementById('viewCustomerBody').innerHTML = '<div class="text-center" style="padding:40px"><div class="spinner"></div></div>';

  const res = await apiCall('handlers/customers.php', { action: 'get', id });
  if (!res.success) return;

  const c = res.data;
  let contactsHtml = '';
  let notesHtml = c.notes ? `<div><label class="form-label">Notes</label><p>${escapeHtml(c.notes)}</p></div>` : '';

  if (res.contacts && res.contacts.length) {
    contactsHtml = res.contacts.map(ct => `
      <div style="padding:10px;background:var(--bg-base);border-radius:8px;border:1px solid var(--border);margin-bottom:6px">
        <strong>${escapeHtml(ct.name)}</strong> <span class="text-muted">${escapeHtml(ct.job_title || '')}</span><br>
        <span class="text-xs">${escapeHtml(ct.phone || '')} ${ct.email ? '· ' + escapeHtml(ct.email) : ''}</span>
      </div>`).join('');
  } else {
    contactsHtml = '<p class="text-muted text-sm">No contacts added</p>';
  }

  document.getElementById('viewCustomerTitle').textContent = c.customer_name;
  document.getElementById('viewCustomerBody').innerHTML = `
    <div class="form-grid mb-16">
      <div><label class="form-label">Customer Name</label><p>${escapeHtml(c.customer_name)}</p></div>
      <div><label class="form-label">Business</label>      <p>${escapeHtml(c.business_name || '—')}</p></div>
      <div><label class="form-label">Phone</label>         <p>${escapeHtml(c.phone || '—')}</p></div>
      <div><label class="form-label">Email</label>         <p>${escapeHtml(c.email || '—')}</p></div>
      <div><label class="form-label">Country</label>       <p>${escapeHtml(c.country_name || '—')}</p></div>
      <div><label class="form-label">Address</label>       <p>${escapeHtml(c.address || '—')}</p></div>
      <div><label class="form-label">Priority</label>      <p>${renderPriority(c.priority)}</p></div>
      <div><label class="form-label">Since</label>         <p>${formatDate(c.date_created)}</p></div>
      ${notesHtml}
    </div>
    <div class="hr"></div>
    <label class="form-label">Contacts</label>
    ${contactsHtml}
    <div class="hr"></div>
    <div class="d-flex gap-8">
      <button class="btn btn-primary btn-sm" onclick="closeModal('viewCustomerModal');editCustomer(${id})">Edit Customer</button>
      <a href="index.php?page=leads&customer_id=${id}" class="btn btn-secondary btn-sm">View Leads</a>
    </div>`;
}

// =============================================
// Edit Customer
// =============================================
async function editCustomer(id) {
  if (!CAN_CUSTOMER_EDIT) { showToast('Permission denied', 'error'); return; }
  const res = await apiCall('handlers/customers.php', { action: 'get', id });
  if (!res.success) { showToast('Error loading customer', 'error'); return; }

  const c = res.data;
  document.querySelector('#addCustomerForm [name=customer_name]').value = c.customer_name;
  document.querySelector('#addCustomerForm [name=business_name]').value = c.business_name || '';
  document.querySelector('#addCustomerForm [name=email]').value         = c.email || '';
  document.querySelector('#addCustomerForm [name=priority]').value      = c.priority || 3;
  document.querySelector('#addCustomerForm [name=country_id]').value    = c.country_id || '';
  const sourceEl = document.querySelector('#addCustomerForm [name=source_id]'); if (sourceEl) sourceEl.value = c.source_id || '';
  document.querySelector('#addCustomerForm [name=address]').value       = c.address || '';
  document.querySelector('#addCustomerForm [name=notes]').value         = c.notes || '';
  
  // Handle phone with country code
  let phone = c.phone || '';
  let phoneCode = '<?= addslashes($defaultPhoneCode ?: '+961') ?>'; // default
  let phoneNumber = phone;
  
  // Try to extract phone code
  for (const country of <?= json_encode($countriesList) ?>) {
    if (phone.startsWith(country.phone_code)) {
      phoneCode = country.phone_code;
      phoneNumber = phone.substring(country.phone_code.length);
      break;
    }
  }
  
  document.getElementById('phone_code').value = phoneCode;
  document.querySelector('#addCustomerForm [name=phone]').value = phoneNumber;

  // Set stars
  const priority = c.priority || 3;
  const starContainer = document.querySelector('#addCustomerForm .star-rating-wrap');
  const allStars = starContainer.querySelectorAll('.star-input');
  const hiddenInput = starContainer.querySelector('input[name="priority"]');
  hiddenInput.value = priority;
  allStars.forEach((s, idx) => {
    s.style.color = idx < priority ? 'var(--yellow)' : 'var(--text-muted)';
  });

  let editInput = document.getElementById('edit_customer_id');
  if (!editInput) {
    editInput      = document.createElement('input');
    editInput.type = 'hidden';
    editInput.id   = 'edit_customer_id';
    editInput.name = 'edit_id';
    document.getElementById('addCustomerForm').appendChild(editInput);
  }
  editInput.value = id;

  document.getElementById('contactsContainer').innerHTML = '';
  contactCount = 0;

  if (res.contacts && res.contacts.length) {
    res.contacts.forEach(contact => {
      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" value="${escapeHtml(contact.name      || '')}"></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" value="${escapeHtml(contact.job_title || '')}"></div>
          <div class="form-group mb-0"><label class="form-label">Phone</label>     <input type="text"  name="contacts[${i}][phone]"     class="form-control" value="${escapeHtml(contact.phone     || '')}"></div>
          <div class="form-group mb-0"><label class="form-label">Email</label>     <input type="email" name="contacts[${i}][email]"     class="form-control" value="${escapeHtml(contact.email     || '')}"></div>
        </div>
        <button type="button" onclick="document.getElementById('contact_row_${i}').remove()" class="btn btn-danger btn-sm" style="margin-top:8px">Remove</button>`;
      document.getElementById('contactsContainer').appendChild(div);
    });
  }

  document.querySelector('#addCustomerModal .modal-title').textContent = 'Edit Customer';
  openModal('addCustomerModal');
}

// =============================================
// Delete Customer
// =============================================
async function deleteCustomer(id, name) {
  if (!CAN_CUSTOMER_DELETE) { showToast('Permission denied', 'error'); return; }
  confirmAction(`Delete customer "${name}"? This cannot be undone.`, async () => {
    const res = await apiCall('handlers/customers.php', { action: 'delete', id });
    if (res.success) {
      showToast('Customer deleted', 'success');
      setTimeout(() => location.reload(), 600);
    } else {
      showToast(res.message || 'Error', 'error');
    }
  });
}


let _ctPhone = '', _ctEmail = '', _ctPhoneCode = '';

function openContactModal(id, name, phone, email, phoneCode) {
  if (!CAN_CUSTOMER_MESSAGE) { showToast('Permission denied', 'error'); return; }
  _ctPhone = phone;
  _ctEmail = email;
  _ctPhoneCode = phoneCode || '';
  document.getElementById('ct_customer_id').value = id;
  document.getElementById('contactModalTitle').textContent = 'Contact: ' + name;
  document.getElementById('ct_subject').value = '';
  document.getElementById('ct_message').value = '';
  clearContactMedia();
  if (document.getElementById('emailMessage')) {
    document.getElementById('emailMessage').innerHTML = '';
  }
  switchContactTab('whatsapp');
  openModal('contactModal');
}

function switchContactTab(tab) {
  document.getElementById('ct_type').value = tab;

  document.querySelectorAll('.contact-tab').forEach(btn => {
    const active = btn.dataset.tab === tab;
    btn.style.color             = active ? 'var(--primary)' : 'var(--text-muted)';
    btn.style.borderBottomColor = active ? 'var(--primary)' : 'transparent';
  });

  const recipientEl = document.getElementById('ct_recipient');
  const subjectGrp  = document.getElementById('ct_subject_group');
  const emailEditor = document.getElementById('emailEditor');
  const textMessage = document.getElementById('ct_message');
  const whatsappMediaGroup = document.getElementById('ct_whatsapp_media_group');

  if (whatsappMediaGroup) whatsappMediaGroup.style.display = (tab === 'whatsapp' || tab === 'email') ? 'block' : 'none';

  switch (tab) {
    case 'whatsapp':
      recipientEl.textContent  = _ctPhone ? _ctPhone : '⚠️ No phone number';
      subjectGrp.style.display = 'none';
      emailEditor.style.display = 'none';
      textMessage.style.display = 'block';
      textMessage.placeholder = 'Type your WhatsApp message...';
      break;
    case 'sms':
      recipientEl.textContent  = _ctPhone ? _ctPhone : '⚠️ No phone number';
      subjectGrp.style.display = 'none';
      emailEditor.style.display = 'none';
      textMessage.style.display = 'block';
      textMessage.placeholder = 'Type your SMS message...';
      break;
    case 'email':
      recipientEl.textContent  = _ctEmail ? _ctEmail : '⚠️ No email address';
      subjectGrp.style.display = 'block';
      emailEditor.style.display = 'block';
      textMessage.style.display = 'none';
      break;
  }
}

function formatText(command, value) {
  if (command === 'color' || command === 'fontSize') {
    document.execCommand('fontSize', false, '7');
    // For color and font size
    document.execCommand(command, false, value);
  } else {
    document.execCommand(command, false, null);
  }
  document.getElementById('emailMessage').focus();
}

function clearContactMedia() {
  const mediaInput = document.getElementById('ct_media');
  const preview = document.getElementById('ct_media_preview');
  const img = document.getElementById('ct_media_preview_img');

  if (mediaInput) mediaInput.value = '';
  if (img) img.src = '';
  if (preview) preview.style.display = 'none';
}

document.addEventListener('change', function(e) {
  if (e.target && e.target.id === 'ct_media') {
    const file = e.target.files && e.target.files[0] ? e.target.files[0] : null;
    const preview = document.getElementById('ct_media_preview');
    const img = document.getElementById('ct_media_preview_img');

    if (!file) { clearContactMedia(); return; }
    if (!file.type.match(/^image\//)) {
      showToast('Please choose an image file', 'error');
      clearContactMedia();
      return;
    }

    img.src = URL.createObjectURL(file);
    preview.style.display = 'block';
  }
});

async function sendContactMessage() {
  const type       = document.getElementById('ct_type').value;
  const customerId = document.getElementById('ct_customer_id').value;
  const subject    = document.getElementById('ct_subject').value.trim();
  let message = document.getElementById('ct_message').value.trim();
  
  if (type === 'email') {
    message = document.getElementById('emailMessage').innerHTML;
  }

  if (!message) { showToast('Please enter a message', 'error'); return; }
  if (type === 'email' && !subject) { showToast('Please enter a subject', 'error'); return; }

  const btn  = document.getElementById('ct_send_btn');
  const orig = btn.textContent;
  btn.textContent = 'Sending...';
  btn.disabled    = true;

  try {
    let res;

    if (type === 'sms') {
      res = await sendSmsFromBrowser(_ctPhone, message);
      if (res.success) {
        apiCall('handlers/communications.php', {
          action: 'log', type: 'sms',
          customer_id: customerId,
          subject: '', message,
          status: 'sent', response: 'Sent via browser'
        });
      }
    } else {
      const mediaInput = document.getElementById('ct_media');

      if ((type === 'whatsapp' || type === 'email') && mediaInput && mediaInput.files && mediaInput.files[0]) {
        const fd = new FormData();
        fd.append('action', 'send');
        fd.append('target_type', 'direct');
        fd.append('type', type);
        fd.append('customer_id', customerId);
        fd.append('subject', subject);
        fd.append('message', message);
        fd.append('media', mediaInput.files[0]);
        res = await apiCall('handlers/communications.php', fd);
      } else {
        res = await apiCall('handlers/communications.php', {
          action: 'send', target_type: 'direct', type, customer_id: customerId, subject, message
        });
      }
    }

    if (res.success) {
      showToast('Message sent successfully!', 'success');
      closeModal('contactModal');
    } else {
      showToast(res.message || 'Error sending message', 'error');
    }
  } catch (err) {
    showToast('Error: ' + err.message, 'error');
  } finally {
    btn.textContent = orig;
    btn.disabled    = false;
  }
}

async function sendSmsFromBrowser(phone, message) {
  phone = phone.replace(/[^0-9]/g, '');
  const url = 'https://sms.unosms.net/api.php'
    + '?user=' + encodeURIComponent('abed_mahfouz@hotmail.com')
    + '&pass=uwscqq'
    + '&to='   + phone
    + '&from=Amctag'
    + '&msg='  + encodeURIComponent(message);

  try {
    await fetch(url, { method: 'GET', mode: 'no-cors', cache: 'no-cache' });
    return { success: true, message: 'SMS sent successfully' };
  } catch (err) {
    return { success: false, message: 'SMS network error: ' + err.message };
  }
}

function escapeHtml(text) {
  if (!text) return '';
  const div = document.createElement('div');
  div.textContent = text;
  return div.innerHTML;
}

function renderPriority(priority) {
  let stars = '';
  for (let i = 1; i <= 5; i++) {
    stars += `<span style="color: ${i <= priority ? 'var(--yellow)' : 'var(--text-muted)'}">★</span>`;
  }
  return stars;
}


function openAddCustomerModal() {
  if (!CAN_CUSTOMER_ADD) { showToast('Permission denied', 'error'); return; }
  const form = document.getElementById('addCustomerForm');

  // reset form fields
  form.reset();

  // reset edit mode
  const editInput = document.getElementById('edit_customer_id');
  if (editInput) editInput.remove();

  // reset contacts
  document.getElementById('contactsContainer').innerHTML = '';
  contactCount = 0;

  // reset title
  document.querySelector('#addCustomerModal .modal-title').textContent = 'Add Customer';

  // reset stars
  const starContainer = document.querySelector('#addCustomerForm .star-rating-wrap');
  const stars = starContainer.querySelectorAll('.star-input');
  starContainer.querySelector('input[name="priority"]').value = 3;

  stars.forEach(s => s.style.color = 'var(--text-muted)');

  stars.forEach((s, idx) => {
    if (idx < 3) s.style.color = 'var(--yellow)';
  });

  openModal('addCustomerModal');
}


</script>

<script>
</script>
