<?php
require_once __DIR__.'/../includes/auth.php';
ec_require_min_role('admin');

$db = ec_db(); if (!$db) die('DB connection failed');
function h($s){ return htmlspecialchars((string)$s, ENT_QUOTES, 'UTF-8'); }

$action = $_POST['action'] ?? $_GET['action'] ?? null;

/* ---------- helpers ---------- */
function branch_name_by_id(mysqli $db, ?int $bid): ?string {
  if (!$bid) return null;
  $st=$db->prepare("SELECT name FROM branches WHERE id=? LIMIT 1");
  $st->bind_param('i',$bid);
  $st->execute();
  $res=$st->get_result();
  $row = $res ? $res->fetch_assoc() : null;
  $st->close();
  return $row['name'] ?? null;
}

function email_exists(mysqli $db, string $email, int $excludeId=0): bool {
  $st=$db->prepare("SELECT 1 AS x FROM users WHERE email=? AND id<>? LIMIT 1");
  $st->bind_param('si',$email,$excludeId);
  $st->execute();
  $res=$st->get_result();
  $row=$res ? $res->fetch_assoc() : null;
  $st->close();
  return (bool)$row;
}


/* ---------- API: roles list ---------- */
if ($action==='roles') {
  $rs=$db->query("SELECT slug,name FROM roles ORDER BY id");
  $out=[]; while($r=$rs->fetch_assoc()) $out[]=$r;
  header('Content-Type: application/json'); echo json_encode($out); exit;
}

