<?php
// =============================================
// SHARK CRM - Settings
// =============================================

$account = $conn->query("SELECT * FROM accounts WHERE id = $account_id")->fetch_assoc();
$lost_reasons = $conn->query("SELECT * FROM lost_reason WHERE account_id = $account_id ORDER BY date_created DESC");
$all_users = $conn->query("SELECT u.*, r.name as role_name FROM users u LEFT JOIN roles r ON u.role_id = r.id WHERE u.account_id = $account_id ORDER BY u.datetime_created DESC");
$roles = $conn->query("SELECT * FROM roles WHERE account_id = $account_id");
$stages = $conn->query("SELECT * FROM stage WHERE account_id = $account_id ORDER BY position ASC");

// Get configuration settings (create table if needed)
// $config = $conn->query("SELECT * FROM account_config WHERE account_id = $account_id")->fetch_assoc();
// if (!$config) {
//     // Create default config if not exists
//     $conn->query("INSERT INTO account_config (account_id, whatsapp_number, sms_number, email_from) VALUES ($account_id, '', '', '')");
//     $config = ['whatsapp_number' => '', 'sms_number' => '', 'email_from' => ''];
// }

// Check if current user is admin
$current_user = $conn->query("SELECT role_id FROM users WHERE id = $user_id")->fetch_assoc();
$is_admin = $current_user && $current_user['role_id'] == 1; // Assuming role_id 1 is admin

