<?php
// users.php — form validation (surname, firstname, sex, role), Status col, delete icon, deactivate/activate with dialog
declare(strict_types=1);
session_start();

/* ===== DB via include (expects $DB_HOST, $DB_NAME, $DB_USER, $DB_PASS, optional $DB_CHARSET) ===== */
@include __DIR__ . '/../../includes/connect.php';
if (!isset($DB_HOST,$DB_NAME,$DB_USER,$DB_PASS)) { http_response_code(500); echo "DB parameters not found in includes/connect.php"; exit; }
$DB_CHARSET = $DB_CHARSET ?? 'utf8mb4';
$dsn = "mysql:host={$DB_HOST};dbname={$DB_NAME};charset={$DB_CHARSET}";
$options = [
  PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
  PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
  PDO::ATTR_EMULATE_PREPARES => false,
];
try { $pdo = new PDO($dsn, $DB_USER, $DB_PASS, $options); }
catch (Throwable $e) { http_response_code(500); echo "Database connection failed."; exit; }

/* ===== CSRF ===== */
if (empty($_SESSION['csrf_token'])) $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
function require_csrf(): void {
  if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $tok = $_POST['csrf'] ?? '';
    if (!hash_equals($_SESSION['csrf_token'] ?? '', $tok)) {
      header('Content-Type: application/json'); http_response_code(400);
      echo json_encode(['ok'=>false,'error'=>'Invalid CSRF token']); exit;
    }
  }
}

/* ===== Dictionaries ===== */
$DESIG = [""=>"?", "1"=>"Commissioner Office", "2"=>"Chief Land Officer","3"=>"Principal Land Officer","4"=>"Senior Land Officer","5"=>"Deeds Officer","6"=>"High Registrar of Deeds"];
$SEX   = ["m"=>"Male","f"=>"Female",""=>"?"];
$ROLES = ["" => "?", "1" => "SuperAdmin", "2" => "Admin", "3" => "Data Capture Officer", "4" => "Printing Officer"];

/* ===== Helpers ===== */
function h(string $s): string { return htmlspecialchars($s, ENT_QUOTES, 'UTF-8'); }
function render_row(array $u, array $DESIG, array $SEX, array $ROLES): string {
  $id=(int)$u['userid']; $un=h($u['username']??''); $desV=(string)($u['designation']??''); $des=h($DESIG[$desV]??'?');
  $sn=h($u['surname']??''); $fn=h($u['firstname']??''); $mn=h($u['middlename']??'');
  $sxV=(string)($u['sex']??''); $sx=h($SEX[$sxV]??'?'); $roleV=(string)($u['roleid']??''); $role=h($ROLES[$roleV]??'?');
  $status = ($u['status']??'active')==='inactive' ? 'Inactive' : 'Active';
  $statusV= strtolower($status);

  return '
  <tr class="row" data-id="'.$id.'">
    <td class="sn-coltiny" data-sort-value=""></td>

    <td class="sn-col editable" data-col="username" data-type="text" data-sort-value="'.$un.'">'.$un.'</td>
    <td class="sn-col" data-sort-value="********">********</td>
    <td class="sn-col editable" data-col="designation" data-type="select" data-value="'.$desV.'" data-sort-value="'.$des.'">'.$des.'</td>
    <td class="sn-col editable" data-col="surname" data-type="text" data-sort-value="'.$sn.'">'.$sn.'</td>
    <td class="sn-col editable" data-col="firstname" data-type="text" data-sort-value="'.$fn.'">'.$fn.'</td>
    <td class="sn-col editable" data-col="middlename" data-type="text" data-sort-value="'.$mn.'">'.$mn.'</td>
    <td class="sn-col editable" data-col="sex" data-type="select" data-value="'.$sxV.'" data-sort-value="'.$sx.'">'.$sx.'</td>
    <td class="sn-col editable" data-col="roleid" data-type="select" data-value="'.$roleV.'" data-sort-value="'.$role.'">'.$role.'</td>

    <td class="sn-col status '.$statusV.'" data-sort-value="'.$status.'">'.$status.'</td>

    <td class="actions" data-sort-value="">
      <button class="icon-btn btn-deactivate" data-id="'.$id.'" title="'.($status==='Active'?'Deactivate':'Activate').'">
        '.($status==='Active'
            // PAUSE icon (deactivate)
      ? '<svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 5h4v14H6zM14 5h4v14h-4z"/></svg>'
            : '<svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>'  // play-like
         ).'
      </button>
      <button class="icon-btn btn-delete" data-id="'.$id.'" title="Delete user">
        <svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true"><path d="M9 3h6l1 2h4v2H4V5h4l1-2zm1 6h2v9h-2V9zm4 0h2v9h-2V9z"/></svg>
      </button>
    </td>
  </tr>';
}

