<?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 = 10;
$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'] : '';
$date_from       = isset($_GET['date_from'])       ? sanitize($conn, $_GET['date_from']) : '';
$date_to         = isset($_GET['date_to'])         ? sanitize($conn, $_GET['date_to']) : '';

$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 ($date_from)       $where .= " AND DATE(c.date_created) >= '$date_from'";
if ($date_to)         $where .= " AND DATE(c.date_created) <= '$date_to'";

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 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()) {
    $countriesList[] = $row;
}

$having = '';

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

$customers = $conn->query("
  SELECT
    c.*,
    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 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="Quick search..." value="<?= htmlspecialchars($search) ?>">
    </div>
    <div>



     <?php if ($canCustomerAdd): ?>
  <button class="btn btn-primary" onclick="openAddCustomerModal()">+ Add Customer</button>
<?php endif; ?>

      <button class="btn btn-secondary" onclick="toggleFilters()">🔍 Show 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) ? '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>
        <button class="btn btn-secondary btn-sm" onclick="clearFilters()">Clear All Filters</button>
      </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">Min 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">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>
      <div style="display:flex;gap:8px;margin-top:12px;">
        <button class="btn btn-primary btn-sm" onclick="applyFilters()">Apply Filters</button>
        <button class="btn btn-secondary btn-sm" onclick="toggleFilters()">Hide Filters</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><a href="#" onclick="sortTable('priority')">Priority ↕</a></th>
            <th>Leads</th>
            <th><a href="#" onclick="sortTable('date_created')">Since ↕</a></th>
            <th>Added By</th>
            <th>Contact</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
          <?php if ($customers->num_rows === 0): ?>
            <tr><td colspan="11" class="text-center text-muted" style="padding:40px">No customers found</td></tr>
          <?php else: ?>
            <?php while ($c = $customers->fetch_assoc()): ?>
            <tr data-id="<?= $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><span class="stars"><?= renderStars($c['priority']) ?></span></td>
              <td>
                <a href="index.php?page=leads&customer_id=<?= $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><?= htmlspecialchars($c['created_by_name'] ?: '—') ?></td>
              <td>
                <?php if ($canCustomerMessage): ?><button class="btn btn-primary btn-sm" data-permission="message"
                  onclick="openContactModal(<?= $c['id'] ?>, '<?= addslashes($c['customer_name']) ?>', '<?= addslashes($c['phone']) ?>', '<?= addslashes($c['email']) ?>', '<?= addslashes($c['phone_code'] ?? '') ?>')">
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" style="margin-right:4px;vertical-align:middle">
                    <path d="M21 15a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H3a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h4m8 0h4M12 3v12m-4-4 4 4 4-4"/>
                  </svg>
                  Contact
                </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=<?= $c['id'] ?>">View</a>
                  
                  <?php
                  
                  if ($canCustomerEdit): ?><button class="btn btn-secondary btn-sm" data-permission="edit" onclick="editCustomer(<?= $c['id'] ?>)">Edit</button><?php endif; ?>
                  <?php if ($canCustomerDelete): ?><button class="btn btn-danger btn-sm" data-permission="delete"    onclick="deleteCustomer(<?= $c['id'] ?>, '<?= addslashes($c['customer_name']) ?>')">Del</button><?php endif; ?>
                </div>
                </td>
              </tr>
            <?php endwhile; ?>
          <?php endif; ?>
        </tbody>
      </table>
    </div>
    
    <!-- Pagination -->
    <?php if ($total_pages > 1): ?>
    <div class="pagination" style="display:flex;justify-content:center;gap:8px;padding:20px;border-top:1px solid var(--border);">
      <?php if ($page > 1): ?>
        <a href="?page=customers&page_num=<?= $page-1 ?><?= isset($_GET['filter_customer']) ? '&' . http_build_query(array_filter($_GET)) : '' ?>" class="btn btn-secondary btn-sm">← Previous</a>
      <?php endif; ?>
      
      <?php for ($i = 1; $i <= $total_pages; $i++): ?>
        <?php if ($i == $page): ?>
          <span class="btn btn-primary btn-sm" style="background:#1a3a6f;color:white;"><?= $i ?></span>
        <?php else: ?>
          <a href="?page=customers&page_num=<?= $i ?><?= isset($_GET['filter_customer']) ? '&' . http_build_query(array_filter($_GET)) : '' ?>" class="btn btn-secondary btn-sm"><?= $i ?></a>
        <?php endif; ?>
      <?php endfor; ?>
      
      <?php if ($page < $total_pages): ?>
        <a href="?page=customers&page_num=<?= $page+1 ?><?= isset($_GET['filter_customer']) ? '&' . http_build_query(array_filter($_GET)) : '' ?>" class="btn btn-secondary btn-sm">Next →</a>
      <?php endif; ?>
    </div>
    <?php endif; ?>
  </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'] ?>">
                    <?= $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'] ?>"><?= 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">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>

<!-- ===================== 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>
      </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 dfrom = document.getElementById('dateFrom').value;
  const dto = document.getElementById('dateTo').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 (dfrom) params.set('date_from', dfrom);
  if (dto) params.set('date_to', dto);
  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));
}

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';
  });
});

// =============================================
// 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 = '+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 || '';
  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 = '+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 = '';
  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');

  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();
}

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 {
      res = await apiCall('handlers/communications.php', {
        action: 'send', 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>