// All countries
$all_countries = $conn->query("
    SELECT *
    FROM countries
    ORDER BY name ASC
");

// Account countries
$account_countries = [];

$res = $conn->query("
    SELECT country_id, is_default
    FROM country_account
    WHERE account_id = $account_id
");

while ($row = $res->fetch_assoc()) {
    $account_countries[$row['country_id']] = $row['is_default'];
}




// include 'whatsapp_connect_tab.php'; 
$wa_connected = $conn->query("
    SELECT client_id, phone_number
    FROM contact_phone
    WHERE account_id = $account_id
    LIMIT 1
")->fetch_assoc();


?>

<div class="fade-in">
<div class="tabs">
    
  <button class="tab-btn <?= (!isset($_GET['tab']) || $_GET['tab'] == 'account') ? 'active' : '' ?>" data-tab="tab-account" onclick="switchTab('account')">Account</button>
  <button class="tab-btn <?= (isset($_GET['tab']) && $_GET['tab'] == 'users') ? 'active' : '' ?>" data-tab="tab-users" onclick="switchTab('users')">Users</button>
  <button class="tab-btn <?= (isset($_GET['tab']) && $_GET['tab'] == 'lost') ? 'active' : '' ?>" data-tab="tab-lost" onclick="switchTab('lost')">Lost Reasons</button>
  <button class="tab-btn <?= (isset($_GET['tab']) && $_GET['tab'] == 'stages') ? 'active' : '' ?>" data-tab="tab-stages" onclick="switchTab('stages')">Stages</button>
  
  <button class="tab-btn <?= (isset($_GET['tab']) && $_GET['tab'] == 'whatsapp') ? 'active' : '' ?>"
        data-tab="tab-whatsapp"
        onclick="switchTab('whatsapp')">
  💬 WhatsApp
</button>

<button class="tab-btn <?= (isset($_GET['tab']) && $_GET['tab'] == 'countries') ? 'active' : '' ?>"
        data-tab="tab-countries"
        onclick="switchTab('countries')">
  🌍 Countries
</button>


  <button class="tab-btn <?= (isset($_GET['tab']) && $_GET['tab'] == 'password') ? 'active' : '' ?>" data-tab="tab-password" onclick="switchTab('password')">Password</button>
  <button class="tab-btn <?= (isset($_GET['tab']) && $_GET['tab'] == 'config') ? 'active' : '' ?>" data-tab="tab-config" onclick="switchTab('config')" style="display:none">⚙️ Configuration</button>
</div>

<!-- ===================== ACCOUNT TAB ===================== -->
<div class="tab-pane <?= (!isset($_GET['tab']) || $_GET['tab'] == 'account') ? 'active' : '' ?>" id="tab-account">
  <div class="card" style="max-width:600px">
    <div class="card-header"><span class="card-title">Account Settings</span></div>
    <div class="card-body">
      <form id="accountForm">
        <div class="form-grid">
          <div class="form-group">
            <label class="form-label">Client Name</label>
            <input type="text" name="client_name" class="form-control" value="<?= htmlspecialchars($account['client_name']) ?>">
          </div>
          <div class="form-group">
            <label class="form-label">Business Name</label>
            <input type="text" name="business_name" class="form-control" value="<?= htmlspecialchars($account['business_name']) ?>">
          </div>
          <div class="form-group">
            <label class="form-label">Phone</label>
            <input type="text" name="phone" class="form-control" value="<?= htmlspecialchars($account['phone']) ?>">
          </div>
          <div class="form-group">
            <label class="form-label">Email</label>
            <input type="email" name="email" class="form-control" value="<?= htmlspecialchars($account['email']) ?>">
          </div>
          <div class="form-group">
            <label class="form-label">Currency</label>
            <select name="currency" class="form-control">
              <?php foreach (['USD','EUR','GBP','AED','SAR','LBP'] as $c): ?>
              <option value="<?= $c ?>" <?= $account['currency']===$c?'selected':'' ?>><?= $c ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label class="form-label">Status</label>
            <select name="status" class="form-control">
              <option value="active" <?= $account['status']==='active'?'selected':'' ?>>Active</option>
              <option value="inactive" <?= $account['status']==='inactive'?'selected':'' ?>>Inactive</option>
            </select>
          </div>
        </div>
        <button type="button" class="btn btn-primary" onclick="saveAccount()">Save Changes</button>
      </form>
    </div>
  </div>
</div>

<!-- ===================== USERS TAB ===================== -->
<div class="tab-pane <?= (isset($_GET['tab']) && $_GET['tab'] == 'users') ? 'active' : '' ?>" id="tab-users">
  <div class="toolbar">
    <span class="card-title">Team Members</span>
    <?php if ($is_admin): ?>
    <button class="btn btn-primary btn-sm" onclick="openModal('addUserModal')" style="margin-left:auto">+ Add User</button>
    <?php endif; ?>
  </div>
  <div class="card">
    <div class="table-wrapper">
      <table class="crm-table">
        <thead><tr><th>Name</th><th>Email</th><th>Phone</th><th>Role</th><th>Since</th><th>Actions</th></tr></thead>
        <tbody>
          <?php while ($u = $all_users->fetch_assoc()): ?>
          <tr id="user_<?= $u['id'] ?>">
            <td><div class="d-flex align-center gap-8"><div class="avatar avatar-sm"><?= strtoupper(substr($u['name'],0,2)) ?></div><?= htmlspecialchars($u['name']) ?></div></td>
            <td><?= htmlspecialchars($u['email']) ?></td>
            <td><?= htmlspecialchars($u['phone'] ?: '—') ?></td>
            <td>
              <?php if ($is_admin && $u['id'] != $user_id): ?>
              <select class="form-control form-control-sm" onchange="changeUserRole(<?= $u['id'] ?>, this.value)">
                <option value="">No Role</option>
                <?php 
                $roles->data_seek(0);
                while ($ro = $roles->fetch_assoc()): 
                ?>
                <option value="<?= $ro['id'] ?>" <?= $u['role_id'] == $ro['id'] ? 'selected' : '' ?>><?= htmlspecialchars($ro['name']) ?></option>
                <?php endwhile; ?>
              </select>
              <?php else: ?>
              <span class="badge badge-blue"><?= htmlspecialchars($u['role_name'] ?: 'User') ?></span>
              <?php endif; ?>
             </td>
            <td class="text-muted text-xs"><?= formatDate($u['datetime_created']) ?></td>
            <td>
              <?php if ($u['id'] != $user_id): ?>
                <?php if ($is_admin): ?>
                <button class="btn btn-warning btn-sm" onclick="editUser(<?= $u['id'] ?>, '<?= addslashes($u['name']) ?>', '<?= addslashes($u['email']) ?>', '<?= addslashes($u['phone']) ?>', <?= $u['role_id'] ?: 'null' ?>)">Edit</button>
                <button class="btn btn-danger btn-sm" onclick="deleteUser(<?= $u['id'] ?>, '<?= addslashes($u['name']) ?>')">Remove</button>
                <?php endif; ?>
              <?php else: ?>
              <span class="badge badge-teal">You</span>
              <?php endif; ?>
             </td>
           </tr>
          <?php endwhile; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- ===================== LOST REASONS TAB ===================== -->
<div class="tab-pane <?= (isset($_GET['tab']) && $_GET['tab'] == 'lost') ? 'active' : '' ?>" id="tab-lost">
  <div class="toolbar">
    <span class="card-title">Lost Reasons</span>
    <?php if ($is_admin): ?>
    <button class="btn btn-primary btn-sm" onclick="openModal('addLostModal')" style="margin-left:auto">+ Add Reason</button>
    <?php endif; ?>
  </div>
  <div class="card">
    <div class="table-wrapper">
      <table class="crm-table" id="lostReasonsTable">
        <thead><tr><th>Reason</th><th>Status</th><th>Created</th><th>Actions</th></tr></thead>
        <tbody>
          <?php while ($lr = $lost_reasons->fetch_assoc()): ?>
          <tr id="lr_<?= $lr['id'] ?>">
            <td class="font-bold">
              <?php if ($is_admin): ?>
              <input type="text" class="form-control form-control-sm" id="lr_name_<?= $lr['id'] ?>" value="<?= htmlspecialchars($lr['name']) ?>" style="display:none;">
              <span id="lr_name_span_<?= $lr['id'] ?>"><?= htmlspecialchars($lr['name']) ?></span>
              <?php else: ?>
              <?= htmlspecialchars($lr['name']) ?>
              <?php endif; ?>
            </td>
            <td>
              <?php if ($is_admin): ?>
              <select class="form-control form-control-sm" id="lr_status_<?= $lr['id'] ?>" style="display:none;">
                <option value="active" <?= $lr['status']=='active'?'selected':'' ?>>Active</option>
                <option value="inactive" <?= $lr['status']=='inactive'?'selected':'' ?>>Inactive</option>
              </select>
              <?php endif; ?>
              <span class="badge badge-<?= $lr['status']==='active'?'green':'gray' ?>" id="lr_status_span_<?= $lr['id'] ?>"><?= ucfirst($lr['status']) ?></span>
            </td>
            <td class="text-muted text-xs"><?= formatDate($lr['date_created']) ?></td>
            <td>
              <?php if ($is_admin): ?>
              <button class="btn btn-warning btn-sm" id="lr_edit_btn_<?= $lr['id'] ?>" onclick="editLostReason(<?= $lr['id'] ?>)">Edit</button>
              <button class="btn btn-success btn-sm" id="lr_save_btn_<?= $lr['id'] ?>" style="display:none;" onclick="saveLostReason(<?= $lr['id'] ?>)">Save</button>
              <button class="btn btn-danger btn-sm" onclick="deleteLostReason(<?= $lr['id'] ?>)">Del</button>
              <?php endif; ?>
            </td>
          </tr>
          <?php endwhile; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- ===================== STAGES TAB ===================== -->
<div class="tab-pane <?= (isset($_GET['tab']) && $_GET['tab'] == 'stages') ? 'active' : '' ?>" id="tab-stages">
  <div class="toolbar">
    <span class="card-title">Deal Stages</span>
    <?php if ($is_admin): ?>
    <button class="btn btn-primary btn-sm" onclick="openModal('addStageModal')" style="margin-left:auto">+ Add Stage</button>
    <?php endif; ?>
  </div>

  <div class="card">
    <div class="table-wrapper">
      <table class="crm-table">
        <thead>
          <tr>
            <th>Stage</th>
            <th>Position</th>
            <th>Color</th>
            <th>Type</th>
            <th>Actions</th>
          </tr>
        </thead>
        <tbody>
        <?php while ($s = $stages->fetch_assoc()): ?>
        <tr id="stage_<?= $s['id'] ?>">
          <td class="font-bold">
            <?php if ($is_admin): ?>
            <input type="text" class="form-control form-control-sm" id="stage_name_<?= $s['id'] ?>" value="<?= htmlspecialchars($s['name']) ?>" style="display:none;">
            <span id="stage_name_span_<?= $s['id'] ?>"><?= htmlspecialchars($s['name']) ?></span>
            <?php else: ?>
            <?= htmlspecialchars($s['name']) ?>
            <?php endif; ?>
          </td>
          <td>
            <?php if ($is_admin): ?>
            <input type="number" class="form-control form-control-sm" id="stage_position_<?= $s['id'] ?>" value="<?= $s['position'] ?>" style="display:none; width:80px;">
            <span id="stage_position_span_<?= $s['id'] ?>"><?= $s['position'] ?></span>
            <?php else: ?>
            <?= $s['position'] ?>
            <?php endif; ?>
          </td>
          <td>
            <?php if ($is_admin): ?>
            <input type="color" class="form-control form-control-sm" id="stage_color_<?= $s['id'] ?>" value="<?= $s['color'] ?>" style="display:none; width:60px; height:30px;">
            <?php endif; ?>
            <span style="background:<?= $s['color'] ?>; width:18px; height:18px; display:inline-block; border-radius:4px;" id="stage_color_span_<?= $s['id'] ?>"></span>
          </td>
          <td>
            <?php if ($is_admin): ?>
            <select class="form-control form-control-sm" id="stage_type_<?= $s['id'] ?>" style="display:none;">
              <option value="normal" <?= (!$s['is_start'] && !$s['is_end']) ? 'selected' : '' ?>>Normal</option>
              <option value="start" <?= $s['is_start'] ? 'selected' : '' ?>>Start</option>
              <option value="end" <?= $s['is_end'] ? 'selected' : '' ?>>End</option>
            </select>
            <?php endif; ?>
            <span id="stage_type_span_<?= $s['id'] ?>">
              <?php
              if ($s['is_start']) echo '<span class="badge badge-green">Start</span>';
              elseif ($s['is_end']) echo '<span class="badge badge-red">End</span>';
              else echo '<span class="badge badge-blue">Normal</span>';
              ?>
            </span>
          </td>
          <td>
            <?php if ($is_admin): ?>
            <button class="btn btn-warning btn-sm" id="stage_edit_btn_<?= $s['id'] ?>" onclick="editStage(<?= $s['id'] ?>)">Edit</button>
            <button class="btn btn-success btn-sm" id="stage_save_btn_<?= $s['id'] ?>" style="display:none;" onclick="saveStage(<?= $s['id'] ?>)">Save</button>
            <button class="btn btn-danger btn-sm" onclick="deleteStage(<?= $s['id'] ?>)">Delete</button>
            <?php endif; ?>
          </td>
        </tr>
        <?php endwhile; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<!-- ===================== CONFIGURATION TAB ===================== -->
<div class="tab-pane <?= (isset($_GET['tab']) && $_GET['tab'] == 'config') ? 'active' : '' ?>" id="tab-config">
  <div class="card" style="max-width:600px">
    <div class="card-header">
      <span class="card-title">⚙️ Communication Configuration</span>
      <p class="text-muted text-sm" style="margin-top: 8px;">Set up default contact methods for sending WhatsApp, SMS, and Email from leads</p>
    </div>
    <div class="card-body">
      <form id="configForm">
        <div class="form-grid">
          <div class="form-group span-2">
            <label class="form-label">
              📱 WhatsApp Number
              <span class="text-muted text-xs">(Include country code, e.g., +96171234567)</span>
            </label>
            <input type="tel" name="whatsapp_number" id="whatsapp_number" class="form-control" 
                   placeholder="+96171234567" value="<?= htmlspecialchars($config['phone_number']) ?>">
            <div class="form-hint text-xs text-muted">Used when clicking WhatsApp button on lead contacts</div>
          </div>
          
          <div class="form-group span-2">
            <label class="form-label">
              ✉️ SMS Number
              <span class="text-muted text-xs">(For SMS gateway integration)</span>
            </label>
            <input type="tel" name="sms_number" id="sms_number" class="form-control" 
                   placeholder="+96171234567" value="<?= htmlspecialchars($config['sms_number']) ?>">
            <div class="form-hint text-xs text-muted">Number used for sending SMS messages via your SMS gateway</div>
          </div>
          
          <div class="form-group span-2">
            <label class="form-label">
              📧 Email From Address
              <span class="text-muted text-xs">(Sender email for communications)</span>
            </label>
            <input type="email" name="email_from" id="email_from" class="form-control" 
                   placeholder="contact@yourcompany.com" value="<?= htmlspecialchars($config['email_from']) ?>">
            <div class="form-hint text-xs text-muted">Email address that will appear as sender when sending emails from CRM</div>
          </div>
          
          <div class="form-group span-2">
            <label class="form-label">
              📧 Email Host / SMTP Server (Optional)
            </label>
            <input type="text" name="smtp_host" id="smtp_host" class="form-control" 
                   placeholder="smtp.gmail.com" value="<?= htmlspecialchars($config['smtp_host'] ?? '') ?>">
          </div>
          
          <div class="form-group">
            <label class="form-label">SMTP Port</label>
            <input type="number" name="smtp_port" id="smtp_port" class="form-control" 
                   placeholder="587" value="<?= htmlspecialchars($config['smtp_port'] ?? '') ?>">
          </div>
          
          <div class="form-group">
            <label class="form-label">SMTP Username</label>
            <input type="text" name="smtp_username" id="smtp_username" class="form-control" 
                   value="<?= htmlspecialchars($config['smtp_username'] ?? '') ?>">
          </div>
          
          <div class="form-group">
            <label class="form-label">SMTP Password</label>
            <input type="password" name="smtp_password" id="smtp_password" class="form-control" 
                   value="<?= htmlspecialchars($config['smtp_password'] ?? '') ?>">
            <div class="form-hint text-xs text-muted">Leave blank to keep existing password</div>
          </div>
          
          <div class="form-group span-2">
            <label class="form-label">
              🔗 WhatsApp API URL (Optional - for automated sending)
            </label>
            <input type="url" name="whatsapp_api_url" id="whatsapp_api_url" class="form-control" 
                   placeholder="https://api.whatsapp.com/send?phone=" value="<?= htmlspecialchars($config['whatsapp_api_url'] ?? '') ?>">
            <div class="form-hint text-xs text-muted">Custom API endpoint for WhatsApp integration</div>
          </div>
        </div>
        
        <div style="margin-top: 20px; display: flex; gap: 12px;">
          <button type="button" class="btn btn-primary" onclick="saveConfig()">💾 Save Configuration</button>
          <button type="button" class="btn btn-secondary" onclick="testWhatsApp()">📱 Test WhatsApp</button>
          <button type="button" class="btn btn-secondary" onclick="testEmail()">📧 Test Email</button>
        </div>
      </form>
    </div>
  </div>
  
  <!-- Usage Instructions -->
  <div class="card" style="margin-top: 24px;">
    <div class="card-header">
      <span class="card-title">📖 How to Use</span>
    </div>
    <div class="card-body">
      <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px;">
        <div>
          <h4>📱 WhatsApp</h4>
          <p class="text-sm text-muted">The WhatsApp number will be used when you click the WhatsApp button in:</p>
          <ul class="text-sm">
            <li>Lead details page</li>
            <li>Customer contacts list</li>
            <li>Quick contact buttons</li>
          </ul>
        </div>
        <div>
          <h4>✉️ SMS</h4>
          <p class="text-sm text-muted">The SMS number will be used for sending text messages through your SMS gateway integration.</p>
        </div>
        <div>
          <h4>📧 Email</h4>
          <p class="text-sm text-muted">The email address will appear as the sender when sending emails from:</p>
          <ul class="text-sm">
            <li>Lead follow-ups</li>
            <li>Activity notifications</li>
            <li>Customer communications</li>
          </ul>
        </div>
      </div>
    </div>
  </div>
</div>


<!-- ===================== WHATSAPP CONNECT TAB ===================== -->
<div class="tab-pane <?= (isset($_GET['tab']) && $_GET['tab'] == 'whatsapp') ? 'active' : '' ?>" id="tab-whatsapp">
  <div style="max-width:700px">

    <!-- Header -->
    <div class="card" style="margin-bottom:20px;background:linear-gradient(135deg,#25D366 0%,#128C7E 100%);border:none;">
      <div class="card-body" style="display:flex;align-items:center;gap:16px;padding:24px;">
        <div style="width:56px;height:56px;background:rgba(255,255,255,0.2);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:28px;flex-shrink:0;">💬</div>
        <div>
          <div style="font-size:20px;font-weight:700;color:#fff;">WhatsApp Connect</div>
          <div style="color:rgba(255,255,255,0.85);font-size:14px;margin-top:2px;">Link your WhatsApp number to send messages directly from the CRM</div>
        </div>
      </div>
    </div>

    <?php if ($wa_connected): ?>
    <!-- ══════════ ALREADY CONNECTED ══════════ -->
    <div class="card" style="margin-bottom:20px;border:2px solid #25D366;">
      <div class="card-body" style="padding:24px;">
        <div style="display:flex;align-items:center;gap:16px;">
          <div style="width:52px;height:52px;background:#DCFCE7;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:26px;flex-shrink:0;">✅</div>
          <div style="flex:1;">
            <div style="font-weight:700;font-size:16px;color:#166534;">WhatsApp Connected</div>
            <div class="text-sm text-muted" style="margin-top:4px;">
              Phone: <strong><?= htmlspecialchars($wa_connected['phone_number'] ?: '—') ?></strong>
            </div>
            <div class="text-xs text-muted" style="margin-top:2px;">Client ID: <?= htmlspecialchars($wa_connected['client_id']) ?></div>
          </div>
          <button class="btn btn-danger btn-sm" onclick="disconnectAndReset('<?= htmlspecialchars($wa_connected['client_id']) ?>')">🔌 Disconnect</button>
        </div>
      </div>
    </div>

    <?php else: ?>
    <!-- ══════════ NOT CONNECTED — Connect Flow ══════════ -->

    <!-- Step 1: Create Client -->
    <div class="card" id="wa-step-create" style="margin-bottom:20px;">
      <div class="card-header">
        <span class="card-title">
          <span style="display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;background:var(--primary,#3B82F6);color:#fff;border-radius:50%;font-size:12px;font-weight:700;margin-right:8px;">1</span>
          Create WhatsApp Client
        </span>
      </div>
      <div class="card-body">
        <p class="text-muted text-sm" style="margin-bottom:16px;">Give your WhatsApp connection a name, then scan the QR code with your phone.</p>
        <div style="display:flex;gap:12px;align-items:flex-end;">
          <div class="form-group" style="flex:1;margin-bottom:0;">
            <label class="form-label">Connection Name *</label>
            <input type="text" id="wa_client_name" class="form-control" placeholder="e.g. Sales Line">
          </div>
          <button class="btn btn-primary" onclick="createWaClient()" id="wa_create_btn" style="white-space:nowrap;">
            🔗 Connect WhatsApp
          </button>
        </div>
      </div>
    </div>

    <!-- Step 2: QR Code -->
    <div class="card" id="wa-step-qr" style="margin-bottom:20px;display:none;">
      <div class="card-header">
        <span class="card-title">
          <span style="display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;background:var(--primary,#3B82F6);color:#fff;border-radius:50%;font-size:12px;font-weight:700;margin-right:8px;">2</span>
          Scan QR Code with WhatsApp
        </span>
      </div>
      <div class="card-body">
        <div style="display:flex;gap:32px;align-items:flex-start;flex-wrap:wrap;">

          <!-- QR Image -->
          <div style="text-align:center;flex-shrink:0;">
            <div id="wa_qr_wrapper" style="width:224px;height:224px;border:3px solid #25D366;border-radius:16px;overflow:hidden;background:#fff;display:flex;align-items:center;justify-content:center;">
              <div id="wa_qr_loading" style="text-align:center;color:#888;padding:16px;">
                <div style="font-size:32px;margin-bottom:8px;">⏳</div>
                <div style="font-size:13px;">Loading QR...</div>
              </div>
              <img id="wa_qr_img"
     src=""
     alt="QR Code"
     style="width:100%;height:100%;object-fit:contain;display:none;"
     onload="
        document.getElementById('wa_qr_loading').style.display='none';
        this.style.display='block';
     "
     onerror="
        document.getElementById('wa_qr_loading').innerHTML='❌ Failed loading QR';
     "
>
                   
            </div>
            <div style="margin-top:10px;">
              <span id="wa_status_badge" class="badge badge-gray">Initializing...</span>
            </div>
            <button class="btn btn-secondary btn-sm" style="margin-top:10px;" onclick="refreshQR()" id="wa_refresh_btn">🔄 Refresh QR</button>
          </div>

          <!-- Instructions -->
          <div style="flex:1;min-width:200px;">
            <p class="text-sm font-bold" style="margin-bottom:12px;">How to scan:</p>
            <ol style="padding-left:20px;color:var(--text-muted,#6B7280);font-size:14px;line-height:2.2;">
              <li>Open WhatsApp on your phone</li>
              <li>Tap <strong>⋮ Menu</strong> (Android) or <strong>Settings</strong> (iPhone)</li>
              <li>Tap <strong>Linked Devices</strong></li>
              <li>Tap <strong>Link a Device</strong></li>
              <li>Point your phone at the QR code</li>
            </ol>
            <div id="wa_connected_msg" style="display:none;margin-top:16px;padding:14px;background:#F0FDF4;border:1px solid #86EFAC;border-radius:10px;">
              <div style="font-size:20px;margin-bottom:4px;">✅</div>
              <div style="font-weight:700;color:#166534;">Connected!</div>
              <div style="font-size:13px;color:#166534;margin-top:4px;">Saving to database...</div>
            </div>
          </div>
        </div>

        <div style="margin-top:20px;">
          <button class="btn btn-secondary btn-sm" onclick="resetWaStep()">← Start Over</button>
        </div>
      </div>
    </div>

    <?php endif; ?>
  </div>
</div>
<script>
// ──────────────────────────────────────────────
// WhatsApp Connect JS
// ──────────────────────────────────────────────
const WA_API_BASE = 'https://amctag-whats.38f0fz.easypanel.host/api';
const WA_TOKEN    = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiI3MzFiMTlhNDdlZDg2MjUxZDg2YjYyYTYiLCJ0eXBlIjoidXNlciIsImlhdCI6MTc3OTE3NzE1Nn0.NaszEOLCnWT59oXBCdi7WKwXT-QbZWpFF3G_64fsTDs';

let waClientId   = null;  // "client_xxxx"
let waInternalId = null;  // MongoDB _id
let waImageUrl   = null;  // QR PNG url
let waPollTimer  = null;
let waPollActive = false;

async function waFetch(path, method = 'GET', body = null) {
    const opts = {
        method,
        headers: { 'Authorization': `Bearer ${WA_TOKEN}`, 'Content-Type': 'application/json' }
    };
    if (body) opts.body = JSON.stringify(body);
    const res = await fetch(WA_API_BASE + path, opts);
    return res.json();
}

// ── 1. Create Client ──────────────────────────────────────────
async function createWaClient() {
    const name = document.getElementById('wa_client_name').value.trim();
    if (!name) { showToast('Enter a connection name', 'warning'); return; }

    const btn = document.getElementById('wa_create_btn');
    btn.disabled = true;
    btn.innerHTML = '⏳ Creating...';

    try {
        const data = await waFetch('/clients', 'POST', { name });

        if (data.client && data.qrShare) {
            waClientId   = data.client.clientId;
            waInternalId = data.client._id;
            waImageUrl   = data.qrShare.imageUrl;
            if (waImageUrl.startsWith('http://')) {
    waImageUrl = waImageUrl.replace('http://', 'https://');
}

            // بنبين الـ QR step وبنحمل الصورة فورًا
            document.getElementById('wa-step-create').style.display = 'none';
            document.getElementById('wa-step-qr').style.display     = 'block';
            loadQRImage();
            startStatusPoll();
            showToast('Client created! Scan the QR.', 'success');
        } else {
            showToast(data.message || 'Failed to create client', 'error');
            btn.disabled = false;
            btn.innerHTML = '🔗 Connect WhatsApp';
        }
    } catch(e) {
        showToast('Network error: ' + e.message, 'error');
        btn.disabled = false;
        btn.innerHTML = '🔗 Connect WhatsApp';
    }
}

// ── 2. Load QR Image (فوري من الـ imageUrl) ──────────────────
// function loadQRImage() {
//     if (!waImageUrl) return;

//     const img     = document.getElementById('wa_qr_img');
//     const loading = document.getElementById('wa_qr_loading');

//     // نخبي الصورة القديمة ونبين الـ spinner
//     img.style.display     = 'none';
//     loading.style.display = 'block';
//     loading.innerHTML     = '<div style="font-size:28px">⏳</div><div style="font-size:13px;margin-top:6px">Loading QR...</div>';

//     // cache-buster
//     const sep = waImageUrl.includes('?') ? '&' : '?';
//     img.src = waImageUrl ;
//     // img.src = "https://www.amctag.com/assets/images/logo-blue-2.png";
//     // الـ onload بالـ HTML راح يخبي الـ spinner وبيبين الصورة
// }


let qrRetryCount = 0;
let qrRetryTimer = null;

function loadQRImage() {
    if (!waImageUrl) return;

    const img = document.getElementById('wa_qr_img');
    const loading = document.getElementById('wa_qr_loading');

    qrRetryCount = 0;
    clearTimeout(qrRetryTimer);

    function tryLoadQR() {
        qrRetryCount++;

        img.style.display = 'none';
        loading.style.display = 'block';
        loading.innerHTML =
            '<div style="font-size:28px">⏳</div>' +
            '<div style="font-size:13px;margin-top:6px">Loading QR... attempt ' + qrRetryCount + '</div>';

        const url = waImageUrl.replace('http://', 'https://');
        const sep = url.includes('?') ? '&' : '?';

        img.onload = function () {
            clearTimeout(qrRetryTimer);
            loading.style.display = 'none';
            img.style.display = 'block';
        };

        img.onerror = function () {
            console.log('QR not ready, retry...', img.src);

            if (qrRetryCount < 15) {
                qrRetryTimer = setTimeout(tryLoadQR, 1000);
            } else {
                loading.innerHTML =
                    '<div style="font-size:20px">❌</div>' +
                    '<div style="font-size:12px;margin-top:6px">QR not ready. Click Refresh</div>';
            }
        };

        img.src = url + sep + '_t=' + Date.now();
    }

    tryLoadQR();
}



// ── 3. Refresh QR ─────────────────────────────────────────────
function refreshQR() {
    const btn = document.getElementById('wa_refresh_btn');
    btn.disabled = true;
    btn.textContent = '⏳';
    loadQRImage();
    setTimeout(() => { btn.disabled = false; btn.textContent = '🔄 Refresh QR'; }, 1800);
}

// ── 4. Poll Status — بيوقف فور connected ─────────────────────
function startStatusPoll() {
    clearInterval(waPollTimer);
    waPollActive = true;

    waPollTimer = setInterval(async () => {
        if (!waPollActive || !waClientId) {
            clearInterval(waPollTimer);
            return;
        }

        try {
            const data    = await waFetch('/clients');
            const clients = Array.isArray(data) ? data : (data.clients || []);
            const client  = clients.find(c => c.clientId === waClientId);
            if (!client) return;

            const status = client.status || '';
            updateStatusBadge(status);

            if (status === 'connected' || status === 'ready') {
                // ✅ وقف الـ poll فورًا
                waPollActive = false;
                clearInterval(waPollTimer);
                onWaConnected(client.phone || null);
            }
        } catch(e) { /* silent */ }
    }, 3000);
}

// ── 5. On Connected — بيحفظ بالـ DB وبـ reload ───────────────
async function onWaConnected(phone) {
    document.getElementById('wa_connected_msg').style.display = 'block';
    document.getElementById('wa_qr_wrapper').style.borderColor = '#25D366';
    updateStatusBadge('connected');
    showToast('WhatsApp connected! 🎉', 'success');

    try {
        const res = await apiCall('handlers/settings.php', {
            action:       'save_wa_client',
            client_id:    waInternalId,
            phone_number: phone || ''
        });
        if (res.success) {
            showToast('Saved! Reloading...', 'success');
            setTimeout(() => location.reload(), 1500);
        } else {
            showToast('Connected but DB error: ' + (res.message || ''), 'warning');
        }
    } catch(e) {
        showToast('Connected but could not save to DB', 'warning');
    }
}

// ── Status Badge ──────────────────────────────────────────────
function updateStatusBadge(status) {
    const badge = document.getElementById('wa_status_badge');
    if (!badge) return;
    const map = {
        'initializing': { cls:'badge-gray',  txt:'Initializing...' },
        'qr_ready':     { cls:'badge-blue',  txt:'Waiting for scan...' },
        'connecting':   { cls:'badge-blue',  txt:'Connecting...' },
        'connected':    { cls:'badge-green', txt:'Connected ✓' },
        'ready':        { cls:'badge-green', txt:'Connected ✓' },
        'disconnected': { cls:'badge-red',   txt:'Disconnected' },
    };
    const info = map[status] || { cls:'badge-gray', txt: status || '—' };
    badge.className   = 'badge ' + info.cls;
    badge.textContent = info.txt;
}

// ── Disconnect من الـ connected card ─────────────────────────
async function disconnectAndReset(clientId) {
    if (!confirm('Disconnect WhatsApp and remove from CRM?')) return;
    try { await waFetch('/clients/' + clientId + '/disconnect', 'POST'); } catch(e) {}
    const res = await apiCall('handlers/settings.php', { action: 'delete_wa_client' });
    if (res.success) {
        showToast('Disconnected', 'success');
        setTimeout(() => location.reload(), 800);
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

// ── Start Over ────────────────────────────────────────────────
function resetWaStep() {
    waPollActive = false;
    clearInterval(waPollTimer);
    waClientId = waInternalId = waImageUrl = null;

    document.getElementById('wa-step-create').style.display = 'block';
    document.getElementById('wa-step-qr').style.display     = 'none';
    document.getElementById('wa_client_name').value         = '';

    const btn = document.getElementById('wa_create_btn');
    if (btn) { btn.disabled = false; btn.innerHTML = '🔗 Connect WhatsApp'; }

    const img     = document.getElementById('wa_qr_img');
    const loading = document.getElementById('wa_qr_loading');
    if (img)     { img.src = ''; img.style.display = 'none'; }
    if (loading) { loading.style.display = 'block'; loading.innerHTML = '<div style="font-size:28px">⏳</div><div style="font-size:13px;margin-top:6px">Loading QR...</div>'; }

    const msg = document.getElementById('wa_connected_msg');
    if (msg) msg.style.display = 'none';
}

// ── وقف الـ poll لو المستخدم غير الـ tab ─────────────────────
document.addEventListener('click', function(e) {
    const btn = e.target.closest('.tab-btn');
    if (btn && btn.dataset.tab !== 'tab-whatsapp') {
        waPollActive = false;
        clearInterval(waPollTimer);
    }
});
</script>


<!-- ===================== PASSWORD TAB ===================== -->
<div class="tab-pane <?= (isset($_GET['tab']) && $_GET['tab'] == 'password') ? 'active' : '' ?>" id="tab-password">
  <div class="card" style="max-width:400px">
    <div class="card-header"><span class="card-title">Change Password</span></div>
    <div class="card-body">
      <form id="pwForm">
        <div class="form-group">
          <label class="form-label">Current Password</label>
          <input type="password" name="current_password" class="form-control" required>
        </div>
        <div class="form-group">
          <label class="form-label">New Password</label>
          <input type="password" name="new_password" class="form-control" required minlength="6">
        </div>
        <div class="form-group">
          <label class="form-label">Confirm New Password</label>
          <input type="password" name="confirm_password" class="form-control" required>
        </div>
        <button type="button" class="btn btn-primary" onclick="changePassword()">Update Password</button>
      </form>
    </div>
  </div>
</div>
</div>



<!-- ===================== COUNTRIES TAB ===================== -->
<div class="tab-pane <?= (isset($_GET['tab']) && $_GET['tab'] == 'countries') ? 'active' : '' ?>" id="tab-countries">

<style>
.countries-grid{
  display:grid;
  grid-template-columns: repeat(auto-fill, minmax(170px, 1fr));
  gap:12px;
}

.country-box{
  border:1px solid #eee;
  border-radius:12px;
  padding:12px;
  display:flex;
  justify-content:space-between;
  align-items:flex-start;
  cursor:pointer;
  transition:0.2s;
  background:#fff;
}

.country-box:hover{
  border-color:#3B82F6;
  transform:translateY(-2px);
}

.country-left{
  display:flex;
  flex-direction:column;
  gap:4px;
}

.country-name{
  font-weight:600;
  font-size:14px;
}

.default-badge{
  font-size:10px;
  padding:2px 6px;
  border-radius:6px;
  background:#10b981;
  color:#fff;
  width:fit-content;
}

.country-right{
  display:flex;
  flex-direction:column;
  align-items:center;
  gap:6px;
}

.country-right small{
  font-size:10px;
  color:#666;
}
</style>

<div class="card" >

  <div class="card-header">
    <span class="card-title">🌍 Available Countries</span>
  </div>

  <div class="card-body">

    <!-- SEARCH -->
    <div class="form-group" style="margin-bottom:15px;">
      <input 
        type="text" 
        id="countrySearch" 
        class="form-control" 
        placeholder="Search country..."
        onkeyup="filterCountriesGrid()"
      >
    </div>

    <!-- GRID -->
    <div id="countriesList" class="countries-grid">

      <?php 
      // IMPORTANT: use $all_countries only ONCE (clone result first)
      $countriesRes = $conn->query("SELECT * FROM countries ORDER BY name ASC");

      while($c = $countriesRes->fetch_assoc()):
        $isChecked = isset($account_countries[$c['id']]);
        $isDefault = ($config['default_country'] ?? 0) == $c['id'];
      ?>

        <div class="country-box country-item" data-name="<?= strtolower($c['name']) ?>">

          <div class="country-left">
            <div class="country-name">
              <?= htmlspecialchars($c['name']) ?>
            </div>

            <?php if($isDefault): ?>
              <div class="default-badge">DEFAULT</div>
            <?php endif; ?>
          </div>

          <div class="country-right">

            <!-- SELECT COUNTRY -->
            <input 
              type="checkbox"
              class="country-checkbox"
              value="<?= $c['id'] ?>"
              <?= $isChecked ? 'checked' : '' ?>
            >

            <!-- DEFAULT COUNTRY -->
            <input 
              type="radio"
              name="default_country"
              value="<?= $c['id'] ?>"
              <?= $isDefault ? 'checked' : '' ?>
            >
            <small>default</small>

          </div>

        </div>

      <?php endwhile; ?>

    </div>

    <!-- SAVE -->
    <div style="margin-top:20px;">
      <button type="button" class="btn btn-primary" onclick="saveCountries()">
        💾 Save Countries
      </button>
    </div>

  </div>
</div>
</div>

<!-- ADD USER MODAL -->
<div class="modal-overlay" id="addUserModal">
  <div class="modal">
    <div class="modal-header"><span class="modal-title">Add User</span><button class="modal-close">✕</button></div>
    <div class="modal-body">
      <form id="addUserForm">
        <div class="form-grid">
          <div class="form-group"><label class="form-label">Name *</label><input type="text" name="name" class="form-control" required></div>
          <div class="form-group"><label class="form-label">Phone</label><input type="text" name="phone" class="form-control"></div>
          <div class="form-group span-2"><label class="form-label">Email *</label><input type="email" name="email" class="form-control" required></div>
          <div class="form-group"><label class="form-label">Password *</label><input type="password" name="password" class="form-control" required minlength="6"></div>
          <div class="form-group"><label class="form-label">Role</label>
            <select name="role_id" class="form-control">
              <option value="">No Role</option>
              <?php $roles->data_seek(0); while ($ro = $roles->fetch_assoc()): ?>
              <option value="<?= $ro['id'] ?>"><?= htmlspecialchars($ro['name']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>
        </div>
      </form>
    </div>
    <div class="modal-footer">
      <button class="btn btn-secondary" onclick="closeModal('addUserModal')">Cancel</button>
      <button class="btn btn-primary" onclick="addUser()">Add User</button>
    </div>
  </div>
</div>

<!-- EDIT USER MODAL -->
<div class="modal-overlay" id="editUserModal">
  <div class="modal">
    <div class="modal-header"><span class="modal-title">Edit User</span><button class="modal-close">✕</button></div>
    <div class="modal-body">
      <form id="editUserForm">
        <input type="hidden" name="user_id" id="edit_user_id">
        <div class="form-grid">
          <div class="form-group"><label class="form-label">Name *</label><input type="text" name="name" id="edit_user_name" class="form-control" required></div>
          <div class="form-group"><label class="form-label">Phone</label><input type="text" name="phone" id="edit_user_phone" class="form-control"></div>
          <div class="form-group span-2"><label class="form-label">Email *</label><input type="email" name="email" id="edit_user_email" class="form-control" required></div>
          <div class="form-group"><label class="form-label">New Password (leave blank to keep current)</label><input type="password" name="password" class="form-control" minlength="6"></div>
          <div class="form-group"><label class="form-label">Role</label>
            <select name="role_id" id="edit_user_role" class="form-control">
              <option value="">No Role</option>
              <?php $roles->data_seek(0); while ($ro = $roles->fetch_assoc()): ?>
              <option value="<?= $ro['id'] ?>"><?= htmlspecialchars($ro['name']) ?></option>
              <?php endwhile; ?>
            </select>
          </div>
        </div>
      </form>
    </div>
    <div class="modal-footer">
      <button class="btn btn-secondary" onclick="closeModal('editUserModal')">Cancel</button>
      <button class="btn btn-primary" onclick="updateUser()">Update User</button>
    </div>
  </div>
</div>

<!-- ADD LOST REASON MODAL -->
<div class="modal-overlay" id="addLostModal">
  <div class="modal">
    <div class="modal-header"><span class="modal-title">Add Lost Reason</span><button class="modal-close">✕</button></div>
    <div class="modal-body">
      <div class="form-group"><label class="form-label">Reason *</label><input type="text" id="lostReasonInput" class="form-control" placeholder="e.g. Price too high"></div>
    </div>
    <div class="modal-footer">
      <button class="btn btn-secondary" onclick="closeModal('addLostModal')">Cancel</button>
      <button class="btn btn-primary" onclick="addLostReason()">Add</button>
    </div>
  </div>
</div>

<!-- ADD STAGE MODAL -->
<div class="modal-overlay" id="addStageModal">
  <div class="modal">
    <div class="modal-header">
      <span class="modal-title">Add Stage</span>
      <button class="modal-close">✕</button>
    </div>
    <div class="modal-body">
      <div class="form-group">
        <label class="form-label">Stage Name *</label>
        <input type="text" id="stageName" class="form-control">
      </div>
      <div class="form-group">
        <label class="form-label">Position</label>
        <input type="number" id="stagePosition" class="form-control">
      </div>
      <div class="form-group">
        <label class="form-label">Color</label>
        <input type="color" id="stageColor" class="form-control" value="#6B7280">
      </div>
      <div class="form-group">
        <label class="form-label">Type</label>
        <select id="stageType" class="form-control">
          <option value="normal">Normal</option>
          <option value="start">Start</option>
          <option value="end">End</option>
        </select>
      </div>
    </div>
    <div class="modal-footer">
      <button class="btn btn-secondary" onclick="closeModal('addStageModal')">Cancel</button>
      <button class="btn btn-primary" onclick="addStage()">Add</button>
    </div>
  </div>
</div>

<script>
// Tab switching function with URL parameter
function switchTab(tabName) {
    // Update URL without reloading
    const url = new URL(window.location.href);
    url.searchParams.set('tab', tabName);
    window.history.pushState({}, '', url);
    
    // Hide all tab panes
    document.querySelectorAll('.tab-pane').forEach(pane => {
        pane.classList.remove('active');
    });
    
    // Show selected tab pane
    document.getElementById('tab-' + tabName).classList.add('active');
    
    // Update tab buttons
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('active');
        if (btn.dataset.tab === 'tab-' + tabName) {
            btn.classList.add('active');
        }
    });
}

// Initialize tabs on page load
document.addEventListener('DOMContentLoaded', function() {
    const urlParams = new URLSearchParams(window.location.search);
    const tab = urlParams.get('tab');
    if (tab) {
        switchTab(tab);
    }
});



// Test WhatsApp
function testWhatsApp() {
    const whatsappNumber = document.getElementById('whatsapp_number').value;
    if (!whatsappNumber) {
        showToast('Please set a WhatsApp number first', 'warning');
        return;
    }
    const message = encodeURIComponent('Hello! This is a test message from SHARK CRM.');
    window.open(`https://wa.me/${whatsappNumber.replace(/[^0-9+]/g, '')}?text=${message}`, '_blank');
}

async function testEmail() {
    const emailFrom = document.getElementById('email_from').value;
    if (!emailFrom) {
        showToast('Please set an email address first', 'warning');
        return;
    }
    
    const res = await apiCall('handlers/settings.php', { 
        action: 'test_email',
        email: emailFrom
    });
    
    if (res.success) {
        showToast('Test email sent successfully!', 'success');
    } else {
        showToast(res.message || 'Failed to send test email', 'error');
    }
}

function editUser(id, name, email, phone, roleId) {
    document.getElementById('edit_user_id').value = id;
    document.getElementById('edit_user_name').value = name;
    document.getElementById('edit_user_email').value = email;
    document.getElementById('edit_user_phone').value = phone || '';
    document.getElementById('edit_user_role').value = roleId || '';
    openModal('editUserModal');
}

async function updateUser() {
    const fd = new FormData(document.getElementById('editUserForm'));
    fd.append('action', 'update_user');
    
    const res = await apiCall('handlers/settings.php', fd);
    if (res.success) { 
        showToast('User updated!', 'success'); 
        closeModal('editUserModal'); 
        setTimeout(() => location.reload(), 600); 
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

async function changeUserRole(userId, roleId) {
    const res = await apiCall('handlers/settings.php', {
        action: 'update_user_role',
        user_id: userId,
        role_id: roleId
    });
    
    if (res.success) {
        showToast('Role updated!', 'success');
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

function editLostReason(id) {
    document.getElementById('lr_name_span_' + id).style.display = 'none';
    document.getElementById('lr_name_' + id).style.display = 'block';
    document.getElementById('lr_status_span_' + id).style.display = 'none';
    document.getElementById('lr_status_' + id).style.display = 'block';
    document.getElementById('lr_edit_btn_' + id).style.display = 'none';
    document.getElementById('lr_save_btn_' + id).style.display = 'inline-block';
}

async function saveLostReason(id) {
    const name = document.getElementById('lr_name_' + id).value.trim();
    const status = document.getElementById('lr_status_' + id).value;
    
    if (!name) {
        showToast('Please enter a reason', 'warning');
        return;
    }
    
    const res = await apiCall('handlers/settings.php', {
        action: 'update_lost_reason',
        id: id,
        name: name,
        status: status
    });
    
    if (res.success) {
        showToast('Lost reason updated!', 'success');
        document.getElementById('lr_name_span_' + id).textContent = name;
        document.getElementById('lr_status_span_' + id).textContent = status.charAt(0).toUpperCase() + status.slice(1);
        document.getElementById('lr_status_span_' + id).className = 'badge badge-' + (status === 'active' ? 'green' : 'gray');
        
        // Reset display
        document.getElementById('lr_name_span_' + id).style.display = 'inline';
        document.getElementById('lr_name_' + id).style.display = 'none';
        document.getElementById('lr_status_span_' + id).style.display = 'inline';
        document.getElementById('lr_status_' + id).style.display = 'none';
        document.getElementById('lr_edit_btn_' + id).style.display = 'inline-block';
        document.getElementById('lr_save_btn_' + id).style.display = 'none';
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

function editStage(id) {
    document.getElementById('stage_name_span_' + id).style.display = 'none';
    document.getElementById('stage_name_' + id).style.display = 'block';
    document.getElementById('stage_position_span_' + id).style.display = 'none';
    document.getElementById('stage_position_' + id).style.display = 'block';
    document.getElementById('stage_color_span_' + id).style.display = 'none';
    document.getElementById('stage_color_' + id).style.display = 'block';
    document.getElementById('stage_type_span_' + id).style.display = 'none';
    document.getElementById('stage_type_' + id).style.display = 'block';
    document.getElementById('stage_edit_btn_' + id).style.display = 'none';
    document.getElementById('stage_save_btn_' + id).style.display = 'inline-block';
}

async function saveStage(id) {
    const name = document.getElementById('stage_name_' + id).value.trim();
    const position = document.getElementById('stage_position_' + id).value;
    const color = document.getElementById('stage_color_' + id).value;
    const type = document.getElementById('stage_type_' + id).value;
    
    if (!name) {
        showToast('Enter stage name', 'warning');
        return;
    }
    
    const res = await apiCall('handlers/settings.php', {
        action: 'update_stage',
        id: id,
        name: name,
        position: position,
        color: color,
        type: type
    });
    
    if (res.success) {
        showToast('Stage updated!', 'success');
        
        // Update displayed values
        document.getElementById('stage_name_span_' + id).textContent = name;
        document.getElementById('stage_position_span_' + id).textContent = position;
        document.getElementById('stage_color_span_' + id).style.backgroundColor = color;
        
        // Update type badge
        let typeHtml = '';
        if (type === 'start') typeHtml = '<span class="badge badge-green">Start</span>';
        else if (type === 'end') typeHtml = '<span class="badge badge-red">End</span>';
        else typeHtml = '<span class="badge badge-blue">Normal</span>';
        document.getElementById('stage_type_span_' + id).innerHTML = typeHtml;
        
        // Reset display
        document.getElementById('stage_name_span_' + id).style.display = 'inline';
        document.getElementById('stage_name_' + id).style.display = 'none';
        document.getElementById('stage_position_span_' + id).style.display = 'inline';
        document.getElementById('stage_position_' + id).style.display = 'none';
        document.getElementById('stage_color_span_' + id).style.display = 'inline-block';
        document.getElementById('stage_color_' + id).style.display = 'none';
        document.getElementById('stage_type_span_' + id).style.display = 'inline';
        document.getElementById('stage_type_' + id).style.display = 'none';
        document.getElementById('stage_edit_btn_' + id).style.display = 'inline-block';
        document.getElementById('stage_save_btn_' + id).style.display = 'none';
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

async function addStage() {
    const name = document.getElementById('stageName').value.trim();
    const position = document.getElementById('stagePosition').value;
    const color = document.getElementById('stageColor').value;
    const type = document.getElementById('stageType').value;

    if (!name) {
        showToast('Enter stage name', 'warning');
        return;
    }

    const res = await apiCall('handlers/settings.php', {
        action: 'add_stage',
        name: name,
        position: position,
        color: color,
        type: type
    });

    if (res.success) {
        showToast('Stage added!', 'success');
        closeModal('addStageModal');
        setTimeout(() => location.reload(), 600);
    }
}

async function deleteStage(id) {
    confirmAction('Delete this stage?', async () => {
        const res = await apiCall('handlers/settings.php', {
            action: 'delete_stage',
            id: id
        });

        if (res.success) {
            showToast('Stage deleted', 'success');
            document.getElementById('stage_' + id).remove();
        }
    });
}

async function saveAccount() {
    const fd = new FormData(document.getElementById('accountForm'));
    fd.append('action', 'update');
    const res = await apiCall('handlers/settings.php', fd);
    if (res.success) {
        showToast('Account updated!', 'success');
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

async function addUser() {
    const fd = new FormData(document.getElementById('addUserForm'));
    fd.append('action', 'add_user');
    const res = await apiCall('handlers/settings.php', fd);
    if (res.success) { 
        showToast('User added!', 'success'); 
        closeModal('addUserModal'); 
        setTimeout(() => location.reload(), 600); 
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

async function deleteUser(id, name) {
    confirmAction(`Remove user "${name}"?`, async () => {
        const res = await apiCall('handlers/settings.php', { action: 'delete_user', id: id });
        if (res.success) { 
            showToast('User removed', 'success'); 
            setTimeout(() => location.reload(), 600); 
        } else {
            showToast(res.message || 'Error', 'error');
        }
    });
}

async function addLostReason() {
    const name = document.getElementById('lostReasonInput').value.trim();
    if (!name) { 
        showToast('Please enter a reason', 'warning'); 
        return; 
    }
    const res = await apiCall('handlers/settings.php', { action: 'add_lost_reason', name: name });
    if (res.success) { 
        showToast('Added!', 'success'); 
        closeModal('addLostModal'); 
        setTimeout(() => location.reload(), 600); 
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

async function deleteLostReason(id) {
    confirmAction('Delete this lost reason?', async () => {
        const res = await apiCall('handlers/settings.php', { action: 'delete_lost_reason', id: id });
        if (res.success) { 
            showToast('Deleted', 'success'); 
            const el = document.getElementById('lr_' + id); 
            if (el) el.remove(); 
        } else {
            showToast(res.message || 'Error', 'error');
        }
    });
}

async function changePassword() {
    const f = document.getElementById('pwForm');
    const np = f.querySelector('[name=new_password]').value;
    const cp = f.querySelector('[name=confirm_password]').value;
    if (np !== cp) { 
        showToast('Passwords do not match', 'error'); 
        return; 
    }
    const fd = new FormData(f);
    fd.append('action', 'change_password');
    const res = await apiCall('handlers/settings.php', fd);
    if (res.success) { 
        showToast('Password updated!', 'success'); 
        f.reset(); 
    } else {
        showToast(res.message || 'Error', 'error');
    }
}

function filterCountriesGrid() {
    const input = document.getElementById('countrySearch').value.toLowerCase();
    const items = document.querySelectorAll('.country-item');

    items.forEach(item => {
        const name = item.getAttribute('data-name');
        item.style.display = name.includes(input) ? 'flex' : 'none';
    });
}

async function saveCountries() {

    const countries = [];

    document.querySelectorAll('.country-checkbox:checked').forEach(el => {
        countries.push(el.value);
    });

    const defaultCountry = document.querySelector('input[name="default_country"]:checked')?.value || '';

    const res = await apiCall('handlers/settings.php', {
        action: 'save_countries',
        countries: countries,
        default_country: defaultCountry
    });

    if (res.success) {
        showToast('Countries updated!', 'success');
    } else {
        showToast(res.message || 'Error', 'error');
    }
}
</script>