/* ===== AJAX endpoints ===== */
if ($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['action'])) {
  header('Content-Type: application/json'); require_csrf();
  $action = $_POST['action'];

  if ($action==='add') {
    $username=trim($_POST['username']??''); $password=(string)($_POST['password']??'');
    $designation=trim($_POST['designation']??''); $surname=trim($_POST['surname']??'');
    $firstname=trim($_POST['firstname']??''); $middlename=trim($_POST['middlename']??'');
    $sex=trim($_POST['sex']??''); $roleid=trim($_POST['roleid']??'');

    // REQUIRED: username, password, surname, firstname, sex, roleid
    if ($username===''||$password==='') { echo json_encode(['ok'=>false,'error'=>'Username and password are required']); exit; }
    if ($surname===''||$firstname==='') { echo json_encode(['ok'=>false,'error'=>'Surname and Firstname are required']); exit; }
    if (!in_array($sex, ['m','f'], true)) { echo json_encode(['ok'=>false,'error'=>'Sex is required']); exit; }
    if (!in_array($roleid, ['1','2','3','4'], true)) { echo json_encode(['ok'=>false,'error'=>'Role is required']); exit; }

    $stmt=$pdo->prepare("SELECT COUNT(*) FROM users WHERE username=?"); $stmt->execute([$username]);
    if ($stmt->fetchColumn()>0) { echo json_encode(['ok'=>false,'error'=>'Username already exists']); exit; }

    // sanitize optional selects
    if (!in_array($designation, ["","1","2","3","4","5","6"], true)) $designation = "";

    $hash=password_hash($password,PASSWORD_DEFAULT);

    $ins=$pdo->prepare("INSERT INTO users (username,password,designation,surname,firstname,middlename,sex,roleid,status) VALUES (?,?,?,?,?,?,?,?,?)");
    $ins->execute([$username,$hash,$designation,$surname,$firstname,$middlename,$sex,$roleid,'active']);

    $id=(int)$pdo->lastInsertId();
    $row=['userid'=>$id,'username'=>$username,'designation'=>$designation,'surname'=>$surname,'firstname'=>$firstname,'middlename'=>$middlename,'sex'=>$sex,'roleid'=>$roleid,'status'=>'active'];
    echo json_encode(['ok'=>true,'row_html'=>render_row($row,$DESIG,$SEX,$ROLES)]); exit;
  }

  if ($action==='delete') {
    $id=(int)($_POST['userid']??0);
    if ($id<=0) { echo json_encode(['ok'=>false,'error'=>'Invalid ID']); exit; }
    $del=$pdo->prepare("DELETE FROM users WHERE userid=?"); $del->execute([$id]);
    echo json_encode(['ok'=>true,'userid'=>$id]); exit;
  }

  if ($action==='status') {
    $id=(int)($_POST['userid']??0);
    $to=(string)($_POST['to']??'inactive');
    if ($id<=0 || !in_array($to,['active','inactive'],true)) { echo json_encode(['ok'=>false,'error'=>'Invalid request']); exit; }
    $st=$pdo->prepare("UPDATE users SET status=? WHERE userid=?");
    $st->execute([$to,$id]);
    echo json_encode(['ok'=>true,'userid'=>$id,'status'=>$to]); exit;
  }

  if ($action==='update') {
    $id=(int)($_POST['userid']??0); $col=(string)($_POST['col']??''); $val=(string)($_POST['val']??'');
    if ($id<=0) { echo json_encode(['ok'=>false,'error'=>'Invalid ID']); exit; }
    $text=['username','surname','firstname','middlename']; $select=['designation','sex','roleid'];
    $allowed=array_merge($text,$select); if (!in_array($col,$allowed,true)) { echo json_encode(['ok'=>false,'error'=>'Column not editable']); exit; }

    if (in_array($col,$text,true)) {
      $val=trim($val);
      if ($col==='username') {
        if ($val==='') { echo json_encode(['ok'=>false,'error'=>'Username is required']); exit; }
        $q=$pdo->prepare("SELECT COUNT(*) FROM users WHERE username=? AND userid<>?"); $q->execute([$val,$id]);
        if ($q->fetchColumn()>0) { echo json_encode(['ok'=>false,'error'=>'Username already exists']); exit; }
      }
      if ($col==='surname' && $val==='') { echo json_encode(['ok'=>false,'error'=>'Surname is required']); exit; }
      if ($col==='firstname' && $val==='') { echo json_encode(['ok'=>false,'error'=>'Firstname is required']); exit; }
    } else {
      if ($col==='designation' && !in_array($val,["","1","2","3","4","5","6"],true)) $val="";
      if ($col==='sex' && !in_array($val,["m","f"],true)) { echo json_encode(['ok'=>false,'error'=>'Sex is required']); exit; }
      if ($col==='roleid' && !in_array($val,["1","2","3","4"],true)) { echo json_encode(['ok'=>false,'error'=>'Role is required']); exit; }
    }
    $sql="UPDATE users SET {$col}=:v WHERE userid=:id"; $st=$pdo->prepare($sql); $st->execute([':v'=>$val,':id'=>$id]);

    if ($col==='designation') { echo json_encode(['ok'=>true,'display'=>($DESIG[$val]??'?'),'raw'=>$val]); exit; }
    if ($col==='sex')         { echo json_encode(['ok'=>true,'display'=>($SEX[$val]??'?'),'raw'=>$val]); exit; }
    if ($col==='roleid')      { echo json_encode(['ok'=>true,'display'=>($ROLES[$val]??'?'),'raw'=>$val]); exit; }
    echo json_encode(['ok'=>true,'display'=>$val]); exit;
  }

  echo json_encode(['ok'=>false,'error'=>'Unknown action']); exit;
}

