<?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 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 = [];
$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 15";
$rs = mysqli_query($con, $logSql);
if ($rs) {
  while ($r = mysqli_fetch_assoc($rs)) $logs[] = $r;
}

/* =========================================================
   UI
========================================================= */
?>
<style>
/* small patch to prevent horizontal overflow in old/new cells */
.table-wrap table td pre.json {
  margin:0;
  white-space:pre-wrap;
  word-break:break-word;
  overflow-wrap:anywhere;
  font-size:12px;
  line-height:1.35;
  color:#cbd5e1;
}
.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; }
</style>

<div class="master-wrap">
  <div class="headbar">
    <div>
      <div class="title">Update User</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 class="muted">Latest 15</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>
            <th>Old</th>
            <th>New</th>
          </tr>
        </thead>
        <tbody>
          <?php if(!$logs): ?>
            <tr><td colspan="7" 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 = [];
              $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($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><?=h($lg['action_type'] ?? '')?></td>
              <td><pre class="json"><?=h($oldj)?></pre></td>
              <td><pre class="json"><?=h($newj)?></pre></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>
</div>

<?php
echo ob_get_clean();
