<?php
session_start();
error_reporting(0);
include('config.php');
require_once('auth_guard.php');

if (empty($_SESSION['csrf'])) { $_SESSION['csrf'] = bin2hex(random_bytes(16)); }
$CSRF = $_SESSION['csrf'];

function bad($msg, $code = 400) { http_response_code($code); echo $msg; exit; }

/* ===========================
   CREATE
=========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    if (!hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) bad('Invalid session', 403);

    $name    = trim($_POST['name'] ?? '');
    $email   = trim($_POST['email'] ?? '');        // allowed at CREATE time
    $number  = trim($_POST['number'] ?? '');
    $country = trim($_POST['country'] ?? '');
    $city    = trim($_POST['city'] ?? '');
    $state   = trim($_POST['state'] ?? '');
    $zipcode = trim($_POST['zipcode'] ?? '');
    $status  = (int)($_POST['status'] ?? 0);
    $ib_ref_code = trim($_POST['ib_ref_code'] ?? 'noCode');
    $noClients   = (int)($_POST['noClients'] ?? 0);
    $address     = trim($_POST['address'] ?? '');
    $company     = trim($_POST['company_name'] ?? 'Aalfa Fx Trade');
    $website     = trim($_POST['website'] ?? 'Aalfa Fx Trade');

    if ($email !== '' && !filter_var($email, FILTER_VALIDATE_EMAIL)) bad('Invalid email');

    $uid = bin2hex(random_bytes(8));
    $username = ($email !== '' ? $email : $uid);

    $q = "INSERT INTO ib1
        (uid, name, email, number, username, date, country, noClients, password, status, website, company_name,
         dob, profile_pic, accountCurrencyBase, address, email_confirmed, emailVerDate, emailToken, phoneVer,
         phoneVerToken, pwdResetToken, state, zipcode, city, ib_ref_code, kyc_type, kyc_frontside, front_image,
         kyc_backside, back_image, registered_date_js, Admin_Remark, Admin_Remark_Date, kyc_status, bank_detail,
         account_holder_name, bank_name, bank_account_no, IFSC_Code, swift_code, bank_status)
        VALUES
        (:uid, :name, :email, :number, :username, NOW(), :country, :noClients, NULL, :status, :website, :company_name,
         NULL, NULL, 'USD', :address, 0, NULL, NULL, 0,
         NULL, NULL, :state, :zipcode, :city, :ib_ref_code, NULL, NULL, NULL,
         NULL, NULL, NULL, NULL, NULL, 0, NULL,
         NULL, NULL, NULL, NULL, NULL, NULL)";
    $stmt = $conn->prepare($q);
    $stmt->execute([
        ':uid'=>$uid, ':name'=>$name, ':email'=>$email, ':number'=>$number, ':username'=>$username,
        ':country'=>$country, ':noClients'=>$noClients, ':status'=>$status,
        ':website'=>($website!==''?$website:'Aalfa Fx Trade'),
        ':company_name'=>($company!==''?$company:'Aalfa Fx Trade'),
        ':address'=>$address, ':state'=>$state, ':zipcode'=>$zipcode, ':city'=>$city,
        ':ib_ref_code'=>($ib_ref_code!==''?$ib_ref_code:'noCode'),
    ]);

    // Propagate referral code to aspnetusers.referalId if a matching email exists (only that field).
    if ($email !== '' && $ib_ref_code !== '') {
        $u = $conn->prepare("UPDATE aspnetusers SET referalId = :code WHERE email = :email LIMIT 1");
        $u->execute([':code'=>$ib_ref_code, ':email'=>$email]);
    }

    header("Location: ib_users.php"); exit;
}

/* ===========================
   UPDATE
   - Email is NEVER updated here. We read the existing email from DB and ignore any posted email.
   - If ib_ref_code changes (and is non-empty), mirror to aspnetusers.referalId for that email.
=========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'update') {
    if (!hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) bad('Invalid session', 403);

    $id = (int)($_POST['id'] ?? 0); if ($id<=0) bad('Invalid ID');

    // Load current record to fetch the immutable email and old ib_ref_code
    $r = $conn->prepare("SELECT email, ib_ref_code FROM ib1 WHERE indexId = :id LIMIT 1");
    $r->execute([':id'=>$id]);
    $row = $r->fetch(PDO::FETCH_ASSOC);
    if (!$row) bad('Record not found', 404);

    $lockedEmail = trim((string)$row['email']);         // immutable
    $old_ib_code = trim((string)$row['ib_ref_code']);

    // Collect updatable fields (NO email here)
    $name    = trim($_POST['name'] ?? '');
    $number  = trim($_POST['number'] ?? '');
    $country = trim($_POST['country'] ?? '');
    $city    = trim($_POST['city'] ?? '');
    $state   = trim($_POST['state'] ?? '');
    $zipcode = trim($_POST['zipcode'] ?? '');
    $status  = (int)($_POST['status'] ?? 0);
    $ib_ref_code = trim($_POST['ib_ref_code'] ?? 'noCode');
    $noClients   = (int)($_POST['noClients'] ?? 0);
    $address     = trim($_POST['address'] ?? '');
    $company     = trim($_POST['company_name'] ?? 'Aalfa Fx Trade');
    $website     = trim($_POST['website'] ?? 'Aalfa Fx Trade');

    // Server-side safety: if client tried to post a different email, ignore it entirely.
    // (We don't even read $_POST['email'] here.)

    // Update IB row (excluding email)
    $q = "UPDATE ib1 SET
            name=:name, number=:number, country=:country,
            city=:city, state=:state, zipcode=:zipcode,
            status=:status, ib_ref_code=:code, noClients=:noClients,
            address=:address, company_name=:company_name, website=:website
          WHERE indexId=:id LIMIT 1";
    $stmt = $conn->prepare($q);
    $stmt->execute([
        ':name'=>$name, ':number'=>$number, ':country'=>$country,
        ':city'=>$city, ':state'=>$state, ':zipcode'=>$zipcode, ':status'=>$status,
        ':code'=>($ib_ref_code!==''?$ib_ref_code:'noCode'), ':noClients'=>$noClients,
        ':address'=>$address, ':company_name'=>($company!==''?$company:'Aalfa Fx Trade'),
        ':website'=>($website!==''?$website:'Aalfa Fx Trade'), ':id'=>$id
    ]);

    // If ib_ref_code changed and we have an email to match, mirror to aspnetusers.referalId
    $changed = ($ib_ref_code !== '' && $ib_ref_code !== $old_ib_code);
    if ($changed && $lockedEmail !== '') {
        $u = $conn->prepare("UPDATE aspnetusers SET referalId = :code WHERE email = :email LIMIT 1");
        $u->execute([':code'=>$ib_ref_code, ':email'=>$lockedEmail]);
        // We DO NOT touch email or any other column in aspnetusers.
    }

    header("Location: ib_users.php"); exit;
}

/* ===========================
   TOGGLE STATUS (Activate/Deactivate)
=========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'toggle') {
    if (!hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) bad('Invalid session', 403);

    $id  = (int)($_POST['id'] ?? 0);
    $to  = (int)($_POST['to'] ?? 0); // 1 = activate, 0 = deactivate
    if ($id <= 0 || ($to !== 0 && $to !== 1)) bad('Invalid input');

    $stmt = $conn->prepare("UPDATE ib1 SET status=:s WHERE indexId=:id LIMIT 1");
    $stmt->execute([':s'=>$to, ':id'=>$id]);
    header("Location: ib_users.php"); exit;
}

/* ===========================
   DELETE
=========================== */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'delete') {
    if (!hash_equals($_SESSION['csrf'], $_POST['csrf'] ?? '')) bad('Invalid session', 403);
    $id = (int)($_POST['id'] ?? 0); if ($id<=0) bad('Invalid ID');

    $conn->prepare("DELETE FROM ib1 WHERE indexId=:id LIMIT 1")->execute([':id'=>$id]);
    header("Location: ib_users.php"); exit;
}

