<?php
// Resilient Manage Users page
// - tolerant to missing db_config.php during FTP sync
// - uses SubAdminPageGuard when available
// - supports Add / Edit / Delete / Promote / Demote / Bulk role change


// --- Diagnostic logging (writes to project logs/admin_manage_users_error.log) ---
// This captures PHP warnings/notices/fatals and writes them to a file we can read
$logsDir = __DIR__ . '/logs';
if (!is_dir($logsDir)) {
  @mkdir($logsDir, 0755, true);
}
$diagLog = $logsDir . '/admin_manage_users_error.log';
ini_set('display_errors', 0);
ini_set('log_errors', 0); // we log to our own file to avoid mixing with server logs
set_error_handler(function($errno, $errstr, $errfile, $errline){
  global $diagLog;
  $msg = sprintf("[%s] ERROR %s in %s on line %d: %s\n", date('c'), $errno, $errfile, $errline, $errstr);
  @file_put_contents($diagLog, $msg, FILE_APPEND | LOCK_EX);
  return false; // allow normal handling as well
});
register_shutdown_function(function(){
  global $diagLog;
  $err = error_get_last();
  if ($err) {
    $msg = sprintf("[%s] SHUTDOWN %s in %s on line %d: %s\n", date('c'), $err['type'], $err['file'], $err['line'], $err['message']);
    @file_put_contents($diagLog, $msg, FILE_APPEND | LOCK_EX);
  }
});
@file_put_contents($diagLog, "--- admin_manage_users.php request start: " . date('c') . " ---\n", FILE_APPEND | LOCK_EX);

// Try to include db_config.php with short retries (FTP/cPanel may be syncing files)
$conn = null;
for ($i = 0; $i < 4; $i++) {
  if (file_exists(__DIR__ . '/db_config.php')) { include __DIR__ . '/db_config.php'; break; }
  if ($i < 3) usleep(200000); // 200ms
}
if (!isset($conn)) $conn = null;
session_start();

// Include optional helpers only when all their dependencies are present.
$guardFiles = [
  __DIR__ . '/helpers/subadmin_page_guard.php',
  __DIR__ . '/helpers/subadmin_actions.php',
  __DIR__ . '/helpers/permission_helper.php'
];
$canUsePageGuard = true;
foreach ($guardFiles as $f) {
  if (!file_exists($f) || !is_readable($f)) { $canUsePageGuard = false; break; }
}
if ($canUsePageGuard) {
  require_once __DIR__ . '/helpers/subadmin_page_guard.php';
} else {
  // If guard files are missing or incomplete, log and continue — don't fatal
  error_log('admin_manage_users.php: subadmin guard disabled; helper files missing or unreadable');
}

if (file_exists(__DIR__ . '/helpers/get_back_button.php')) require_once __DIR__ . '/helpers/get_back_button.php';

// Basic authentication check
if (empty($_SESSION['user_id'])) {
    header('Location: admin_login.php'); exit;
}

$pageGuard = null;
if ($canUsePageGuard && class_exists('SubAdminPageGuard')) {
  try {
    $pageGuard = new SubAdminPageGuard('manage_users');
    $pageGuard->enforceView();
  } catch (Throwable $e) {
    // Log and continue — don't break page for missing guard logic
    error_log('admin_manage_users.php: SubAdminPageGuard failed: ' . $e->getMessage());
    $pageGuard = null;
  }
}

$PRIMARY_ADMIN_EMAIL = 'maham11abc@gmail.com';