/* ---------- API: branches list ---------- */
if ($action==='branches') {
  // Detect if branches.active exists; if not, don't filter by it.
  $hasActive = false;
  try {
    $chk = $db->query("SELECT 1 FROM INFORMATION_SCHEMA.COLUMNS
                       WHERE TABLE_SCHEMA = DATABASE()
                         AND TABLE_NAME = 'branches'
                         AND COLUMN_NAME = 'active' LIMIT 1");
    $hasActive = (bool)$chk->fetch_row();
  } catch (Throwable $e) { /* ignore */ }

  $sql = $hasActive
    ? "SELECT id,name FROM branches WHERE active=1 OR active IS NULL ORDER BY name"
    : "SELECT id,name FROM branches ORDER BY name";

  $rs = $db->query($sql);
  $out = [];
  while ($r = $rs->fetch_assoc()) $out[] = $r;
  header('Content-Type: application/json');
  echo json_encode($out);
  exit;
}


/* ---------- API: table fetch ---------- */
if ($action==='fetch') {
  // join to show branch name reliably (prefer users.branch_name, fallback to branches.name)
  $sql="SELECT u.id,u.name,u.email,u.role_slug,u.active,u.avatar_url,u.created_at,
               u.branch_id, COALESCE(u.branch_name, b.name) AS branch_name
        FROM users u
        LEFT JOIN branches b ON b.id=u.branch_id
        ORDER BY u.id DESC";
  $rs=$db->query($sql);
  echo '<div class="table-responsive"><table class="table table-hover align-middle" id="usersTbl"><thead class="table-light"><tr>
        <th>Avatar</th><th>Name</th><th>Email</th><th>Role</th><th>Branch</th><th>Active</th><th>Created</th><th>Action</th>
        </tr></thead><tbody>';
  while($u=$rs->fetch_assoc()){
    $av = (isset($u['avatar_url']) && $u['avatar_url'] !== '' && $u['avatar_url'] !== '0')
          ? $u['avatar_url'] : '/edenrms/assets/img/avatar-default.png';
    $badge = $u['active']?'<span class="badge bg-success">Yes</span>':'<span class="badge bg-secondary">No</span>';
    $branch = $u['branch_id'] ? ('<span class="badge text-bg-info">'.h((string)$u['branch_name']).'</span>') : '<span class="text-muted">—</span>';
    echo '<tr>
      <td><img src="'.h($av).'" style="width:36px;height:36px;border-radius:50%;object-fit:cover"></td>
      <td>'.h($u['name']).'</td>
      <td>'.h($u['email']).'</td>
      <td><span class="badge text-bg-primary">'.h($u['role_slug']).'</span></td>
      <td>'.$branch.'</td>
      <td>'.$badge.'</td>
      <td>'.h($u['created_at']).'</td>
      <td class="d-flex gap-2">
        <button class="btn btn-sm btn-outline-primary" onclick="openEdit('.(int)$u['id'].')"><i class="bi bi-pencil"></i></button>
        <button class="btn btn-sm btn-outline-warning" onclick="openReset('.(int)$u['id'].')"><i class="bi bi-key"></i></button>
        <button class="btn btn-sm btn-outline-danger" onclick="delUser('.(int)$u['id'].')"><i class="bi bi-trash"></i></button>
      </td>
    </tr>';
  }
  echo '</tbody></table></div>'; exit;
}

/* ---------- API: get one ---------- */
if ($action==='get') {
  $id=(int)($_GET['id']??0);
  $st=$db->prepare("SELECT id,name,email,role_slug,avatar_url,active,branch_id,branch_name FROM users WHERE id=?");
  $st->bind_param('i',$id); $st->execute();
  $row=$st->get_result()->fetch_assoc(); $st->close();
  header('Content-Type: application/json'); echo json_encode($row?:[]); exit;
}

/* ---------- API: save (insert/update) ---------- */
if ($action==='save') {
  $id=(int)($_POST['id']??0);
  $name=trim($_POST['name']??'');
  $email=trim($_POST['email']??'');
  $role=trim($_POST['role_slug']??'staff');
  $active=(int)($_POST['active']??1);
  $avatar=trim($_POST['avatar_url']??'');
  $pwd=$_POST['password']??'';
  $branch_id = ($_POST['branch_id'] ?? '') !== '' ? (int)$_POST['branch_id'] : null;

  if ($name===''){ http_response_code(400); echo 'Name required'; exit; }
  if ($email===''){ http_response_code(400); echo 'Email required'; exit; }
  if (email_exists($db,$email,$id)){ http_response_code(409); echo 'Email already exists'; exit; }

  // denormalized copy for quick reads
  $branch_name = $branch_id ? branch_name_by_id($db, $branch_id) : null;

  if ($id===0){
    if($pwd===''){ http_response_code(400); echo 'Password required'; exit; }
    $hash=password_hash($pwd,PASSWORD_DEFAULT);
    $st=$db->prepare("INSERT INTO users
        (name,email,role_slug,password_hash,avatar_url,active,branch_id,branch_name)
        VALUES (?,?,?,?,?,?,?,?)");
    // name(s), email(s), role(s), pass(s), avatar(s), active(i), branch_id(i or NULL), branch_name(s or NULL)
    $st->bind_param('sssssiis',$name,$email,$role,$hash,$avatar,$active,$branch_id,$branch_name);
    $st->execute();
    $st->close();
    echo 'OK'; exit;
  }

  // UPDATE
  if($pwd!==''){
    $hash=password_hash($pwd,PASSWORD_DEFAULT);
    $st=$db->prepare("UPDATE users
                      SET name=?,email=?,role_slug=?,password_hash=?,avatar_url=?,active=?,branch_id=?,branch_name=?
                      WHERE id=?");
    // s s s s s i i s i  => 'sssssiisi'
    $st->bind_param('sssssiisi',$name,$email,$role,$hash,$avatar,$active,$branch_id,$branch_name,$id);
  } else {
    $st=$db->prepare("UPDATE users
                      SET name=?,email=?,role_slug=?,avatar_url=?,active=?,branch_id=?,branch_name=?
                      WHERE id=?");
    // s s s s i i s i  => 'ssssiisi'
    $st->bind_param('ssssiisi',$name,$email,$role,$avatar,$active,$branch_id,$branch_name,$id);
  }
  $st->execute(); $st->close(); echo 'OK'; exit;
}


/* ---------- API: reset password ---------- */
if ($action==='reset') {
  $id=(int)($_POST['id']??0); $pwd=$_POST['password']??'';
  if($id<=0||$pwd===''){ http_response_code(400); echo 'Missing'; exit; }
  $hash=password_hash($pwd,PASSWORD_DEFAULT);
  $st=$db->prepare("UPDATE users SET password_hash=? WHERE id=?");
  $st->bind_param('si',$hash,$id); $st->execute(); $st->close(); echo 'OK'; exit;
}

/* ---------- API: delete ---------- */
if ($action==='delete') {
  $id=(int)($_POST['id']??0);
  if ($id === (int)($_SESSION['user']['id'] ?? 0)) { http_response_code(400); echo 'Cannot delete yourself'; exit; }
  $st=$db->prepare("DELETE FROM users WHERE id=?"); $st->bind_param('i',$id); $st->execute(); $st->close(); echo 'OK'; exit;
}

/* ---------- View ---------- */
$ACTIVE='users';
require_once __DIR__.'/../includes/header.php';
require_once __DIR__.'/../includes/sidebar.php';
?>
<main class="ec-main">
<div class="container-fluid py-4">
  <div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="mb-0">Users</h4>
    <button class="btn btn-primary" id="btnAdd"><i class="bi bi-plus-circle me-1"></i>Add User</button>
  </div>
  <div id="usersWrap"><div class="p-4 text-muted text-center">Loading…</div></div>
</div>

<!-- Add/Edit Modal -->
<div class="modal fade" id="userModal" tabindex="-1">
  <div class="modal-dialog">
    <form class="modal-content" id="userForm">
      <div class="modal-header"><h5 class="modal-title" id="umTitle">Add User</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <input type="hidden" name="id" id="u_id">
        <div class="mb-2"><label class="form-label">Name</label><input class="form-control" name="name" id="u_name" required></div>
        <div class="mb-2"><label class="form-label">Email</label><input type="email" class="form-control" name="email" id="u_email" required></div>

        <div class="row g-2">
          <div class="col-md-6">
            <label class="form-label">Role</label>
            <select class="form-select" name="role_slug" id="u_role" required></select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Branch</label>
            <select class="form-select" name="branch_id" id="u_branch">
              <option value="">— No branch —</option>
            </select>
          </div>
        </div>

        <div class="mb-2">
          <label class="form-label">Password <small class="text-muted">(blank = keep)</small></label>
          <input type="password" class="form-control" name="password" id="u_pwd">
        </div>

        <div class="row g-2">
          <div class="col-8"><label class="form-label">Avatar URL</label><input class="form-control" name="avatar_url" id="u_avatar"></div>
          <div class="col-4 d-flex align-items-end">
            <div class="form-check ms-2"><input class="form-check-input" type="checkbox" id="u_active" checked><label class="form-check-label" for="u_active">Active</label></div>
          </div>
        </div>
      </div>
      <div class="modal-footer"><button class="btn btn-success" type="submit">Save</button><button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Cancel</button></div>
    </form>
  </div>
</div>

<!-- Reset Password Modal -->
<div class="modal fade" id="pwdModal" tabindex="-1">
  <div class="modal-dialog">
    <form class="modal-content" id="pwdForm">
      <div class="modal-header"><h5 class="modal-title">Reset Password</h5><button class="btn-close" data-bs-dismiss="modal"></button></div>
      <div class="modal-body">
        <input type="hidden" id="rp_id">
        <label class="form-label">New Password</label>
        <input type="password" id="rp_pwd" class="form-control" required>
      </div>
      <div class="modal-footer"><button class="btn btn-warning" type="submit">Set New Password</button><button class="btn btn-secondary" type="button" data-bs-dismiss="modal">Cancel</button></div>
    </form>
  </div>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>

<script>
// Debug any AJAX issues in console
$(document).ajaxError(function(event, jqxhr, settings, thrown){
  console.error('AJAX error:', settings && settings.url, jqxhr && jqxhr.status, thrown, jqxhr && jqxhr.responseText);
});

// Safe GET JSON helper (never throws)
function safeJSON(url, data){
  return $.ajax({ url, data, dataType:'json' })
    .then(res => res)
    .catch(err => {
      console.warn('safeJSON error', url, err);
      return null; // signal failure
    });
}

function populateRoles(list){
  const $s = $('#u_role').empty();
  if (Array.isArray(list) && list.length){
    list.forEach(r => $s.append(`<option value="${r.slug}">${r.name}</option>`));
  } else {
    $s.append('<option value="staff">staff</option>');
  }
}

function populateBranches(list){
  const $s = $('#u_branch').empty().append('<option value="">— No branch —</option>');
  if (Array.isArray(list) && list.length){
    list.forEach(b => $s.append(`<option value="${b.id}">${b.name}</option>`));
  }
}

function loadUsers(){
  $.post('users.php', {action:'fetch'})
    .done(html => $('#usersWrap').html(html))
    .fail(x => alert('Load users failed:\n' + x.responseText));
}

// --- Add button: OPEN FIRST, then fill dropdowns ---
$('#btnAdd').on('click', async function(){
  $('#umTitle').text('Add User');
  $('#userForm')[0].reset();
  $('#u_id').val('');
  $('#u_active').prop('checked', true);

  const modal = new bootstrap.Modal(document.getElementById('userModal'));
  modal.show();

  const [roles, branches] = await Promise.all([
    safeJSON('users.php', {action:'roles'}),
    safeJSON('users.php', {action:'branches'})
  ]);
  populateRoles(roles);
  populateBranches(branches);

  const msgs = [];
  if (roles === null) msgs.push('Could not load Roles (check PHP errors or auth).');
  if (branches === null) msgs.push('Could not load Branches (check PHP errors or auth).');
  if (msgs.length) alert(msgs.join('\n'));
}); // <-- this closing brace was missing

// --- Edit flow (loads roles, branches, and user) ---
async function openEdit(id){
  const modalEl = document.getElementById('userModal');
  const modal = new bootstrap.Modal(modalEl);

  $('#umTitle').text('Edit User');
  $('#userForm')[0].reset();
  $('#u_id').val('');
  $('#u_active').prop('checked', true);
  modal.show();

  const [roles, branches, u] = await Promise.all([
    safeJSON('users.php', {action:'roles'}),
    safeJSON('users.php', {action:'branches'}),
    safeJSON('users.php', {action:'get', id})
  ]);
  populateRoles(roles);
  populateBranches(branches);

  if (u){
    $('#u_id').val(u.id||'');
    $('#u_name').val(u.name||'');
    $('#u_email').val(u.email||'');
    $('#u_role').val(u.role_slug||'staff');
    $('#u_avatar').val(u.avatar_url||'');
    $('#u_active').prop('checked', (u.active||0)==1);
    $('#u_branch').val(u.branch_id || '');
    $('#u_pwd').val('');
  } else {
    alert('Could not load user details.');
  }
}

// Save (insert/update)
$('#userForm').on('submit', function(e){
  e.preventDefault();
  const d = $(this).serializeArray().reduce((o,i)=>(o[i.name]=i.value,o),{});
  d.active = $('#u_active').is(':checked') ? 1 : 0;
  d.action = 'save';
  $.post('users.php', d)
    .done(() => {
      bootstrap.Modal.getInstance(document.getElementById('userModal')).hide();
      loadUsers();
    })
    .fail(x => alert('Save failed:\n' + x.responseText));
});

// Reset password
function openReset(id){
  $('#rp_id').val(id);
  $('#rp_pwd').val('');
  new bootstrap.Modal(document.getElementById('pwdModal')).show();
}
$('#pwdForm').on('submit', function(e){
  e.preventDefault();
  $.post('users.php', {action:'reset', id:$('#rp_id').val(), password:$('#rp_pwd').val()})
    .done(() => bootstrap.Modal.getInstance(document.getElementById('pwdModal')).hide())
    .fail(x => alert('Reset failed:\n' + x.responseText));
});

// Delete
function delUser(id){
  if(!confirm('Delete this user?')) return;
  $.post('users.php', {action:'delete', id})
    .done(loadUsers)
    .fail(x => alert('Delete failed:\n' + x.responseText));
}

// initial load
$(loadUsers);
</script>




</main></div>
</body></html>
