<?php
@ini_set('display_errors', '1');
@error_reporting(E_ALL);

require_once __DIR__ . '/../includes/auth.php';
require_login(); // provides $con (mysqli)
global $con;

ob_start();
?>
<link rel="stylesheet" href="/adminconsole/assets/ui.css">
<?php

/* =========================================================
  Update User (Operations)
  - Search ONLY by Mobile (no UserID in panel)
  - After search: ask choice (Edit Name OR Disable Wrong Signup)
  - Supports profile_type_id: 1 Recruiter, 2 Candidate, 3 Promoter
  - Logs every action in jos_admin_user_replace_log
  - No horizontal “huge JSON” – wrap Old/New nicely
  - No csrf_token redeclare (guards used)
========================================================= */

/* ---------- safe CSRF (do NOT redeclare if already exists) ---------- */
if (!function_exists('csrf_token')) {
  function csrf_token(): string
  {
    if (session_status() !== PHP_SESSION_ACTIVE) @session_start();
    if (empty($_SESSION['_csrf'])) $_SESSION['_csrf'] = bin2hex(random_bytes(16));
    return $_SESSION['_csrf'];
  }
}
if (!function_exists('verify_csrf')) {
  function verify_csrf($token): bool
  {
    if (session_status() !== PHP_SESSION_ACTIVE) @session_start();
    return !empty($token) && !empty($_SESSION['_csrf']) && hash_equals($_SESSION['_csrf'], (string)$token);
  }
}

/* ---------- helpers ---------- */
function h($s)
{
  return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8');
}
function clean($v)
{
  return trim((string)$v);
}
function log_label(string $key): string
{
  $label = preg_replace('/_\d+$/', '', $key);
  $label = str_replace('_', ' ', (string)$label);
  $label = ucwords($label);
  return preg_replace('/\bId\b/', 'ID', $label);
}
function log_value($value): string
{
  if (is_array($value)) {
    $flat = [];
    foreach ($value as $v) {
      if (is_array($v)) $flat[] = json_encode($v, JSON_UNESCAPED_UNICODE);
      elseif ($v === null || $v === '') $flat[] = '—';
      else $flat[] = (string)$v;
    }
    return $flat ? implode(', ', $flat) : '—';
  }
  if ($value === null || $value === '') return '—';
  if (is_bool($value)) return $value ? 'Yes' : 'No';
  return (string)$value;
}
function render_log_details(array $data): void
{
  if (!$data) {
    echo '<div class="log-empty muted">No details available.</div>';
    return;
  }
  foreach ($data as $key => $value) {
    echo '<div class="log-field">';
    echo '<div class="log-label">' . h(log_label((string)$key)) . '</div>';
    echo '<div class="log-value">' . h(log_value($value)) . '</div>';
    echo '</div>';
  }
}

function table_exists(mysqli $con, string $name): bool
{
  $name = mysqli_real_escape_string($con, $name);
  $rs = mysqli_query($con, "SHOW TABLES LIKE '$name'");
  return ($rs && mysqli_num_rows($rs) > 0);
}
function col_exists(mysqli $con, string $table, string $col): bool
{
  $t = mysqli_real_escape_string($con, $table);
  $c = mysqli_real_escape_string($con, $col);
  $r = mysqli_query($con, "SHOW COLUMNS FROM `$t` LIKE '$c'");
  return ($r && mysqli_num_rows($r) > 0);
}
function index_exists(mysqli $con, string $table, string $key): bool
{
  $t = mysqli_real_escape_string($con, $table);
  $k = mysqli_real_escape_string($con, $key);
  $r = mysqli_query($con, "SHOW INDEX FROM `$t` WHERE Key_name='$k'");
  return ($r && mysqli_num_rows($r) > 0);
}
function keep_params(array $changes = [])
{
  $qs = $_GET;
  foreach ($changes as $k => $v) {
    if ($v === null) unset($qs[$k]);
    else $qs[$k] = $v;
  }
  $q = http_build_query($qs);
  return $q ? ('?' . $q) : ($_SERVER['SCRIPT_NAME'] ?? 'user_update.php');
}