$users = [];
if (!empty($conn)) {
  try {
    $res = $conn->query("SELECT id, username, email, phone, age, gender, created_at FROM users ORDER BY id DESC");
  } catch (Throwable $e) {
    error_log('admin_manage_users.php: Failed to query users table: ' . $e->getMessage());
    $res = false;
  }

  // Check if admins/subadmins tables exist (avoid querying missing tables)
  $haveAdmins = false;
  $haveSubadmins = false;
  if ($res !== false) {
    try {
      $t = $conn->query("SHOW TABLES LIKE 'admins'");
      $haveAdmins = ($t && $t->num_rows > 0);
    } catch (Throwable $e) {
      error_log('admin_manage_users.php: SHOW TABLES admins failed: ' . $e->getMessage());
      $haveAdmins = false;
    }
    try {
      $t = $conn->query("SHOW TABLES LIKE 'subadmins'");
      $haveSubadmins = ($t && $t->num_rows > 0);
    } catch (Throwable $e) {
      error_log('admin_manage_users.php: SHOW TABLES subadmins failed: ' . $e->getMessage());
      $haveSubadmins = false;
    }
  }

  if ($res) {
    while ($r = $res->fetch_assoc()) {
      // Flag primary admin for later UI adjustments (don\'t skip it any more)
      $r['is_primary'] = ($r['email'] === $PRIMARY_ADMIN_EMAIL);

      // Check admin status safely
      $uid = (int)$r['id'];
      $r['is_admin'] = false;
      $r['is_editor'] = false;
      $r['is_subadmin'] = false;
      if ($haveAdmins) {
        try {
          $admin_check = $conn->query("SELECT id FROM admins WHERE user_id = $uid LIMIT 1");
          $r['is_admin'] = ($admin_check && $admin_check->num_rows > 0);
        } catch (Throwable $e) {
          error_log('admin_manage_users.php: admins query failed: ' . $e->getMessage());
          $r['is_admin'] = false;
        }
      }
      // Check editor status
      if ($haveSubadmins) {
        try {
          $editor_check = $conn->query("SELECT user_id FROM editors WHERE user_id = $uid LIMIT 1");
          $r['is_editor'] = ($editor_check && $editor_check->num_rows > 0);
        } catch (Throwable $e) {
          error_log('admin_manage_users.php: editors query failed: ' . $e->getMessage());
          $r['is_editor'] = false;
        }
      }
      // Check subadmin status
      if ($haveSubadmins) {
        try {
          $subadmin_check = $conn->query("SELECT user_id FROM subadmins WHERE user_id = $uid LIMIT 1");
          $r['is_subadmin'] = ($subadmin_check && $subadmin_check->num_rows > 0);
        } catch (Throwable $e) {
          error_log('admin_manage_users.php: subadmins query failed: ' . $e->getMessage());
          $r['is_subadmin'] = false;
        }
      }

      $users[] = $r;
    }
  }
} else {
    $usersFile = __DIR__ . '/data/users.json';
  // Try to load users.json; retry briefly if file may be syncing via FTP
  for ($i=0;$i<4;$i++) {
    if (file_exists($usersFile)) {
      $tmp = @file_get_contents($usersFile);
      $dec = @json_decode($tmp, true);
      if (is_array($dec)) { 
        // Filter and check each user from JSON
        foreach ($dec as $u) {
          // preserve primary admin record too, mark it for UI
          $u['is_primary'] = ($u['email'] === $PRIMARY_ADMIN_EMAIL);
          $users[] = $u;
        }
        break; 
      }
    }
    if ($i < 3) usleep(200000);
  }
}

if ($pageGuard && method_exists($pageGuard, 'getCapabilities')) {
    $cap = $pageGuard->getCapabilities();
    $canCreate = !empty($cap['can_create']);
    $canEdit = !empty($cap['can_edit']);
    $canDelete = !empty($cap['can_delete']);
} else {
  // Fallback based on session: allow subadmins to create/edit, only admins can delete
  $isAdmin = !empty($_SESSION['is_admin']);
  $isSubadmin = !empty($_SESSION['is_subadmin']);
  $canCreate = $isAdmin || $isSubadmin;
  $canEdit = $isAdmin || $isSubadmin;
  $canDelete = $isAdmin;
}

// Protect primary admin email
$PRIMARY_ADMIN_EMAIL = 'maham11abc@gmail.com';