/* ===== Server-side Search + Sort + Pagination (status included) ===== */
$q = trim($_GET['q'] ?? '');
$perPage = max(5, min(100, (int)($_GET['per'] ?? 10)));
$page = max(1, (int)($_GET['page'] ?? 1));
$sort = $_GET['sort'] ?? 'userid';
$dir  = strtolower($_GET['dir'] ?? 'desc') === 'asc' ? 'asc' : 'desc';

$sortable = [
  'userid'    => 'userid',
  'username'  => 'username',
  'designation'=>'designation',
  'surname'   => 'surname',
  'firstname' => 'firstname',
  'middlename'=> 'middlename',
  'sex'       => 'sex',
  'roleid'    => 'roleid',
  'status'    => 'status'
];
$orderBy = $sortable[$sort] ?? 'userid';
$offset = ($page - 1) * $perPage;

$where = '1=1';
$args = [];
if ($q !== '') {
  $where = '(username LIKE :q OR surname LIKE :q OR firstname LIKE :q OR middlename LIKE :q)';
  $args[':q'] = '%'.$q.'%';
}
$countStmt = $pdo->prepare("SELECT COUNT(*) FROM users WHERE $where");
$countStmt->execute($args);
$total = (int)$countStmt->fetchColumn();
$pages = max(1, (int)ceil($total / $perPage));
if ($page > $pages) { $page = $pages; $offset = ($page-1)*$perPage; }

$sql = "SELECT userid, username, designation, surname, firstname, middlename, sex, roleid, status
        FROM users WHERE $where
        ORDER BY $orderBy $dir
        LIMIT :lim OFFSET :off";
$dataStmt = $pdo->prepare($sql);
foreach ($args as $k=>$v) { $dataStmt->bindValue($k,$v,PDO::PARAM_STR); }
$dataStmt->bindValue(':lim', $perPage, PDO::PARAM_INT);
$dataStmt->bindValue(':off', $offset, PDO::PARAM_INT);
$dataStmt->execute();
$users = $dataStmt->fetchAll();