/* ---------- tables ---------- */
$T_USERS      = 'jos_app_users';
$T_ADMIN      = 'jos_admin_users';
$T_REC        = 'jos_app_recruiter_profile';
$T_CAN        = 'jos_app_candidate_profile';
$T_PRO        = 'jos_app_promoter_profile';
$T_LOG        = 'jos_admin_user_replace_log';

/* ---------- ensure log schema (no duplicate index errors) ---------- */
function ensure_log_schema(mysqli $con, string $T_LOG)
{
  if (!table_exists($con, $T_LOG)) {
    mysqli_query($con, "CREATE TABLE `$T_LOG` (
      `id` INT NOT NULL AUTO_INCREMENT,
      `admin_user_id` INT NOT NULL DEFAULT 0,
      `user_id` INT NOT NULL DEFAULT 0,
      `action_type` VARCHAR(80) NOT NULL DEFAULT '',
      `old_data` MEDIUMTEXT NULL,
      `new_data` MEDIUMTEXT NULL,
      `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
  }

  // make sure important columns exist
  if (!col_exists($con, $T_LOG, 'created_at')) {
    mysqli_query($con, "ALTER TABLE `$T_LOG` ADD `created_at` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP");
  }
  if (!col_exists($con, $T_LOG, 'action_type')) {
    mysqli_query($con, "ALTER TABLE `$T_LOG` ADD `action_type` VARCHAR(80) NOT NULL DEFAULT ''");
  }
  if (!col_exists($con, $T_LOG, 'admin_user_id')) {
    mysqli_query($con, "ALTER TABLE `$T_LOG` ADD `admin_user_id` INT NOT NULL DEFAULT 0");
  }
  if (!col_exists($con, $T_LOG, 'user_id')) {
    mysqli_query($con, "ALTER TABLE `$T_LOG` ADD `user_id` INT NOT NULL DEFAULT 0");
  }
  if (!col_exists($con, $T_LOG, 'old_data')) {
    mysqli_query($con, "ALTER TABLE `$T_LOG` ADD `old_data` MEDIUMTEXT NULL");
  }
  if (!col_exists($con, $T_LOG, 'new_data')) {
    mysqli_query($con, "ALTER TABLE `$T_LOG` ADD `new_data` MEDIUMTEXT NULL");
  }

  // indexes (avoid duplicate key name error)
  if (!index_exists($con, $T_LOG, 'idx_user_id')) {
    @mysqli_query($con, "ALTER TABLE `$T_LOG` ADD INDEX `idx_user_id` (`user_id`)");
  }
  if (!index_exists($con, $T_LOG, 'idx_admin_user_id')) {
    @mysqli_query($con, "ALTER TABLE `$T_LOG` ADD INDEX `idx_admin_user_id` (`admin_user_id`)");
  }
  if (!index_exists($con, $T_LOG, 'idx_created_at')) {
    @mysqli_query($con, "ALTER TABLE `$T_LOG` ADD INDEX `idx_created_at` (`created_at`)");
  }
}
ensure_log_schema($con, $T_LOG);

/* ---------- admin info ---------- */
$admin_id = 0;
$admin_name = '';
if (!empty($_SESSION['admin_user']) && is_array($_SESSION['admin_user'])) {
  $admin_id = (int)($_SESSION['admin_user']['id'] ?? 0);
  $admin_name = (string)($_SESSION['admin_user']['name'] ?? '');
}
if ($admin_id <= 0) {
  // fallback: best-effort find by session mobile/email if present
  $admin_id = (int)($_SESSION['admin_id'] ?? 0);
}

/* ---------- flash ---------- */
$ok = (string)($_GET['ok'] ?? '');
$err = '';

/* =========================================================
   Core: fetch user by mobile
========================================================= */
$mobile = preg_replace('/\D+/', '', (string)($_GET['mobile'] ?? ''));
$user = null;

function fetch_user_by_mobile(mysqli $con, string $T_USERS, string $mobile)
{
  if ($mobile === '') return null;
  $sql = "SELECT id, profile_type_id, profile_id, mobile_no
          FROM `$T_USERS`
          WHERE mobile_no = ?
          LIMIT 1";
  $st = $con->prepare($sql);
  $st->bind_param('s', $mobile);
  $st->execute();
  $r = $st->get_result()->fetch_assoc();
  $st->close();
  return $r ?: null;
}

function fetch_profile_name(mysqli $con, array $u): array
{
  // returns: [label, name_value, table, name_col, mobile_col]
  $ptype = (int)($u['profile_type_id'] ?? 0);
  $pid   = (int)($u['profile_id'] ?? 0);

  if ($ptype === 1) { // recruiter
    $sql = "SELECT id, organization_name AS nm, mobile_no FROM jos_app_recruiter_profile WHERE id=? LIMIT 1";
    $st = $con->prepare($sql);
    $st->bind_param('i', $pid);
    $st->execute();
    $row = $st->get_result()->fetch_assoc();
    $st->close();
    return ['Recruiter', ($row['nm'] ?? ''), 'jos_app_recruiter_profile', 'organization_name', 'mobile_no'];
  }
  if ($ptype === 2) { // candidate
    $sql = "SELECT id, candidate_name AS nm, mobile_no FROM jos_app_candidate_profile WHERE id=? LIMIT 1";
    $st = $con->prepare($sql);
    $st->bind_param('i', $pid);
    $st->execute();
    $row = $st->get_result()->fetch_assoc();
    $st->close();
    return ['Candidate', ($row['nm'] ?? ''), 'jos_app_candidate_profile', 'candidate_name', 'mobile_no'];
  }
  if ($ptype === 3) { // promoter (as per signup: name)
    $sql = "SELECT id, name AS nm, mobile_no FROM jos_app_promoter_profile WHERE id=? LIMIT 1";
    $st = $con->prepare($sql);
    $st->bind_param('i', $pid);
    $st->execute();
    $row = $st->get_result()->fetch_assoc();
    $st->close();
    return ['Promoter', ($row['nm'] ?? ''), 'jos_app_promoter_profile', 'name', 'mobile_no'];
  }
  return ['User', '', '', '', ''];
}

/* =========================================================
   POST actions
   - edit_name
   - disable_replace_55series
========================================================= */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  if (!verify_csrf($_POST['csrf'] ?? null)) {
    $err = "Invalid request.";
  } else {
    $post_mobile = preg_replace('/\D+/', '', (string)($_POST['mobile'] ?? ''));
    $user = fetch_user_by_mobile($con, $T_USERS, $post_mobile);
    if (!$user) {
      $err = "No user found for this mobile.";
    } else {
      $profileMeta = fetch_profile_name($con, $user);
      [$ptypeLabel, $profileName, $profileTable, $nameCol, $mobileCol] = $profileMeta;

      // old snapshot
      $old = [
        'user_id' => (int)$user['id'],
        'old_mobile' => (string)$user['mobile_no'],
        'profile_type_id' => (int)$user['profile_type_id'],
        'profile_id' => (int)$user['profile_id'],
        'profile_name' => (string)$profileName,
      ];

      /* ---------- Edit Name ---------- */
      if (isset($_POST['do_edit_name'])) {
        $new_name = clean($_POST['new_name'] ?? '');
        if ($new_name === '') {
          $err = "Name is required.";
        } elseif (!$profileTable || !$nameCol) {
          $err = "Profile table not found for this user type.";
        } else {
          $pid = (int)$user['profile_id'];

          $st = $con->prepare("UPDATE `$profileTable` SET `$nameCol`=? WHERE id=?");
          $st->bind_param('si', $new_name, $pid);
          $okExec = $st->execute();
          $st->close();

          if ($okExec) {
            $new = $old;
            $new['profile_name'] = $new_name;

            $action = 'edit_name';
            $stL = $con->prepare("INSERT INTO `$T_LOG` (admin_user_id,user_id,action_type,old_data,new_data) VALUES (?,?,?,?,?)");
            $oldj = json_encode($old, JSON_UNESCAPED_UNICODE);
            $newj = json_encode($new, JSON_UNESCAPED_UNICODE);
            $uid  = (int)$user['id'];
            $stL->bind_param('iisss', $admin_id, $uid, $action, $oldj, $newj);
            $stL->execute();
            $stL->close();

            header('Location: ' . keep_params(['mobile' => $post_mobile, 'ok' => 'Name updated successfully', 'action' => null]));
            exit;
          } else {
            $err = "Update failed.";
          }
        }
      }

      /* ---------- Disable wrong signup (55-series) ---------- */
      if (isset($_POST['do_disable'])) {
        // Your rule: use 55-series, identifiable; avoid real-number conflicts
        // Example: 55 + (user_id padded to 8 digits) => total 10 digits.
        $uid = (int)$user['id'];
        $dummy_mobile = '55' . str_pad((string)$uid, 8, '0', STR_PAD_LEFT); // 10 digits

        // update app user mobile
        $con->begin_transaction();
        try {
          // 1) update jos_app_users.mobile_no
          $stU = $con->prepare("UPDATE `$T_USERS` SET mobile_no=? WHERE id=?");
          $stU->bind_param('si', $dummy_mobile, $uid);
          if (!$stU->execute()) throw new Exception("users update failed");
          $stU->close();

          // optional hard-disable fields if they exist (safe)
          if (col_exists($con, $T_USERS, 'status_id')) {
            @mysqli_query($con, "UPDATE `$T_USERS` SET status_id=0 WHERE id=" . (int)$uid);
          }
          if (col_exists($con, $T_USERS, 'fcm_token')) {
            @mysqli_query($con, "UPDATE `$T_USERS` SET fcm_token='' WHERE id=" . (int)$uid);
          }
          if (col_exists($con, $T_USERS, 'latitude')) {
            @mysqli_query($con, "UPDATE `$T_USERS` SET latitude='' WHERE id=" . (int)$uid);
          }
          if (col_exists($con, $T_USERS, 'longitude')) {
            @mysqli_query($con, "UPDATE `$T_USERS` SET longitude='' WHERE id=" . (int)$uid);
          }

          // 2) update profile mobile + set name to dummy
          $pid = (int)$user['profile_id'];
          if ($profileTable && $mobileCol) {
            // update mobile
            $stP = $con->prepare("UPDATE `$profileTable` SET `$mobileCol`=? WHERE id=?");
            $stP->bind_param('si', $dummy_mobile, $pid);
            if (!$stP->execute()) throw new Exception("profile mobile update failed");
            $stP->close();

            // set name field to dummy if present
            if ($nameCol) {
              $dummy_name = 'dummy';
              $stN = $con->prepare("UPDATE `$profileTable` SET `$nameCol`=? WHERE id=?");
              $stN->bind_param('si', $dummy_name, $pid);
              $stN->execute();
              $stN->close();
            }
          }

          // 3) log
          $new = $old;
          $new['dummy_mobile'] = $dummy_mobile;
          $new['cleared'] = [];
          foreach (['fcm_token', 'latitude', 'longitude'] as $c) {
            if (col_exists($con, $T_USERS, $c)) $new['cleared'][] = $c;
          }
          $new['status_id_set_0'] = col_exists($con, $T_USERS, 'status_id') ? 1 : 0;
          $new['profile_name_set_to'] = $nameCol ? 'dummy' : null;

          $action = 'disable_replace_55series';
          $stL = $con->prepare("INSERT INTO `$T_LOG` (admin_user_id,user_id,action_type,old_data,new_data) VALUES (?,?,?,?,?)");
          $oldj = json_encode($old, JSON_UNESCAPED_UNICODE);
          $newj = json_encode($new, JSON_UNESCAPED_UNICODE);
          $stL->bind_param('iisss', $admin_id, $uid, $action, $oldj, $newj);
          $stL->execute();
          $stL->close();

          $con->commit();

          header('Location: ' . keep_params(['mobile' => $post_mobile, 'ok' => 'User disabled successfully (moved to 55-series)', 'action' => null]));
          exit;
        } catch (Exception $e) {
          $con->rollback();
          $err = "Disable failed: " . $e->getMessage();
        }
      }
    }
  }
}

/* =========================================================
   Load user (GET)
========================================================= */
if ($mobile !== '') {
  $user = fetch_user_by_mobile($con, $T_USERS, $mobile);
}

/* =========================================================
   Recent logs (latest 15)
========================================================= */
$logs = [];

/* --- pagination setup --- */
$page = max(1, (int)($_GET['page'] ?? 1));

/* limit filter */
$limit = $_GET['limit'] ?? '50';

$allowedLimits = [ '50', 'all'];

if (!in_array($limit, $allowedLimits, true)) {
  $limit = '50';
}

/* total count */
$totalRows = 0;

$countSql = "SELECT COUNT(*) AS total FROM `$T_LOG`";
$countRs = mysqli_query($con, $countSql);

if ($countRs) {
  $countRow = mysqli_fetch_assoc($countRs);
  $totalRows = (int)($countRow['total'] ?? 0);
}

/* build query */
if ($limit === 'all') {

  $totalPages = 1;
  $offset = 0;

  $logSql = "SELECT l.*, a.name AS admin_name
             FROM `$T_LOG` l
             LEFT JOIN `$T_ADMIN` a 
             ON a.id = l.admin_user_id
             ORDER BY l.id DESC";
} else {

  $limitInt = (int)$limit;
  $offset = ($page - 1) * $limitInt;

  $totalPages = (int)ceil($totalRows / $limitInt);

  $logSql = "SELECT l.*, a.name AS admin_name
             FROM `$T_LOG` l
             LEFT JOIN `$T_ADMIN` a 
             ON a.id = l.admin_user_id
             ORDER BY l.id DESC
             LIMIT $limitInt OFFSET $offset";
}

/* fetch logs */
$rs = mysqli_query($con, $logSql);

if ($rs) {
  while ($r = mysqli_fetch_assoc($rs)) {
    $logs[] = $r;
  }
}

/* =========================================================
   UI
========================================================= */
?>
<style>
  .user-actions {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
    justify-content: flex-end;
  }

  .user-card-top {
    display: flex;
    gap: 12px;
    align-items: flex-start;
    justify-content: space-between;
    flex-wrap: wrap;
  }

  .muted {
    color: #9ca3af;
  }

  hr.sep {
    border: 0;
    border-top: 1px solid rgba(255, 255, 255, .08);
    margin: 14px 0;
  }

  .change-details-modal .modal-content {
    border: 0;
    border-radius: 14px;
    overflow: hidden;
  }

  .change-details-modal .modal-header {
    border-bottom: 1px solid rgba(148, 163, 184, .22);
  }

  .change-details-card {
    border: 1px solid rgba(148, 163, 184, .28);
    border-radius: 12px;
    padding: 16px;
    margin-bottom: 14px;
    background: #fff;
  }

  .change-details-card.new-data {
    border-color: rgba(22, 163, 74, .25);
    background: #e7f2ff;
  }

  .change-details-card.old-data {
    background: #e7f2ff;
  }

  .change-details-title {
    margin: 0 0 12px;
    font-size: 15px;
    font-weight: 800;
    color: #111827;
  }

  .log-details-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
    gap: 12px;
  }

  .log-field {
    border: 1px solid rgba(148, 163, 184, .22);
    border-radius: 10px;
    padding: 10px 12px;
    background: rgba(255, 255, 255, .82);
    min-width: 0;
  }

  .log-label {
    font-size: 12px;
    font-weight: 800;
    color: #475569;
    margin-bottom: 4px;
  }

  .log-value {
    font-size: 14px;
    color: #0f172a;
    overflow-wrap: anywhere;
  }

  .log-empty {
    padding: 10px 0;
  }

  @media (min-width: 768px) {
    .log-details-grid {
      grid-template-columns: repeat(3, minmax(0, 1fr));
    }
  }

  .custom-modal {
    display: none;
    position: fixed;
    inset: 0;
    background: rgba(0, 0, 0, .55);
    z-index: 99999;
    padding: 20px;
    overflow-y: auto;
  }

  .custom-modal.active {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .custom-modal-box {
    width: 100%;
    max-width: 950px;
    background: #fff;
    border-radius: 18px;
    overflow: hidden;
    box-shadow: 0 20px 60px rgba(0, 0, 0, .25);
    animation: modalFade .2s ease;
  }

  .custom-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 18px 22px;
    border-bottom: 1px solid #e5e7eb;
  }

  .custom-modal-header h3 {
    margin: 0;
    font-size: 22px;
    font-weight: 700;
  }

  .custom-modal-body {
    padding: 22px;
    max-height: 80vh;
    overflow-y: auto;
  }

  .custom-close-btn {
    border: none;
    background: #ef4444;
    color: #fff;
    width: 38px;
    height: 38px;
    border-radius: 50%;
    cursor: pointer;
    font-size: 24px;
    line-height: 1;
  }

  .custom-close-btn:hover {
    opacity: .9;
  }

  @keyframes modalFade {
    from {
      transform: scale(.95);
      opacity: 0;
    }

    to {
      transform: scale(1);
      opacity: 1;
    }
  }
</style>

<div class="master-wrap">
  <div class="headbar">
    <div>
      <div>
        <h2 class="title">Update User</h2>
      </div>
      <div class="muted">Safe tool: It does <b>NOT</b> delete any user. It disables wrong signup by moving mobile to <b>55-series</b> and setting name = <b>dummy</b>.</div>
    </div>
  </div>

  <?php if ($ok): ?><div class="alert ok"><?= h($ok) ?></div><?php endif; ?>
  <?php if ($err): ?><div class="alert danger"><?= h($err) ?></div><?php endif; ?>

  <div class="card">
    <div class="toolbar">
      <form method="get" class="search" style="gap:10px">
        <input class="inp" name="mobile" value="<?= h($mobile) ?>" placeholder="Enter 10-digit mobile to search" style="max-width:320px">
        <button class="btn primary" type="submit">Search</button>
        <a class="btn secondary" href="<?= h(keep_params(['mobile' => null, 'action' => null, 'ok' => null])) ?>">Reset</a>
      </form>
    </div>

    <?php if ($mobile !== '' && !$user): ?>
      <div class="badge off" style="margin-top:10px">No user found.</div>
    <?php endif; ?>

    <?php if ($user): ?>
      <?php
      $meta = fetch_profile_name($con, $user);
      [$ptypeLabel, $profileName, $profileTable, $nameCol, $mobileCol] = $meta;
      $uid = (int)$user['id'];
      $pid = (int)$user['profile_id'];
      $ptypeId = (int)$user['profile_type_id'];
      ?>
      <hr class="sep">
      <div class="user-card-top">
        <div>
          <div class="muted" style="font-size:13px">User</div>
          <div style="font-size:22px;font-weight:800;letter-spacing:.2px"><?= h($profileName ?: '—') ?></div>
          <div class="muted" style="margin-top:6px">
            <span class="badge on"><?= h($ptypeLabel) ?></span>
            <span class="badge on" style="margin-left:6px">Active</span>
            <span style="margin-left:10px">User ID: <b><?= h($uid) ?></b></span>
            <span style="margin-left:10px">Profile ID: <b><?= h($pid) ?></b></span>
            <span style="margin-left:10px">Mobile: <b><?= h($user['mobile_no']) ?></b></span>
          </div>
        </div>

        <!-- Step 1 buttons (no name/mobile input here) -->
        <div class="user-actions">
          <a class="btn success" href="<?= h(keep_params(['mobile' => $mobile, 'action' => 'edit_name'])) ?>">Edit Name</a>
          <a class="btn danger" href="<?= h(keep_params(['mobile' => $mobile, 'action' => 'disable'])) ?>">Disable Wrong Signup (55-series)</a>
        </div>
      </div>

      <?php $action = (string)($_GET['action'] ?? ''); ?>

      <?php if ($action === 'edit_name'): ?>
        <hr class="sep">
        <div class="card" style="margin-top:0">
          <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap">
            <h3 style="margin:0">Edit Name</h3>
            <a class="btn secondary" href="<?= h(keep_params(['action' => null])) ?>">Back</a>
          </div>
          <div class="muted" style="margin-top:6px">
            This will update:
            <?php if ($ptypeId === 1): ?>Recruiter <b>organization_name</b><?php endif; ?>
          <?php if ($ptypeId === 2): ?>Candidate <b>candidate_name</b><?php endif; ?>
        <?php if ($ptypeId === 3): ?>Promoter <b>name</b><?php endif; ?>
      & store a log entry.
          </div>

          <form method="post" style="margin-top:12px;display:grid;grid-template-columns:1fr;gap:12px;max-width:520px">
            <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="mobile" value="<?= h($mobile) ?>">
            <label>New Name*</label>
            <input class="inp" name="new_name" required value="<?= h($profileName) ?>" placeholder="Enter correct name">
            <button class="btn success" name="do_edit_name" type="submit">Save Name</button>
          </form>
        </div>
      <?php endif; ?>

      <?php if ($action === 'disable'): ?>
        <hr class="sep">
        <div class="card" style="margin-top:0">
          <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap">
            <h3 style="margin:0">Disable Wrong Signup</h3>
            <a class="btn secondary" href="<?= h(keep_params(['action' => null])) ?>">Back</a>
          </div>

          <div class="muted" style="margin-top:8px">
            This will:
            <ul style="margin:6px 0 0 18px">
              <li>Move user mobile to <b>55 + user_id padded</b> (unique 10-digit)</li>
              <li>Update profile mobile also</li>
              <li>Set profile name = <b>dummy</b></li>
              <li>Optionally clear fcm_token/lat/long & set status_id=0 if those columns exist</li>
              <li>Create a log entry</li>
            </ul>
          </div>

          <form method="post" style="margin-top:12px;display:flex;gap:10px;flex-wrap:wrap;align-items:center">
            <input type="hidden" name="csrf" value="<?= h(csrf_token()) ?>">
            <input type="hidden" name="mobile" value="<?= h($mobile) ?>">
            <button class="btn danger" name="do_disable" type="submit"
              onclick="return confirm('Are you sure? This will disable the user by moving mobile to 55-series and setting name dummy.');">
              Yes, Disable Now
            </button>
          </form>
        </div>
      <?php endif; ?>

    <?php endif; ?>
  </div>

  <!-- Recent logs -->
  <div class="card" style="margin-top:16px">
    <div style="display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap">

  <h3 style="margin:0">
    Recent Replace / Edit Logs
  </h3>

  <div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap">

    <div class="muted">
      Total Records:
      <b><?= h($totalRows) ?></b>
    </div>

    <form method="get" style="display:flex;gap:8px;align-items:center">

      <?php if (!empty($mobile)): ?>
        <input type="hidden" name="mobile" value="<?= h($mobile) ?>">
      <?php endif; ?>

      <?php if (!empty($_GET['action'])): ?>
        <input type="hidden" name="action" value="<?= h($_GET['action']) ?>">
      <?php endif; ?>

      <label style="font-size:14px">
        Show:
      </label>

      <select
        name="limit"
        class="inp"
        onchange="this.form.submit()"
        style="width:120px">

        <!-- <option value="15" <?= $limit === '15' ? 'selected' : '' ?>>
          Last 15
        </option> -->

        <option value="50" <?= $limit === '50' ? 'selected' : '' ?>>
          Last 50
        </option>

        <!-- <option value="100" <?= $limit === '100' ? 'selected' : '' ?>>
          Last 100
        </option> -->

        <option value="all" <?= $limit === 'all' ? 'selected' : '' ?>>
          View All
        </option>

      </select>
    </form>

  </div>
</div>

    <div class="table-wrap" style="margin-top:10px">
      <table>
        <thead>
          <tr>
            <th style="width:60px">SR</th>
            <th style="width:160px">When</th>
            <th style="width:140px">Admin</th>
            <th style="width:140px">User</th>
            <th style="width:220px">Action</th>
          </tr>
        </thead>
        <tbody>
          <?php if (!$logs): ?>
            <tr>
              <td colspan="5" class="muted">No logs yet.</td>
            </tr>
          <?php endif; ?>

          <?php $sr = 0;
          foreach ($logs as $lg): $sr++; ?>
            <?php
            $oldj = (string)($lg['old_data'] ?? '');
            $newj = (string)($lg['new_data'] ?? '');
            $oldA = json_decode($oldj, true);
            if (!is_array($oldA)) $oldA = [];
            $newA = json_decode($newj, true);
            if (!is_array($newA)) $newA = [];
            $uId  = (int)($lg['user_id'] ?? 0);
            $uMob = (string)($oldA['old_mobile'] ?? '');
            $uPty = (int)($oldA['profile_type_id'] ?? 0);
            $uPid = (int)($oldA['profile_id'] ?? 0);
            $uNm  = (string)($oldA['profile_name'] ?? '');
            $uLabel = ($uPty === 1 ? 'Recruiter' : ($uPty === 2 ? 'Candidate' : ($uPty === 3 ? 'Promoter' : 'Type ' . $uPty)));
            $adminNm = (string)($lg['admin_name'] ?? ('#' . (int)$lg['admin_user_id']));
            $when = (string)($lg['created_at'] ?? '');
            ?>
            <tr>
              <td><?= h($sr) ?></td>
              <td><?= h(date('d-m-Y h:i A', strtotime($when))) ?></td>
              <td>
                <div><b><?= h($adminNm) ?></b></div>
                <div class="muted">#<?= h((int)$lg['admin_user_id']) ?></div>
              </td>
              <td>
                <div><b>User #<?= h($uId) ?></b></div>
                <div class="muted"><?= h($uLabel) ?> · <?= h($uMob ?: '—') ?></div>
              </td>
              <td>
                <button type="button"
                  class="btn primary"
                  onclick="openDetailsModal('detailsModal_<?= h($sr) ?>')">
                  View Details
                </button>
              </td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
<?php if ($limit !== 'all' && $totalPages > 1): ?>

  <div style="
    display:flex;
    justify-content:center;
    align-items:center;
    gap:10px;
    margin-top:20px;
    flex-wrap:wrap;
  ">

    <!-- Previous -->
    <?php if ($page > 1): ?>
      <a
        class="btn secondary"
        href="<?= h(keep_params([
          'page' => $page - 1,
          'limit' => $limit
        ])) ?>">
        ← Prev
      </a>
    <?php endif; ?>

    <span class="muted">
      Page <b><?= h($page) ?></b>
      of
      <b><?= h($totalPages) ?></b>
    </span>

    <!-- Next -->
    <?php if ($page < $totalPages): ?>
      <a
        class="btn primary"
        href="<?= h(keep_params([
          'page' => $page + 1,
          'limit' => $limit
        ])) ?>">
        Next →
      </a>
    <?php endif; ?>

  </div>

<?php endif; ?>
    <?php $sr = 0;
    foreach ($logs as $lg): $sr++; ?>
      <?php
      $oldj = (string)($lg['old_data'] ?? '');
      $newj = (string)($lg['new_data'] ?? '');
      $oldA = json_decode($oldj, true);
      if (!is_array($oldA)) $oldA = [];
      $newA = json_decode($newj, true);
      if (!is_array($newA)) $newA = [];
      ?>
      <div class="custom-modal"
        id="detailsModal_<?= h($sr) ?>">

        <div class="custom-modal-box">

          <div class="custom-modal-header">
            <h3>User Change Details</h3>

            <button type="button"
              class="custom-close-btn"
              onclick="closeDetailsModal('detailsModal_<?= h($sr) ?>')">
              ×
            </button>
          </div>

          <div class="custom-modal-body">

            <div class="change-details-card new-data">
              <h6 class="change-details-title">
                New Details
              </h6>

              <div class="log-details-grid">
                <?php render_log_details($newA); ?>
              </div>
            </div>

            <div class="change-details-card old-data">
              <h6 class="change-details-title">
                Old Details
              </h6>

              <div class="log-details-grid">
                <?php render_log_details($oldA); ?>
              </div>
            </div>

          </div>
        </div>
      </div>
    <?php endforeach; ?>
  </div>
</div>
<script>
  function openDetailsModal(id) {
    document.getElementById(id).classList.add('active');
    document.body.style.overflow = 'hidden';
  }

  function closeDetailsModal(id) {
    document.getElementById(id).classList.remove('active');
    document.body.style.overflow = '';
  }

  document.addEventListener('click', function(e) {
    if (e.target.classList.contains('custom-modal')) {
      e.target.classList.remove('active');
      document.body.style.overflow = '';
    }
  });
</script>
<?php
echo ob_get_clean();