?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Manage Users - Admin</title>
  <link rel="stylesheet" href="styles.css">
  <style>
    table { width:100%; border-collapse:collapse; }
    th,td { padding:8px; border:1px solid #eee; }
    .btn { padding:6px 10px; border-radius:6px; cursor:pointer; }
    .modal { display:none; position:fixed; z-index:1000; left:0; top:0; width:100%; height:100%; background-color:rgba(0,0,0,0.4); }
    .modal.show { display:flex; align-items:center; justify-content:center; }
    .modal-content { background-color:#fff; padding:24px; border-radius:8px; width:90%; max-width:500px; box-shadow:0 4px 8px rgba(0,0,0,0.2); }
    .modal-header { display:flex; justify-content:space-between; align-items:center; margin-bottom:16px; }
    .modal-header h2 { margin:0; }
    .modal-close { cursor:pointer; font-size:24px; color:#999; }
    .form-group { margin-bottom:12px; }
    .form-group label { display:block; margin-bottom:4px; font-weight:600; }
    .form-group input, .form-group select { width:100%; padding:8px; border:1px solid #ddd; border-radius:6px; box-sizing:border-box; }
    .form-footer { display:flex; gap:8px; justify-content:flex-end; margin-top:16px; }
    .modal-message { padding:12px; margin-bottom:12px; border-radius:6px; }
    .modal-message.success { background:#eef8ee; color:#085; border:1px solid #85d485; }
    .modal-message.error { background:#fee; color:#c33; border:1px solid #fcc; }
    .modal-message.default { background:#e3f2fd; color:#1565c0; border:1px solid #90caf9; }
    .maintenance-banner { background:#fff3cd; color:#856404; border:1px solid #ffeeba; padding:12px; border-radius:6px; margin-bottom:12px; display:flex; justify-content:space-between; align-items:center; }
    .maintenance-banner button { background:transparent; border:none; color:#856404; font-weight:600; cursor:pointer; }
  </style>
</head>
<body class="admin-with-sidebar">
<!-- <php if (file_exists(__DIR__ . '/admin_sidebar.php')) include 'admin_sidebar.php'; ?> -->
<main class="admin-main-content" style="padding: 24px;">
  <!-- <div id="maintenanceBanner" class="maintenance-banner">
    <div>Temporary maintenance: some files may load late during FTP sync. Functionality remains available; please wait a moment if things appear empty.</div>
    <div><button onclick="document.getElementById('maintenanceBanner').style.display='none'">Dismiss</button></div>
  </div> -->
  <div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:16px;">
    <h1 style="margin:0;">Users</h1>
    <div style="display:flex; gap:8px;">
      <?php if ($canCreate): ?><button class="btn" onclick="openAddUserModal()" style="background:#4CAF50; color:#fff;">Add User</button><?php endif; ?>
      <?php echo (function_exists('getBackButton')) ? getBackButton('← Back') : ''; ?>
    </div>
  </div>

  <div style="display:flex; gap:12px; align-items:center; margin-bottom:12px;">
    <div>
      <select id="bulkActionSelect" style="padding:6px; border-radius:6px; border:1px solid #ddd;">
        <option value="">Bulk actions</option>
        <option value="delete">Delete Selected</option>
      </select>
      <button class="btn" onclick="applyBulkAction()" style="margin-left:8px;">Apply</button>
    </div>
    <div style="margin-left:auto; display:flex; gap:8px; align-items:center;">
      <label style="font-weight:600;">Change role to...</label>
      <select id="bulkRoleSelect" style="padding:6px; border-radius:6px; border:1px solid #ddd;">
        <option value="">-- Select role --</option>
        <option value="Editor">Editor</option>
        <option value="Sub-admin">Sub-admin</option>
        <option value="User">User</option>
      </select>
      <button class="btn" onclick="applyBulkRoleChange()">Change</button>
    </div>
  </div>

  <table>
    <thead>
      <tr>
        <th style="width:36px;"><input type="checkbox" id="selectAll" onchange="toggleSelectAll(this)"></th>
        <th>Username</th>
        <th>Email</th>
        <th>Role</th>
        <th>Action</th>
      </tr>
    </thead>
    <tbody id="usersTbody">
      <!-- Populated by JS -->
    </tbody>
  </table>

  <!-- View/Edit User Modal -->
  <div id="viewEditUserModal" class="modal">
    <div class="modal-content">
      <div class="modal-header">
        <h2>View/Edit User</h2>
        <span class="modal-close" onclick="closeViewEditModal()">&times;</span>
      </div>
      <div id="veModalMessage" class="modal-message" style="display:none;"></div>
      <form id="viewEditForm">
        <input type="hidden" id="ve_user_id" name="user_id">
        <div class="form-group">
          <label>Username (read-only)</label>
          <input type="text" id="ve_username" readonly style="background:#f5f5f5;">
        </div>
        <div class="form-group">
          <label>Email</label>
          <input type="email" id="ve_email" name="email">
        </div>
        <div class="form-group">
          <label>Name</label>
          <input type="text" id="ve_name" name="name">
        </div>
        <div class="form-group">
          <label>Age</label>
          <input type="number" id="ve_age" name="age">
        </div>
        <div class="form-group">
          <label>Phone</label>
          <input type="text" id="ve_phone" name="phone">
        </div>
        <div class="form-group">
          <label>Gender</label>
          <select id="ve_gender" name="gender">
            <option value="">-- Select --</option>
            <option value="Male">Male</option>
            <option value="Female">Female</option>
            <option value="Other">Other</option>
          </select>
        </div>
        <div class="form-footer">
          <button type="button" class="btn" onclick="closeViewEditModal()" style="background:#999; color:#fff;">Cancel</button>
          <button type="submit" class="btn" style="background:#0066cc; color:#fff;">Save Changes</button>
        </div>
      </form>
    </div>
  </div>

  <!-- Add User Modal -->
  <div id="addUserModal" class="modal">
    <div class="modal-content">
      <div class="modal-header"><h2>Add New User</h2><span class="modal-close" onclick="closeAddUserModal()">&times;</span></div>
      <div id="modalMessage"></div>
      <form id="addUserForm">
        <div class="form-group"><label for="username">Username</label><input type="text" id="username" name="username" required></div>
        <div class="form-group"><label for="email">Email</label><input type="email" id="email" name="email" required></div>
        <div class="form-group"><label for="password">Password</label><input type="password" id="password" name="password" autocomplete="new-password" required></div>
        <div class="form-group"><label for="confirm_password">Confirm Password</label><input type="password" id="confirm_password" name="confirm_password" autocomplete="new-password" required></div>
        <div class="form-group"><label for="phone">Phone (optional)</label><input type="tel" id="phone" name="phone" placeholder="Enter phone number"></div>
        <div class="form-group"><label for="age">Age (optional)</label><input type="number" id="age" name="age" min="1" max="150" placeholder="Enter age"></div>
        <div class="form-group"><label for="gender">Gender (optional)</label><select id="gender" name="gender"><option value="">-- Select --</option><option value="Male">Male</option><option value="Female">Female</option><option value="Other">Other</option></select></div>
        <div class="form-footer"><button type="button" class="btn" onclick="closeAddUserModal()">Cancel</button><button type="submit" class="btn" style="background:#4CAF50;color:#fff;">Create User</button></div>
      </form>
    </div>
  </div>

  <!-- Edit User Modal -->
  <div id="editUserModal" class="modal">
    <div class="modal-content">
      <div class="modal-header"><h2>Edit User</h2><span class="modal-close" onclick="closeEditUserModal()">&times;</span></div>
      <div id="editModalMessage"></div>
      <form id="editUserForm">
        <input type="hidden" id="edit_user_id" name="user_id">
        <div class="form-group"><label for="edit_username">Username</label><input type="text" id="edit_username" name="username" required></div>
        <div class="form-group"><label for="edit_email">Email</label><input type="email" id="edit_email" name="email" required></div>
        <div class="form-group"><label for="edit_password">Password (leave blank to keep)</label><input type="password" id="edit_password" name="password" autocomplete="new-password"></div>
        <div class="form-group"><label for="editConfirmPassword">Confirm Password</label><input type="password" id="editConfirmPassword" autocomplete="new-password"></div>
        <div class="form-footer"><button type="button" class="btn" onclick="closeEditUserModal()">Cancel</button><button type="submit" class="btn" style="background:#4CAF50;color:#fff;">Save Changes</button></div>
      </form>
    </div>
  </div>

  <!-- Editor Permissions Modal (used for assigning Editor role) -->
  <div id="editorPermissionModal" class="modal">
    <div class="modal-content" style="max-height:85vh; overflow-y:auto;">
      <div class="modal-header" style="position:sticky; top:0; background:#fff; z-index:10;"><h2>Assign Editor Permissions</h2><span class="modal-close" onclick="closeEditorPermissionModal()">&times;</span></div>
      <div id="editorPermMessage" class="modal-message default" style="display:none;"></div>
      <form id="editorPermForm" style="padding:12px;">
        <p style="margin-bottom:12px; font-size:13px; color:#666;">Select which admin features this editor can access:</p>
        <div class="form-group">
          <label><input type="checkbox" name="perm_manage_posts" id="perm_manage_posts" checked> Manage Posts &amp; Blog</label>
        </div>
        <div class="form-group">
          <label><input type="checkbox" name="perm_manage_pages" id="perm_manage_pages" checked> Manage Pages</label>
        </div>
        <div class="form-group">
          <label><input type="checkbox" name="perm_manage_products" id="perm_manage_products"> Manage Products</label>
        </div>
        <div class="form-group">
          <label><input type="checkbox" name="perm_manage_orders" id="perm_manage_orders"> Manage Orders</label>
        </div>
        <div class="form-group">
          <label><input type="checkbox" name="perm_manage_carousel" id="perm_manage_carousel"> Manage Carousel &amp; Slider</label>
        </div>
        <div class="form-group">
          <label><input type="checkbox" name="perm_manage_news" id="perm_manage_news"> Manage News</label>
        </div>
        <div class="form-group">
          <label><input type="checkbox" name="perm_manage_categories" id="perm_manage_categories"> Manage Categories</label>
        </div>
        <div class="form-group">
          <label><input type="checkbox" name="perm_manage_users" id="perm_manage_users"> Manage Users</label>
        </div>
        <div class="form-group">
          <label><input type="checkbox" name="perm_manage_seo" id="perm_manage_seo"> Manage SEO</label>
        </div>
        <div class="form-group">
          <label><input type="checkbox" name="perm_manage_settings" id="perm_manage_settings"> Manage Settings</label>
        </div>
        <div class="form-footer" style="position:sticky; bottom:0; background:#fff; padding-top:12px; border-top:1px solid #eee; margin-top:12px;">
          <button type="button" class="btn" onclick="closeEditorPermissionModal()" style="background:#999; color:#fff;">Cancel</button>
          <button type="button" class="btn" onclick="saveEditorPermissions()" style="background:#4CAF50;color:#fff;">Save Permissions</button>
        </div>
      </form>
    </div>
  </div>

</main>

<script src="admin_users_actions.js"></script>
<script>
// Pass PHP permission variables to JavaScript
const canCreate = <?php echo json_encode(!empty($canCreate) ? true : false); ?>;
const canEdit = <?php echo json_encode(!empty($canEdit) ? true : false); ?>;
const canDelete = <?php echo json_encode(!empty($canDelete) ? true : false); ?>;

function htmlEscape(s){ return String(s||'').replace(/[&<>'"]/g, c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'})[c]); }

function openAddUserModal(){ document.getElementById('addUserModal').classList.add('show'); document.getElementById('addUserForm').reset(); document.getElementById('modalMessage').innerHTML=''; }
function closeAddUserModal(){ document.getElementById('addUserModal').classList.remove('show'); }
function openEditUserModal(id){ const row = document.querySelector('input.rowCheckbox[value="'+id+'"]').closest('tr'); document.getElementById('edit_user_id').value = id; document.getElementById('edit_username').value = row.querySelector('strong').textContent.trim(); document.getElementById('edit_email').value = row.querySelectorAll('td')[3].textContent.trim(); document.getElementById('edit_password').value=''; document.getElementById('editConfirmPassword').value=''; document.getElementById('editUserModal').classList.add('show'); }
function closeEditUserModal(){ document.getElementById('editUserModal').classList.remove('show'); }

document.getElementById('addUserForm').addEventListener('submit', async function(e){ e.preventDefault(); const pw = document.getElementById('password').value; const cp = document.getElementById('confirm_password').value; if (pw!==cp){ alert('Passwords do not match'); return; } const fd=new FormData(this); try{ const res=await fetch('api_add_user.php',{method:'POST', body: fd}); const data = await res.json(); if (data.success){ alert('User created'); location.reload(); } else alert('Error: '+(data.message||'unknown')); }catch(err){ alert('Network error: '+err.message);} });

document.getElementById('editUserForm').addEventListener('submit', async function(e){ e.preventDefault(); const pw = document.getElementById('edit_password').value; const cp = document.getElementById('editConfirmPassword').value; if (pw && pw!==cp){ alert('Passwords do not match'); return; } const fd=new FormData(this); try{ const res=await fetch('api_update_user.php',{method:'POST', body: fd}); const data = await res.json(); if (data.success){ alert('Saved'); location.reload(); } else alert('Error: '+(data.message||'unknown')); }catch(err){ alert('Network error: '+err.message);} });

function toggleSelectAll(cb){ document.querySelectorAll('input.rowCheckbox').forEach(i=>i.checked=cb.checked); }
function getSelectedIds(){ return Array.from(document.querySelectorAll('input.rowCheckbox:checked')).map(i=>i.value); }
async function applyBulkAction(){ const act=document.getElementById('bulkActionSelect').value; const ids=getSelectedIds(); if (!ids.length){ alert('No users selected'); return; } if (act==='delete'){
    // skip primary admin when deleting
    const filtered = ids.filter(id=>{ const u = usersData.find(x=>String(x.id)===String(id)); return !(u && u.is_primary); });
    if (filtered.length !== ids.length){ alert('Primary admin cannot be deleted; it will be skipped.'); }
    if (!filtered.length) return;
    if (!confirm('Delete selected users?')) return; 
    for(const id of filtered){ const fd=new FormData(); fd.append('user_id', id); const res = await fetch('admin_delete_user.php',{method:'POST', body: fd}); const d = await res.json(); if (!d.success) alert('Error deleting '+id+': '+(d.message||'unknown')); } location.reload(); } }
async function applyBulkRoleChange(){
  const role=document.getElementById('bulkRoleSelect').value;
  const ids=getSelectedIds();
  if (!ids.length){ alert('No users selected'); return; }
  if (!role){ alert('Select role'); return; }

  // filter out primary admin
  const filteredIds = ids.filter(id=>{ const u = usersData.find(x=>String(x.id)===String(id)); return !(u && u.is_primary); });
  if (filteredIds.length !== ids.length){ alert('Primary admin cannot have its role changed; it will be skipped.'); }
  if (filteredIds.length === 0) return;

  // For Editor role show permissions modal first
  if (role === 'Editor') {
    return new Promise((resolve) => {
      openEditorPermissionModal(filteredIds, async function(permissions){
        const fd=new FormData(); 
        filteredIds.forEach(id=>fd.append('user_ids[]', id)); 
        fd.append('role', role);
        // append permissions as permissions[name]=value
        for (const k in permissions) fd.append('permissions['+k+']', permissions[k]);
        try {
          const res = await fetch('admin_bulk_change_role.php',{method:'POST', body: fd}); 
          const d = await res.json(); 
          if (d.success) {
            alert('Role changed successfully');
            location.reload();
          } else {
            alert('Error: '+(d.message||'unknown'));
          }
        } catch(err) {
          alert('Network error: '+err.message);
        }
        resolve();
      });
    });
  }

  if (!confirm('Change role for '+ids.length+' users to '+role+'?')) return;
  const fd=new FormData(); 
  ids.forEach(id=>fd.append('user_ids[]', id)); 
  fd.append('role', role);
  try {
    const res = await fetch('admin_bulk_change_role.php',{method:'POST', body: fd}); 
    const d = await res.json(); 
    if (d.success) {
      alert('Role changed successfully');
      location.reload();
    } else {
      alert('Error: '+(d.message||'unknown'));
    }
  } catch(err) {
    alert('Network error: '+err.message);
  }
}

/* hook into existing per-row actions in admin_users_actions.js (overridden here) */
async function handleUserAction(userId, action){
  if (!action) return;
  if (action==='view') { openViewEditModal(userId); return; }
  if (action==='edit') { openEditUserModal(userId); return; }
  if (action==='promote_admin' || action==='demote_admin'){
    if (!confirm((action==='promote_admin'?'Promote to admin?':'Remove admin rights?'))) return;
    const fd=new FormData(); fd.append('user_id', userId); fd.append('action', action==='promote_admin'?'promote':'demote'); const res=await fetch('admin_toggle_admin.php',{method:'POST', body: fd}); const d=await res.json(); if (d.success) location.reload(); else alert('Error: '+(d.message||'unknown'));
    return;
  }
  if (action==='promote_subadmin'){
    if (!confirm('Promote to sub-admin?')) return;
    const fd=new FormData(); fd.append('user_id', userId); fd.append('role', 'subadmin'); const res=await fetch('admin_promote_subadmin.php',{method:'POST', body: fd}); const d=await res.json(); if (d.success) location.reload(); else alert('Error: '+(d.message||'unknown'));
    return;
  }
  if (action==='promote_editor'){
    // open editor permission modal for single user
    openEditorPermissionModal([userId], async function(permissions){
      const fd=new FormData(); 
      fd.append('user_id', userId);
      fd.append('role', 'editor');
      for (const k in permissions) fd.append('permissions['+k+']', permissions[k]);
      try {
        const res = await fetch('admin_promote_subadmin.php',{method:'POST', body: fd}); 
        const d = await res.json(); 
        if (d.success){ 
          alert('Promoted to Editor'); 
          location.reload(); 
        } else {
          alert('Error: '+(d.message||'unknown'));
        }
      } catch(err) {
        alert('Network error: '+err.message);
      }
    });
    return;
  }
  if (action==='unpromote_subadmin'){
    if (!confirm('Remove sub-admin privileges?')) return; const fd=new FormData(); fd.append('user_id', userId); const res=await fetch('admin_unpromote_subadmin.php',{method:'POST', body: fd}); const d=await res.json(); if (d.success) { alert('Sub-admin removed'); location.reload(); } else alert('Error: '+(d.message||'unknown'));
    return;
  }
  if (action==='delete_user'){
    const u = usersData.find(x=>String(x.id)===String(userId));
    if (u && u.is_primary) { alert('Cannot delete the primary administrator'); return; }
    if (!confirm('Delete user? This cannot be undone.')) return; const fd=new FormData(); fd.append('user_id', userId); const res=await fetch('admin_delete_user.php',{method:'POST', body: fd}); const d=await res.json(); if (d.success) location.reload(); else alert('Error: '+(d.message||'unknown'));
    return;
  }
}

// Editor permission modal logic
let _editorPendingCallback = null;
function openEditorPermissionModal(userIds, callback){
  _editorPendingCallback = callback;
  // defaults: posts/pages allowed; users disabled
  document.getElementById('perm_manage_posts').checked = true;
  document.getElementById('perm_manage_pages').checked = true;
  document.getElementById('perm_manage_products').checked = false;
  document.getElementById('perm_manage_orders').checked = false;
  document.getElementById('perm_manage_carousel').checked = false;
  document.getElementById('perm_manage_news').checked = false;
  document.getElementById('perm_manage_categories').checked = false;
  document.getElementById('perm_manage_users').checked = false;
  document.getElementById('perm_manage_seo').checked = false;
  document.getElementById('perm_manage_settings').checked = false;
  document.getElementById('editorPermMessage').style.display = 'none';
  document.getElementById('editorPermissionModal').classList.add('show');
}

function saveEditorPermissions() {
  const perms = {};
  perms.manage_posts = document.getElementById('perm_manage_posts').checked ? 'editor' : 'none';
  perms.manage_pages = document.getElementById('perm_manage_pages').checked ? 'editor' : 'none';
  perms.manage_products = document.getElementById('perm_manage_products').checked ? 'editor' : 'none';
  perms.manage_orders = document.getElementById('perm_manage_orders').checked ? 'editor' : 'none';
  perms.manage_carousel = document.getElementById('perm_manage_carousel').checked ? 'editor' : 'none';
  perms.manage_news = document.getElementById('perm_manage_news').checked ? 'editor' : 'none';
  perms.manage_categories = document.getElementById('perm_manage_categories').checked ? 'editor' : 'none';
  perms.manage_users = document.getElementById('perm_manage_users').checked ? 'editor' : 'none';
  perms.manage_seo = document.getElementById('perm_manage_seo').checked ? 'editor' : 'none';
  perms.manage_settings = document.getElementById('perm_manage_settings').checked ? 'editor' : 'none';

  document.getElementById('editorPermissionModal').classList.remove('show');
  if (typeof _editorPendingCallback === 'function') {
    _editorPendingCallback(perms);
  }
}

function closeEditorPermissionModal(){ document.getElementById('editorPermissionModal').classList.remove('show'); }

// View/Edit modal functions
function openViewEditModal(id){ const u = (usersData||[]).find(x=>String(x.id)===String(id)); if (!u) { alert('User not found'); return; } document.getElementById('ve_user_id').value = u.id; document.getElementById('ve_username').value = u.username || ''; document.getElementById('ve_email').value = u.email || ''; document.getElementById('ve_name').value = u.name || ''; document.getElementById('ve_age').value = u.age || ''; document.getElementById('ve_phone').value = u.phone || ''; document.getElementById('ve_gender').value = u.gender || ''; document.getElementById('veModalMessage').style.display='none'; document.getElementById('viewEditUserModal').classList.add('show'); }
function closeViewEditModal(){ document.getElementById('viewEditUserModal').classList.remove('show'); }

document.getElementById('viewEditForm').addEventListener('submit', async function(e){ e.preventDefault(); const fd=new FormData(this); try{ const res = await fetch('api_update_user_details.php',{method:'POST', body: fd}); const d = await res.json(); if (d.success){ alert('Saved'); location.reload(); } else { document.getElementById('veModalMessage').className='modal-message error'; document.getElementById('veModalMessage').innerText = d.message || 'Error saving'; document.getElementById('veModalMessage').style.display='block'; } } catch(err){ alert('Network error: '+err.message); } });

// close modals on outside click
window.addEventListener('click', function(e){ ['addUserModal','editUserModal'].forEach(id=>{ const el=document.getElementById(id); if (el && e.target===el) el.classList.remove('show'); }); });

// Embed users data directly from PHP into JavaScript
var usersData = <?php echo json_encode($users); ?>;

// Load users from embedded PHP data (not from API)
function loadUsers() {
  const users = usersData || [];
  const tbody = document.getElementById('usersTbody'); 
  tbody.innerHTML = '';
  
  if (!users || users.length === 0) {
    tbody.innerHTML = '<tr><td colspan="7" style="text-align:center; color:#666;">No users found. Click "Add User" to create one.</td></tr>';
    return;
  }
  
  // Populate table with users
  for (const u of users) {
    const tr = document.createElement('tr');
    tr.innerHTML = `
      <td><input type="checkbox" class="rowCheckbox" value="${u.id}" ${u.is_primary ? 'disabled' : ''}></td>
      <td style="white-space:nowrap;"><strong>${htmlEscape(u.username)}</strong>${u.is_primary ? ' <span style="color:#c00;font-size:90%;">(Primary)</span>' : ''}</td>

   
      
     <td>${htmlEscape(u.email || '')}</td>
      <td id="role-${u.id}">${u.is_admin ? 'Administrator' : (u.is_editor ? 'Editor' : (u.is_subadmin ? 'Sub-admin' : 'User'))}</td>
      
     
     
      <td>
        <select onchange="handleUserAction(${u.id}, this.value); this.value='';" style="padding:6px; border-radius:6px; border:1px solid #ddd; cursor:pointer;">
        <option value="">-- Action --</option>
        ${canEdit? '<option value="view">View</option><option value="edit">Edit</option>':''}
        ${canCreate? '<option value="promote_editor">Promote to Editor</option>':''}
        ${canCreate? '<option value="promote_subadmin">Promote to Sub-admin</option>':''}
        ${u.is_subadmin && canEdit? '<option value="unpromote_subadmin">Remove Sub-admin</option>':''}
        ${canDelete && !u.is_primary? '<option value="delete_user">Delete User</option>':'<option disabled>Delete (Not Allowed)</option>'}
        </select>
      </td>
    `;
    tbody.appendChild(tr);
  }
}

// start loading users
loadUsers();
</script>
</body>
</html>