/* ===== Build query helper (preserve params) ===== */
function qp(array $overrides): string {
  $base = [
    'q' => $_GET['q'] ?? '',
    'per' => $_GET['per'] ?? 10,
    'page' => $_GET['page'] ?? 1,
    'sort' => $_GET['sort'] ?? 'userid',
    'dir' => $_GET['dir'] ?? 'desc'
  ];
  $final = array_merge($base, $overrides);
  return '?'.http_build_query($final);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>User Management</title>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<style>
  :root{
    --bg:#f6f8fc; --card:#fff; --text:#1f1f1f; --muted:#5f6368;
    --accent:#1a73e8; --danger:#d93025; --overlay:rgba(32,33,36,.6);
    --row-1:#ffffff; --row-2:#f1f3f4; --border:#e0e0e0; --ok:#137333;
  }
  body{margin:0;background:var(--bg);font-family:system-ui,Segoe UI,Roboto,Arial,sans-serif;color:var(--text);}
  .container{max-width:1200px;margin:24px auto;padding:0 16px;}
  .toolbar{display:flex;align-items:center;justify-content:space-between;margin-bottom:12px;gap:12px;flex-wrap:wrap;}
  .toolbar h1{font-size:18px;margin:0;color:var(--muted);font-weight:600;}
  .toolbar .actions{display:flex;gap:8px;align-items:center;flex-wrap:wrap;}
  .btn{border:1px solid var(--border);background:var(--card);padding:8px 12px;border-radius:8px;cursor:pointer}
  .btn.primary{background:var(--accent);color:#fff;border-color:var(--accent);}
  .list-card{background:var(--card);border:1px solid var(--border);border-radius:12px;overflow:hidden;}
  table{width:100%;border-collapse:collapse;}
  thead{background:#eef3ff; user-select:none;}
  th,td{padding:10px 12px;font-size:14px;border-bottom:1px solid var(--border);vertical-align:middle;}
  tbody tr:nth-child(odd){background:var(--row-1);}
  tbody tr:nth-child(even){background:var(--row-2);}
  .sn-coltiny{width:24px}
  .sn-col{white-space:nowrap}
  .empty{padding:20px;color:var(--muted);text-align:center}

  /* Status chip */
  .status.active{color:#137333;}
  .status.inactive{color:#d93025;}

  /* Icon buttons */
  .icon-btn{border:0;background:transparent;cursor:pointer;padding:6px;border-radius:6px;}
  .icon-btn:hover{background:#f1f3f4;}

  /* Sortable (server-side) */
  th.sortable a{color:inherit;text-decoration:none;display:block;position:relative;padding-right:22px;}
  th.sortable .arrow{position:absolute; right:4px; top:50%; transform:translateY(-50%); font-size:12px; color:var(--muted);}
  th.sortable.active{color:#0b57d0;}
  th.sortable.active .arrow{color:#0b57d0;}

  /* Search / pagination UI */
  .searchbar{display:flex;gap:8px;align-items:center;}
  .searchbar input[type="text"], .searchbar select{
    padding:8px 10px;border:1px solid var(--border);border-radius:8px;background:#fff;font-size:14px;
  }
  .pagination{display:flex;align-items:center;justify-content:flex-end;gap:6px;padding:10px;border-top:1px solid var(--border);}
  .pagination a, .pagination span{
    padding:6px 10px;border:1px solid var(--border);border-radius:8px;background:#fff;font-size:13px;text-decoration:none;color:inherit;
  }
  .pagination .current{background:#e8f0fe;border-color:#c6dafc;}

  /* Overlays & Modals (CENTERED) */
  .overlay{position:fixed; inset:0; background:var(--overlay); display:flex; align-items:center; justify-content:center; opacity:0; pointer-events:none; z-index:1000; transition:opacity .15s ease;}
  .overlay.show{opacity:1; pointer-events:auto;}
  .modal{width:min(780px,94vw); max-height:92vh; overflow:auto; background:var(--card); border-radius:12px; box-shadow:0 12px 40px rgba(0,0,0,.2); display:flex; flex-direction:column; margin:0;}
  .modal-header{display:flex;align-items:center;justify-content:space-between;padding:12px 16px;border-bottom:1px solid var(--border);}
  .modal-title{font-size:16px;font-weight:600;}
  .modal-body{padding:16px;}
  .modal-footer{display:flex;justify-content:flex-end;gap:8px;padding:12px 16px;border-top:1px solid var(--border);}
  .close{background:transparent;border:0;font-size:20px;cursor:pointer;color:var(--muted);}
  .grid{display:grid;grid-template-columns:1fr 1fr;gap:12px;}
  .field{display:flex;flex-direction:column;gap:6px;}
  .field label{font-size:12px;color:var(--muted);}
  .field input[type="text"], .field input[type="password"], .field select{
    padding:9px 10px;border:1px solid var(--border);border-radius:8px;background:#fff;font-size:14px;
  }
  .hint{font-size:12px;color:var(--muted);}

  /* Inline editor visuals */
  .editable{cursor:text; position:relative;}
  .editable.editing{background:#fff7e6; outline:2px solid #ffd24d;}
  .cell-spinner{position:absolute; right:6px; top:50%; transform:translateY(-50%); font-size:12px; color:var(--muted);}

  /* Toast (TOP) */
  .toast{position:fixed; top:16px; left:50%; transform:translateX(-50%); background:#202124; color:#fff; padding:10px 14px; border-radius:8px; font-size:13px; display:none; z-index: 1100;}
  .toast.ok{background:var(--ok);} .toast.err{background:var(--danger);}
</style>
</head>
<body>
<div class="container">
  <div class="toolbar">
    <h1>Users</h1>
    <div class="actions">
      <form class="searchbar" method="get" action="">
        <input type="text" name="q" value="<?php echo h($q); ?>" placeholder="Search users...">
        <select name="per">
          <?php foreach ([10,20,50,100] as $pp) { $sel = $perPage===$pp ? 'selected' : ''; echo "<option value=\"$pp\" $sel>$pp / page</option>"; } ?>
        </select>
        <input type="hidden" name="sort" value="<?php echo h($sort); ?>">
        <input type="hidden" name="dir" value="<?php echo h($dir); ?>">
        <button class="btn" type="submit">Search</button>
        <a class="btn" href="<?php echo qp(['q'=>'','page'=>1]); ?>">Reset</a>
      </form>
      <button id="btnAdd" class="btn primary">+ Add user</button>
    </div>
  </div>

  <div class="list-card">
    <table id="usersTable">
      <thead>
        <tr class="title-row">
          <th class="sn-coltiny"></th>
          <?php
            // Server-side sort links
            echo '<th class="sortable '.($sort==='username'?'active':'').'"><a href="'.h(qp(['sort'=>'username','dir'=>$sort==='username'&&$dir==='asc'?'desc':'asc','page'=>1])).'">Username <span class="arrow">'.($sort==='username'?($dir==='asc'?'↑':'↓'):'⇅').'</span></a></th>';
            echo '<th>Password</th>';
            foreach (['designation'=>'Designation','surname'=>'Surname','firstname'=>'Firstname','middlename'=>'Middlename','sex'=>'Sex','roleid'=>'Role','status'=>'Status'] as $c=>$label) {
              $active = $sort===$c; $icon = $active?($dir==='asc'?'↑':'↓'):'⇅';
              echo '<th class="sortable '.($active?'active':'').'"><a href="'.h(qp(['sort'=>$c,'dir'=>$active&&$dir==='asc'?'desc':'asc','page'=>1])).'">'.h($label).' <span class="arrow">'.$icon.'</span></a></th>';
            }
          ?>
          <th></th>
        </tr>
      </thead>
      <tbody id="tbodyUsers">
        <?php
          if (!$users) {
            echo '<tr><td colspan="11" class="empty">No users found.</td></tr>';
          } else {
            foreach ($users as $u) echo render_row($u,$DESIG,$SEX,$ROLES);
          }
        ?>
      </tbody>
    </table>

    <div class="pagination">
      <span>Total: <?php echo $total; ?></span>
      <?php
        $prev = max(1,$page-1); $next = min($pages,$page+1);
        if ($page>1) echo '<a href="'.h(qp(['page'=>1])).'">« First</a><a href="'.h(qp(['page'=>$prev])).'">‹ Prev</a>';
        else echo '<span>« First</span><span>‹ Prev</span>';
        $start = max(1, $page-2); $end = min($pages, $page+2);
        for ($p=$start;$p<=$end;$p++) {
          if ($p===$page) echo '<span class="current">'.$p.'</span>';
          else echo '<a href="'.h(qp(['page'=>$p])).'">'.$p.'</a>';
        }
        if ($page<$pages) echo '<a href="'.h(qp(['page'=>$next])).'">Next ›</a><a href="'.h(qp(['page'=>$pages])).'">Last »</a>';
        else echo '<span>Next ›</span><span>Last »</span>';
      ?>
    </div>
  </div>
</div>

<!-- Add Modal (centered) -->
<div class="overlay" id="overlayAdd">
  <div class="modal" role="dialog" aria-modal="true" aria-labelledby="modalTitle">
    <div class="modal-header">
      <div class="modal-title" id="modalTitle">Add user</div>
      <button class="close" data-close="#overlayAdd" aria-label="Close">✕</button>
    </div>
    <form id="formAdd" class="modal-body" onsubmit="return false;">
      <input type="hidden" name="action" value="add">
      <input type="hidden" name="csrf" value="<?php echo h($_SESSION['csrf_token']); ?>">
      <div class="grid">
        <div class="field"><label for="username">Username*</label><input type="text" id="username" name="username" required></div>
        <div class="field"><label for="password">Password*</label><input type="password" id="password" name="password" required><div class="hint">Stored securely (hashed)</div></div>

        <div class="field"><label for="surname">Surname*</label><input type="text" id="surname" name="surname" required></div>
        <div class="field"><label for="firstname">Firstname*</label><input type="text" id="firstname" name="firstname" required></div>

        <div class="field"><label for="designation">Designation</label>
          <select id="designation" name="designation">
            <option value="">Select Designation</option>
            <option value="2">Chief Land Officer</option>
            <option value="1">Commissioner Office</option>
            <option value="5">Deeds Officer</option>
            <option value="6">High Registrar of Deeds</option>
            <option value="3">Principal Land Officer</option>
            <option value="4">Senior Land Officer</option>
          </select>
        </div>

        <div class="field"><label for="middlename">Middlename</label><input type="text" id="middlename" name="middlename"></div>

        <div class="field"><label for="sex">Sex*</label>
          <select id="sex" name="sex" required>
            <option value="">Select Sex</option><option value="f">Female</option><option value="m">Male</option>
          </select>
        </div>

        <div class="field"><label for="roleid">Role*</label>
          <select id="roleid" name="roleid" required>
            <option value="">Select Role</option>
            <option value="1">SuperAdmin</option><option value="2">Admin</option><option value="3">Data Capture Officer</option><option value="4">Printing Officer</option>
          </select>
        </div>
      </div>
    </form>
    <div class="modal-footer">
      <button class="btn" data-close="#overlayAdd" type="button">Cancel</button>
      <button class="btn primary" id="submitAdd" type="button">Add</button>
    </div>
  </div>
</div>

<!-- Delete Confirm Modal -->
<div class="overlay" id="overlayDel">
  <div class="modal" role="dialog" aria-modal="true" aria-labelledby="delTitle">
    <div class="modal-header">
      <div class="modal-title" id="delTitle">Delete user</div>
      <button class="close" data-close="#overlayDel" aria-label="Close">✕</button>
    </div>
    <div class="modal-body">
      <p>Are you sure you want to delete this user? This action cannot be undone.</p>
      <input type="hidden" id="delUserId" value="">
      <input type="hidden" id="csrfDel" value="<?php echo h($_SESSION['csrf_token']); ?>">
    </div>
    <div class="modal-footer">
      <button class="btn" data-close="#overlayDel" type="button">Cancel</button>
      <button class="btn primary" id="confirmDelete" type="button" style="background:var(--danger);border-color:var(--danger);">Delete</button>
    </div>
  </div>
</div>

<!-- Deactivate/Activate Confirm Modal -->
<div class="overlay" id="overlayStatus">
  <div class="modal" role="dialog" aria-modal="true" aria-labelledby="stTitle">
    <div class="modal-header">
      <div class="modal-title" id="stTitle">Change status</div>
      <button class="close" data-close="#overlayStatus" aria-label="Close">✕</button>
    </div>
    <div class="modal-body">
      <p id="statusMessage">Are you sure you want to deactivate this user?</p>
      <input type="hidden" id="stUserId" value="">
      <input type="hidden" id="stTo" value="inactive">
      <input type="hidden" id="csrfSt" value="<?php echo h($_SESSION['csrf_token']); ?>">
    </div>
    <div class="modal-footer">
      <button class="btn" data-close="#overlayStatus" type="button">Cancel</button>
      <button class="btn primary" id="confirmStatus" type="button">Confirm</button>
    </div>
  </div>
</div>

<div id="toast" class="toast"></div>

<script>
(function($){
  const csrf = '<?php echo h($_SESSION['csrf_token']); ?>';
  const $tbody = $('#tbodyUsers');

  /* Toast */
  function toast(msg, ok=false){
    const $t = $('#toast');
    $t.removeClass('ok err').addClass(ok?'ok':'err').text(msg).stop(true,true).fadeIn(120);
    setTimeout(()=> $t.fadeOut(200), 2000);
  }

  /* Centered modals */
  function openOverlay(sel){ $(sel).addClass('show'); }
  function closeOverlay(sel){ $(sel).removeClass('show'); }
  $(document).on('click','[data-close]',function(){ closeOverlay($(this).data('close')); });
  $(document).on('keydown', function(e){ if(e.key==='Escape'){ closeOverlay('#overlayAdd'); closeOverlay('#overlayDel'); closeOverlay('#overlayStatus'); } });

  /* Client-side validation (extra) before Add submit */
  function validateAdd(){
    const need = [
      {id:'#username', msg:'Username is required'},
      {id:'#password', msg:'Password is required'},
      {id:'#surname', msg:'Surname is required'},
      {id:'#firstname', msg:'Firstname is required'},
      {id:'#sex', msg:'Sex is required', sel:true},
      {id:'#roleid', msg:'Role is required', sel:true},
    ];
    for (const it of need){
      const $el = $(it.id);
      const val = ($el.is('select') ? $el.val() : $el.val().trim());
      if (!val) { $el.trigger('focus'); toast(it.msg); return false; }
    }
    return true;
  }

  /* Add user */
  $('#btnAdd').on('click', ()=> openOverlay('#overlayAdd'));
  $('#submitAdd').on('click', function(){
    if (!validateAdd()) return;
    $.ajax({
      url:'', method:'POST', dataType:'json',
      data: $('#formAdd').serialize(),
      success: function(res){
        if(!res || res.ok!==true){ toast(res && res.error ? res.error : 'Failed to add'); return; }
        const $row = $(res.row_html).hide();
        $tbody.find('.empty').closest('tr').remove();
        $tbody.prepend($row); $row.fadeIn(150);
        closeOverlay('#overlayAdd'); $('#formAdd')[0].reset();
        toast('User added', true);
      },
      error: ()=> toast('Network / server error')
    });
  });

  /* Delete icon => dialog */
  let pendingDeleteId = null;
  $(document).on('click', '.btn-delete', function(){
    pendingDeleteId = $(this).data('id');
    $('#delUserId').val(pendingDeleteId);
    openOverlay('#overlayDel');
  });
  $('#confirmDelete').on('click', function(){
    const id = $('#delUserId').val();
    $.ajax({
      url:'', method:'POST', dataType:'json',
      data:{action:'delete', userid:id, csrf:$('#csrfDel').val()},
      success: function(res){
        if(!res || res.ok!==true){ toast(res && res.error ? res.error : 'Delete failed'); return; }
        $('tr[data-id="'+id+'"]').fadeOut(120, function(){
          $(this).remove();
          if($tbody.children().length===0){
            $tbody.append('<tr><td colspan="11" class="empty">No users found.</td></tr>');
          }
        });
        toast('User deleted', true);
        closeOverlay('#overlayDel');
      },
      error: ()=> toast('Network / server error')
    });
  });

  /* Deactivate/Activate icon => dialog */
  let pendingStatusId = null;
  $(document).on('click', '.btn-deactivate', function(){
    pendingStatusId = $(this).data('id');
    const $row = $('tr[data-id="'+pendingStatusId+'"]');
    const isInactive = $row.find('.status').hasClass('inactive');
    const to = isInactive ? 'active' : 'inactive';
    $('#stUserId').val(pendingStatusId);
    $('#stTo').val(to);
    $('#statusMessage').text(isInactive ? 'Activate this user?' : 'Deactivate this user?');
    $('#stTitle').text(isInactive ? 'Activate user' : 'Deactivate user');
    openOverlay('#overlayStatus');
  });

  $('#confirmStatus').on('click', function(){
    const id = $('#stUserId').val();
    const to = $('#stTo').val();
    $.ajax({
      url:'', method:'POST', dataType:'json',
      data:{action:'status', userid:id, to:to, csrf:$('#csrfSt').val()},
      success: function(res){
        if(!res || res.ok!==true){ toast(res && res.error ? res.error : 'Update failed'); return; }
        const $row = $('tr[data-id="'+id+'"]');
        const label = res.status === 'inactive' ? 'Inactive' : 'Active';
        $row.find('.status').text(label).attr('data-sort-value', label)
            .removeClass('active inactive').addClass(res.status);
        // Update the icon title/action label
        $row.find('.btn-deactivate').attr('title', res.status==='inactive'?'Activate':'Deactivate')
          .html(res.status==='inactive'
            ? '<svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true"><path d="M8 5v14l11-7z"/></svg>'
            // PAUSE icon when active -> shows "Deactivate"
      : '<svg width="18" height="18" viewBox="0 0 24 24" aria-hidden="true"><path d="M6 5h4v14H6zM14 5h4v14h-4z"/></svg>'
  );
        toast('Status updated', true);
        closeOverlay('#overlayStatus');
      },
      error: ()=> toast('Network / server error')
    });
  });

  /* Inline edit (unchanged except required fields enforced server-side) */
  let editing = null;
  const designationOptions = [
    {v:"", t:"?"},{v:"2", t:"Chief Land Officer"},{v:"1", t:"Commissioner Office"},
    {v:"5", t:"Deeds Officer"},{v:"6", t:"High Registrar of Deeds"},{v:"3", t:"Principal Land Officer"},{v:"4", t:"Senior Land Officer"}
  ];
  const sexOptions = [{v:"m", t:"Male"},{v:"f", t:"Female"}];
  const roleOptions = [{v:"1", t:"SuperAdmin"},{v:"2", t:"Admin"},{v:"3", t:"Data Capture Officer"},{v:"4", t:"Printing Officer"}];

  function buildSelect(options, current){
    const $sel = $('<select class="inline-select">')
      .css({width:'calc(100% - 24px)', padding:'6px 8px', font:'inherit', border:'1px solid var(--border)', borderRadius:'6px', background:'#fff'});
    options.forEach(opt=>{
      const $o=$('<option>').val(opt.v).text(opt.t);
      if(opt.v===String(current)) $o.prop('selected', true);
      $sel.append($o);
    });
    return $sel;
  }
  function startEditText($cell){
    if(editing) return;
    editing = { $cell, origText: $cell.text() };
    $cell.addClass('editing');
    const $inp = $('<input type="text" class="inline-input">').val($cell.text())
      .css({width:'calc(100% - 24px)', padding:'6px 8px', font:'inherit', border:'1px solid var(--border)', borderRadius:'6px'});
    const $spin=$('<span class="cell-spinner"></span>');
    $cell.empty().append($inp).append($spin); $inp.trigger('focus').select();
    function commit(newVal){
      if(newVal===editing.origText){ cancel(); return; }
      const userid=$cell.closest('tr').data('id'); const col=$cell.data('col');
      $spin.text('…');
      $.ajax({
        url:'', method:'POST', dataType:'json',
        data:{action:'update', userid, col, val:newVal, csrf},
        success: function(res){
          if(!res || res.ok!==true){ $cell.text(editing.origText).attr('data-sort-value', editing.origText); toast(res && res.error ? res.error : 'Update failed'); }
          else { const display = res.display ?? newVal; $cell.text(display).attr('data-sort-value', display); toast('Saved', true); }
          $cell.removeClass('editing'); editing=null;
        }, error: function(){ $cell.text(editing.origText).attr('data-sort-value', editing.origText); $cell.removeClass('editing'); editing=null; toast('Network / server error'); }
      });
    }
    function cancel(){ $cell.text(editing.origText).attr('data-sort-value', editing.origText); $cell.removeClass('editing'); editing=null; }
    $inp.on('keydown', e=>{ if(e.key==='Enter') commit($inp.val().trim()); else if(e.key==='Escape') cancel(); });
    $inp.on('blur', ()=> commit($inp.val().trim()));
  }
  function startEditSelect($cell){
    if(editing) return;
    const col=$cell.data('col');
    const opts=(col==='designation')?designationOptions:(col==='sex')?sexOptions:roleOptions;
    editing = { $cell, origText:$cell.text(), origVal:$cell.data('value')??'' };
    $cell.addClass('editing');
    const current=String($cell.data('value')??''); const $sel=buildSelect(opts,current); const $spin=$('<span class="cell-spinner"></span>');
    $cell.empty().append($sel).append($spin); $sel.trigger('focus');
    function commit(newVal){
      if(String(newVal)===String(editing.origVal)){ cancel(); return; }
      const userid=$cell.closest('tr').data('id');
      $spin.text('…');
      $.ajax({
        url:'', method:'POST', dataType:'json',
        data:{action:'update', userid, col, val:newVal, csrf},
        success:function(res){
          if(!res || res.ok!==true){
            $cell.text(editing.origText).data('value', editing.origVal).attr('data-sort-value', editing.origText);
            toast(res && res.error ? res.error : 'Update failed');
          } else {
            const label = res.display ?? editing.origText;
            $cell.text(label).data('value', res.raw ?? newVal).attr('data-sort-value', label);
            toast('Saved', true);
          }
          $cell.removeClass('editing'); editing=null;
        },
        error:function(){
          $cell.text(editing.origText).data('value', editing.origVal).attr('data-sort-value', editing.origText);
          $cell.removeClass('editing'); editing=null; toast('Network / server error');
        }
      });
    }
    function cancel(){ $cell.text(editing.origText).data('value', editing.origVal).attr('data-sort-value', editing.origText); $cell.removeClass('editing'); editing=null; }
    $sel.on('keydown', e=>{ if(e.key==='Enter') commit($sel.val()); else if(e.key==='Escape') cancel(); });
    $sel.on('blur', ()=> commit($sel.val()));
  }
  $(document).on('click','td.editable',function(){
    const $cell=$(this), t=$cell.data('type');
    if(t==='text') startEditText($cell); else if(t==='select') startEditSelect($cell);
  });

})(jQuery);
</script>
</body>
</html>