/* ===========================
   READ
=========================== */
$rows = $conn->query("SELECT indexId, uid, name, email, number, country, city, state, zipcode, status, ib_ref_code, noClients, address, company_name, website, reg_date FROM ib1 ORDER BY indexId DESC")->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>IB Users</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
<style>
/* ---- Page polish ---- */
body { background: #f7f8fb; }
.table-wrap{overflow:auto}
.card { border: 1px solid #e9edf3; }
.table thead th { font-weight: 600; letter-spacing: .2px; }
.badge-status{font-size:.75rem}

/* ---- Premium Modals ---- */
.modal-dialog { max-width: 920px; margin-top:40px;}
.modal-dialog-centered { display: flex; align-items: center; min-height: calc(100% - 1rem); }
.modal-content {
  border: 1px solid #e9edf3;
  border-radius: 16px;
  box-shadow: 0 14px 40px rgba(16,24,40,.18);
  overflow: hidden;
}
.modal-header {
  padding: 16px 20px;
  border-bottom: 1px solid #eef2f6;
  background: linear-gradient(135deg, #f8fafc 0%, #eef5ff 100%);
}
.modal-title { font-size: 1.1rem; font-weight: 700; color:#0f172a; display:flex; align-items:center; gap:.5rem; }
.modal-body { padding: 18px 20px; }
.modal-footer { padding: 12px 20px; border-top: 1px solid #eef2f6; }

/* Section headers inside modals */
.section-title {
  font-size: .9rem; font-weight: 700; color:#334155; letter-spacing:.2px;
  margin: 2px 0 10px; display:flex; align-items:center; gap:.5rem;
}
.section-title i { color:#2563eb; }

/* View modal table */
#viewGrid {
  display:grid; grid-template-columns: 1fr 1fr; gap:10px 18px;
}
.kv { display:flex; gap:10px; }
.kv .k { min-width:160px; font-weight:600; color:#475467; background:#f9fafb; border:1px solid #eef2f6; border-radius:10px; padding:10px 12px; }
.kv .v { flex:1; color:#101828; background:white; border:1px solid #eef2f6; border-radius:10px; padding:10px 12px; position:relative; }

/* Pills & chips */
.pill {
  display:inline-flex; align-items:center; gap:.35rem;
  padding:.25rem .55rem; border-radius:999px; font-size:.78rem;
  border:1px solid #e5e7eb; background:#f9fafb; color:#334155;
}
.pill i { font-size:.9rem; }

/* Icon buttons inside value cells */
.v .btn-copy {
  position:absolute; right:8px; top:8px; border:none;
  background:#eef2f6; color:#334155; border-radius:8px; padding:4px 7px; font-size:.8rem;
}
.v .btn-copy:hover { background:#e2e8f0; }

/* Edit modal forms */
.divider { height:1px; background:#eef2f6; margin:10px 0 14px; }
.form-floating>.form-control, .form-floating>.form-select { border-radius:10px; }
.input-group-text { background:#f8fafc; border-radius:10px 0 0 10px; }

/* Buttons */
.btn-icon { display:inline-flex; align-items:center; gap:.45rem; }

/* lock hint */
.lock-hint { font-size: .8rem; color:#475569; }
</style>
</head>
<body class="bg-gray-100">
<?php include "header.php"; ?>

<!-- Page shell leaves space for fixed sidebar on md+ -->
<div class="min-h-screen md:pl-64">
  <?php include "side_bar.php"; ?>
   <main class="px-4 sm:px-6 py-6">
<div class="container py-4">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h1 class="h4 m-0">IB Users</h1>
    <button class="btn btn-primary btn-icon" data-bs-toggle="modal" data-bs-target="#modalAdd">
      <i class="bi bi-plus-lg"></i> Add New
    </button>
  </div>

  <div class="table-wrap card shadow-sm">
    <div class="card-body p-0">
      <table class="table table-striped table-hover align-middle m-0">
        <thead class="table-light">
          <tr>
            <th>Name</th><th>Email</th><th>Phone</th>
            <th>Status</th><th style="width:340px;">Actions</th>
          </tr>
        </thead>
        <tbody>
        <?php foreach($rows as $r): ?>
          <tr data-row='<?= json_encode($r, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_AMP|JSON_HEX_QUOT) ?>'>
            <td><?= htmlspecialchars($r['name'] ?? '') ?></td>
            <td><?= htmlspecialchars($r['email'] ?? '') ?></td>
            <td><?= htmlspecialchars($r['number'] ?? '') ?></td>
            <td>
              <?php if ((int)$r['status']===1): ?>
                <span class="badge text-bg-success badge-status"><i class="bi bi-check2-circle me-1"></i>Active</span>
              <?php else: ?>
                <span class="badge text-bg-secondary badge-status"><i class="bi bi-dash-circle me-1"></i>Inactive</span>
              <?php endif; ?>
            </td>
            <td class="d-flex flex-wrap gap-1">
              <button class="btn btn-sm btn-outline-info btn-icon btn-view" data-bs-toggle="modal" data-bs-target="#modalView">
                <i class="bi bi-eye"></i> View
              </button>
              <button class="btn btn-sm btn-warning btn-icon text-white btn-edit" data-bs-toggle="modal" data-bs-target="#modalEdit">
                <i class="bi bi-pencil-square"></i> Edit
              </button>

              <!-- Activate / Deactivate -->
              <?php if ((int)$r['status']===1): ?>
                <form method="post" class="d-inline" onsubmit="return confirm('Deactivate this IB user?');">
                  <input type="hidden" name="csrf" value="<?= htmlspecialchars($CSRF) ?>">
                  <input type="hidden" name="action" value="toggle">
                  <input type="hidden" name="id" value="<?= (int)$r['indexId'] ?>">
                  <input type="hidden" name="to" value="0">
                  <button class="btn btn-sm btn-outline-danger btn-icon" type="submit">
                    <i class="bi bi-slash-circle"></i> Deactivate
                  </button>
                </form>
              <?php else: ?>
                <form method="post" class="d-inline" onsubmit="return confirm('Activate this IB user?');">
                  <input type="hidden" name="csrf" value="<?= htmlspecialchars($CSRF) ?>">
                  <input type="hidden" name="action" value="toggle">
                  <input type="hidden" name="id" value="<?= (int)$r['indexId'] ?>">
                  <input type="hidden" name="to" value="1">
                  <button class="btn btn-sm btn-outline-success btn-icon" type="submit">
                    <i class="bi bi-check2-circle"></i> Activate
                  </button>
                </form>
              <?php endif; ?>

              <!-- (Optional) Delete button
              <form method="post" class="d-inline" onsubmit="return confirm('Delete this IB user? This cannot be undone.');">
                <input type="hidden" name="csrf" value="<?= htmlspecialchars($CSRF) ?>">
                <input type="hidden" name="action" value="delete">
                <input type="hidden" name="id" value="<?= (int)$r['indexId'] ?>">
                <button class="btn btn-sm btn-outline-secondary btn-icon" type="submit">
                  <i class="bi bi-trash3"></i> Delete
                </button>
              </form>
              -->
            </td>
          </tr>
        <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div></main>

<!-- ============ View Modal ============ -->
<div class="modal fade" id="modalView" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-lg"><div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title"><i class="bi bi-person-vcard"></i> IB User Overview</h5>
      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
    </div>
    <div class="modal-body">
      <div class="section-title"><i class="bi bi-info-circle"></i> Profile</div>
      <div id="viewTopPills" class="mb-2"></div>
      <div id="viewGrid"></div>

      <div class="divider"></div>
      <div class="section-title"><i class="bi bi-geo-alt"></i> Location</div>
      <div id="viewGridLoc" style="display:grid; grid-template-columns: 1fr 1fr; gap:10px 18px;"></div>
    </div>
    <div class="modal-footer">
      <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
    </div>
  </div></div>
</div>

<!-- ============ Add Modal ============ -->
<div class="modal fade" id="modalAdd" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-lg"><div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title"><i class="bi bi-plus-circle"></i> Add IB User</h5>
      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
    </div>
    <form method="post" class="modal-body needs-validation" novalidate>
      <input type="hidden" name="csrf" value="<?= htmlspecialchars($CSRF) ?>">
      <input type="hidden" name="action" value="create">

      <div class="section-title"><i class="bi bi-person"></i> Basic</div>
      <div class="row g-3">
        <div class="col-md-6 form-floating">
          <input class="form-control" id="a_name" name="name" placeholder="Name" required>
          <label for="a_name">Name</label>
          <div class="invalid-feedback">Please enter a name.</div>
        </div>
        <div class="col-md-6 form-floating">
          <input class="form-control" id="a_email" type="email" name="email" placeholder="Email">
          <label for="a_email">Email</label>
          <div class="invalid-feedback">Enter a valid email.</div>
        </div>
        <div class="col-md-6 form-floating">
          <input class="form-control" id="a_phone" name="number" placeholder="Phone">
          <label for="a_phone">Phone</label>
        </div>
        <div class="col-md-6">
          <label class="form-label">Status</label>
          <select class="form-select" name="status">
            <option value="1">Active</option>
            <option value="0" selected>Inactive</option>
          </select>
        </div>
      </div>

      <div class="divider"></div>
      <div class="section-title"><i class="bi bi-diagram-3"></i> Business</div>
      <div class="row g-3">
        <div class="col-md-4 form-floating">
          <input class="form-control" id="a_ib" name="ib_ref_code" placeholder="IB Ref Code">
          <label for="a_ib">IB Ref Code</label>
        </div>
        <div class="col-md-4 form-floating">
          <input class="form-control" id="a_clients" type="number" min="0" value="0" name="noClients" placeholder="No. Clients">
          <label for="a_clients">No. Clients</label>
        </div>
        <div class="col-md-4 form-floating">
          <input class="form-control" id="a_company" name="company_name" value="Aalfa Fx Trade" placeholder="Company Name">
          <label for="a_company">Company Name</label>
        </div>
        <div class="col-md-6 form-floating">
          <input class="form-control" id="a_website" name="website" value="Aalfa Fx Trade" placeholder="Website">
          <label for="a_website">Website</label>
        </div>
        <div class="col-md-6 form-floating">
          <input class="form-control" id="a_country" name="country" placeholder="Country">
          <label for="a_country">Country</label>
        </div>
      </div>

      <div class="divider"></div>
      <div class="section-title"><i class="bi bi-geo"></i> Address</div>
      <div class="row g-3">
        <div class="col-md-12 form-floating">
          <input class="form-control" id="a_addr" name="address" placeholder="Address">
          <label for="a_addr">Address</label>
        </div>
        <div class="col-md-4 form-floating">
          <input class="form-control" id="a_city" name="city" placeholder="City">
          <label for="a_city">City</label>
        </div>
        <div class="col-md-4 form-floating">
          <input class="form-control" id="a_state" name="state" placeholder="State">
          <label for="a_state">State</label>
        </div>
        <div class="col-md-4 form-floating">
          <input class="form-control" id="a_zip" name="zipcode" placeholder="Zipcode">
          <label for="a_zip">Zipcode</label>
        </div>
      </div>

      <div class="modal-footer">
        <button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Cancel</button>
        <button class="btn btn-primary btn-icon" type="submit"><i class="bi bi-check2-circle"></i> Create</button>
      </div>
    </form>
  </div></div>
</div>

<!-- ============ Edit Modal ============ -->
<div class="modal fade" id="modalEdit" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-lg"><div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title"><i class="bi bi-pencil-square"></i> Edit IB User</h5>
      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
    </div>
    <form method="post" class="modal-body needs-validation" id="editForm" novalidate>
      <input type="hidden" name="csrf" value="<?= htmlspecialchars($CSRF) ?>">
      <input type="hidden" name="action" value="update">
      <input type="hidden" name="id" id="edit_id">

      <div class="section-title"><i class="bi bi-person"></i> Basic</div>
      <div class="row g-3">
        <div class="col-md-6 form-floating">
          <input class="form-control" name="name" id="edit_name" placeholder="Name" required>
          <label for="edit_name">Name</label>
          <div class="invalid-feedback">Please enter a name.</div>
        </div>

        <!-- EMAIL LOCKED: readonly and visually marked -->
        <div class="col-md-6">
          <div class="form-floating">
            <input class="form-control" type="email" id="edit_email" placeholder="Email" readonly>
            <label for="edit_email">Email (locked)</label>
          </div>
          <div class="lock-hint mt-1">
            <i class="bi bi-lock"></i> Email can’t be changed.
          </div>
        </div>

        <div class="col-md-6 form-floating">
          <input class="form-control" name="number" id="edit_number" placeholder="Phone">
          <label for="edit_number">Phone</label>
        </div>
        <div class="col-md-6">
          <label class="form-label">Status</label>
          <select class="form-select" name="status" id="edit_status">
            <option value="1">Active</option>
            <option value="0">Inactive</option>
          </select>
        </div>
      </div>

      <div class="divider"></div>
      <div class="section-title"><i class="bi bi-diagram-3"></i> Business</div>
      <div class="row g-3">
        <div class="col-md-4 form-floating">
          <input class="form-control" name="ib_ref_code" id="edit_ib_ref_code" placeholder="IB Ref Code">
          <label for="edit_ib_ref_code">IB Ref Code</label>
        </div>
        <div class="col-md-4 form-floating">
          <input class="form-control" type="number" name="noClients" id="edit_noClients" min="0" placeholder="No. Clients">
          <label for="edit_noClients">No. Clients</label>
        </div>
        <div class="col-md-4 form-floating">
          <input class="form-control" name="company_name" id="edit_company_name" placeholder="Company Name">
          <label for="edit_company_name">Company Name</label>
        </div>
        <div class="col-md-6 form-floating">
          <input class="form-control" name="website" id="edit_website" placeholder="Website">
          <label for="edit_website">Website</label>
        </div>
        <div class="col-md-6 form-floating">
          <input class="form-control" name="country" id="edit_country" placeholder="Country">
          <label for="edit_country">Country</label>
        </div>
      </div>

      <div class="divider"></div>
      <div class="section-title"><i class="bi bi-geo"></i> Address</div>
      <div class="row g-3">
        <div class="col-md-12 form-floating">
          <input class="form-control" name="address" id="edit_address" placeholder="Address">
          <label for="edit_address">Address</label>
        </div>
        <div class="col-md-4 form-floating">
          <input class="form-control" name="city" id="edit_city" placeholder="City">
          <label for="edit_city">City</label>
        </div>
       

        <div class="col-md-4 form-floating">
          <input class="form-control" id="a_state" name="state" placeholder="State">
          <label for="a_state">State</label>
        </div>
        <div class="col-md-4 form-floating">
          <input class="form-control" id="a_zip" name="zipcode" placeholder="Zipcode">
          <label for="a_zip">Zipcode</label>
        </div>
      </div>

      <div class="modal-footer">
        <button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Cancel</button>
        <button class="btn btn-primary btn-icon" type="submit"><i class="bi bi-check2-circle"></i> Create</button>
      </div>
    </form>
  </div></div>
</div>

<!-- ============ Edit Modal ============ -->
<div class="modal fade" id="modalEdit" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-lg"><div class="modal-content">
    <div class="modal-header">
      <h5 class="modal-title"><i class="bi bi-pencil-square"></i> Edit IB User</h5>
      <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
    </div>
    <form method="post" class="modal-body needs-validation" id="editForm" novalidate>
      <input type="hidden" name="csrf" value="<?= htmlspecialchars($CSRF) ?>">
      <input type="hidden" name="action" value="update">
      <input type="hidden" name="id" id="edit_id">

      <div class="section-title"><i class="bi bi-person"></i> Basic</div>
      <div class="row g-3">
        <div class="col-md-6 form-floating">
          <input class="form-control" name="name" id="edit_name" placeholder="Name" required>
          <label for="edit_name">Name</label>
          <div class="invalid-feedback">Please enter a name.</div>
        </div>
        <div class="col-md-6 form-floating">
          <input class="form-control" type="email" name="email" id="edit_email" placeholder="Email">
          <label for="edit_email">Email</label>
          <div class="invalid-feedback">Enter a valid email.</div>
        </div>
        <div class="col-md-6 form-floating">
          <input class="form-control" name="number" id="edit_number" placeholder="Phone">
          <label for="edit_number">Phone</label>
        </div>
        <div class="col-md-6">
          <label class="form-label">Status</label>
          <select class="form-select" name="status" id="edit_status">
            <option value="1">Active</option>
            <option value="0">Inactive</option>
          </select>
        </div>
      </div>

      <div class="divider"></div>
      <div class="section-title"><i class="bi bi-diagram-3"></i> Business</div>
      <div class="row g-3">
        <div class="col-md-4 form-floating">
          <input class="form-control" name="ib_ref_code" id="edit_ib_ref_code" placeholder="IB Ref Code">
          <label for="edit_ib_ref_code">IB Ref Code</label>
        </div>
        <div class="col-md-4 form-floating">
          <input class="form-control" type="number" name="noClients" id="edit_noClients" min="0" placeholder="No. Clients">
          <label for="edit_noClients">No. Clients</label>
        </div>
        <div class="col-md-4 form-floating">
          <input class="form-control" name="company_name" id="edit_company_name" placeholder="Company Name">
          <label for="edit_company_name">Company Name</label>
        </div>
        <div class="col-md-6 form-floating">
          <input class="form-control" name="website" id="edit_website" placeholder="Website">
          <label for="edit_website">Website</label>
        </div>
        <div class="col-md-6 form-floating">
          <input class="form-control" name="country" id="edit_country" placeholder="Country">
          <label for="edit_country">Country</label>
        </div>
      </div>

      <div class="divider"></div>
      <div class="section-title"><i class="bi bi-geo"></i> Address</div>
      <div class="row g-3">
        <div class="col-md-12 form-floating">
          <input class="form-control" name="address" id="edit_address" placeholder="Address">
          <label for="edit_address">Address</label>
        </div>
        <div class="col-md-4 form-floating">
          <input class="form-control" name="city" id="edit_city" placeholder="City">
          <label for="edit_city">City</label>
        </div>
        <div class="col-md-4 form-floating">
          <input class="form-control" name="state" id="edit_state" placeholder="State">
          <label for="edit_state">State</label>
        </div>
        <div class="col-md-4 form-floating">
          <input class="form-control" name="zipcode" id="edit_zipcode" placeholder="Zipcode">
          <label for="edit_zipcode">Zipcode</label>
        </div>
      </div>

      <div class="modal-footer">
        <button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Cancel</button>
        <button class="btn btn-primary btn-icon" type="submit"><i class="bi bi-save2"></i> Save</button>
      </div>
    </form>
  </div></div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Bootstrap client-side validation
(() => {
  'use strict';
  const forms = document.querySelectorAll('.needs-validation');
  Array.from(forms).forEach(form => {
    form.addEventListener('submit', e => {
      if (!form.checkValidity()) { e.preventDefault(); e.stopPropagation(); }
      form.classList.add('was-validated');
    }, false);
  });
})();

// Helpers
function pill(html){ const span=document.createElement('span'); span.className='pill'; span.innerHTML=html; return span; }
function kv(k,v,copyable=false){
  const wrap=document.createElement('div'); wrap.className='kv';
  const kk=document.createElement('div'); kk.className='k'; kk.textContent=k;
  const vv=document.createElement('div'); vv.className='v'; vv.textContent=(v??'');
  if(copyable){
    const b=document.createElement('button'); b.type='button'; b.className='btn-copy'; b.innerHTML='<i class="bi bi-clipboard"></i>';
    b.addEventListener('click',()=>{ navigator.clipboard.writeText(String(v??'')); b.innerHTML='<i class="bi bi-check2"></i>'; setTimeout(()=>b.innerHTML='<i class="bi bi-clipboard"></i>',1000);});
    vv.appendChild(b);
  }
  wrap.appendChild(kk); wrap.appendChild(vv);
  return wrap;
}

// Populate View modal
document.querySelectorAll('.btn-view').forEach(btn=>{
  btn.addEventListener('click', function(){
    const row = JSON.parse(this.closest('tr').dataset.row);

    // Pills
    const pills = document.getElementById('viewTopPills');
    pills.innerHTML='';
    const statusPill = (parseInt(row.status,10)===1)
      ? pill('<i class="bi bi-check2-circle"></i> Active')
      : pill('<i class="bi bi-dash-circle"></i> Inactive');
    const regPill = pill('<i class="bi bi-calendar-event"></i> '+ (row.reg_date ?? ''));
    pills.append(statusPill, regPill);

    // Grid 1 (Profile/Business)
    const g = document.getElementById('viewGrid');
    g.innerHTML='';
    g.append(
      kv('Index ID', row.indexId, true),
      kv('UID', row.uid, true),
      kv('Name', row.name),
      kv('Email', row.email, true),
      kv('Phone', row.number),
      kv('IB Ref Code', row.ib_ref_code, true),
      kv('Company', row.company_name),
      kv('Website', row.website),
      kv('Clients', row.noClients),
      kv('Country', row.country)
    );

    // Grid 2 (Location)
    const gl = document.getElementById('viewGridLoc');
    gl.innerHTML='';
    gl.append(
      kv('Address', row.address),
      kv('City', row.city),
      kv('State', row.state),
      kv('Zipcode', row.zipcode)
    );
  });
});

// Populate Edit modal
document.querySelectorAll('.btn-edit').forEach(btn=>{
  btn.addEventListener('click', function(){
    const row = JSON.parse(this.closest('tr').dataset.row);
    document.getElementById('edit_id').value = row.indexId;
    document.getElementById('edit_name').value = row.name ?? '';
    document.getElementById('edit_email').value = row.email ?? '';
    document.getElementById('edit_number').value = row.number ?? '';
    document.getElementById('edit_country').value = row.country ?? '';
    document.getElementById('edit_city').value = row.city ?? '';
    document.getElementById('edit_state').value = row.state ?? '';
    document.getElementById('edit_zipcode').value = row.zipcode ?? '';
    document.getElementById('edit_status').value = (row.status ?? 0);
    document.getElementById('edit_ib_ref_code').value = row.ib_ref_code ?? 'noCode';
    document.getElementById('edit_noClients').value = row.noClients ?? 0;
    document.getElementById('edit_address').value = row.address ?? '';
    document.getElementById('edit_company_name').value = row.company_name ?? 'Aalfa Fx Trade';
    document.getElementById('edit_website').value = row.website ?? 'Aalfa Fx Trade';
  });
});
</script>
</body>
</html>
