<?php
require_once __DIR__ . '/config/config.php';
require_role(['admin']);

$roles = ['superadmin','admin','hr','audit','gm','accounts','manager','staff','supervisor','opm'];
$departments = $pdo->query("SELECT * FROM departments ORDER BY name")->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['form_action'] ?? '';

    if ($action === 'create') {
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';
        $email = trim($_POST['email'] ?? '');
        $role = $_POST['role'] ?? 'staff';
        $dept = $_POST['department_id'] ?: null;
        $canAdd = isset($_POST['can_add_staff']) ? 1 : 0;

        if ($username === '' || $password === '') {
            flash('error', 'Username and password are required.');
        } else {
            $hash = password_hash($password, PASSWORD_DEFAULT);
            try {
                $pdo->prepare("INSERT INTO users (username, password, email, role, department_id, must_change_password, can_add_staff)
                               VALUES (?,?,?,?,?,1,?)")
                    ->execute([$username, $hash, $email ?: null, $role, $dept, $canAdd]);
                flash('success', 'User created. They must change their password on first login.');
            } catch (PDOException $ex) {
                flash('error', 'Could not create user (username may already exist).');
            }
        }
    } elseif ($action === 'update') {
        $id = $_POST['id'];
        $email = trim($_POST['email'] ?? '');
        $role = $_POST['role'];
        $dept = $_POST['department_id'] ?: null;
        $canAdd = isset($_POST['can_add_staff']) ? 1 : 0;
        $pdo->prepare("UPDATE users SET email=?, role=?, department_id=?, can_add_staff=? WHERE id=?")
            ->execute([$email ?: null, $role, $dept, $canAdd, $id]);
        flash('success', 'User updated.');
    } elseif ($action === 'reset_password') {
        $id = $_POST['id'];
        $newPass = 'welcome123'; // default reset password
        $hash = password_hash($newPass, PASSWORD_DEFAULT);
        $pdo->prepare("UPDATE users SET password=?, must_change_password=1 WHERE id=?")->execute([$hash, $id]);
        flash('success', "Password reset to '$newPass'. User must change it at next login.");
    }
    redirect('users.php');
}

$edit = null;
if (isset($_GET['edit'])) {
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id=?");
    $stmt->execute([$_GET['edit']]);
    $edit = $stmt->fetch();
}

$users = $pdo->query("SELECT u.*, d.name dept_name FROM users u LEFT JOIN departments d ON d.id=u.department_id ORDER BY u.username")->fetchAll();

$pageTitle = 'Users';
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-6">Users & Roles</h1>

<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
  <div class="md:col-span-1 bg-white rounded-xl shadow-sm border border-slate-200 p-5 h-fit">
    <h2 class="font-semibold mb-4"><?= $edit ? 'Edit User' : 'Add User' ?></h2>
    <form method="POST" class="space-y-3">
      <input type="hidden" name="form_action" value="<?= $edit ? 'update' : 'create' ?>">
      <?php if ($edit): ?><input type="hidden" name="id" value="<?= $edit['id'] ?>"><?php endif; ?>
      <?php if (!$edit): ?>
        <input name="username" required placeholder="Username" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
        <input type="password" name="password" required placeholder="Temporary password" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      <?php else: ?>
        <p class="text-sm text-slate-600">Username: <span class="font-medium"><?= e($edit['username']) ?></span></p>
      <?php endif; ?>
      <input type="email" name="email" placeholder="Email (for notifications)" value="<?= e($edit['email'] ?? '') ?>" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
      <select name="role" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
        <?php foreach ($roles as $r): ?>
          <option value="<?= $r ?>" <?= ($edit['role'] ?? '')===$r?'selected':'' ?>><?= ucfirst($r) ?></option>
        <?php endforeach; ?>
      </select>
      <select name="department_id" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
        <option value="">-- Department --</option>
        <?php foreach ($departments as $d): ?>
          <option value="<?= $d['id'] ?>" <?= ($edit['department_id'] ?? null)==$d['id']?'selected':'' ?>><?= e($d['name']) ?></option>
        <?php endforeach; ?>
      </select>
      <label class="flex items-center gap-2 text-sm">
        <input type="checkbox" name="can_add_staff" <?= !empty($edit['can_add_staff']) ? 'checked' : '' ?>>
        Can add staff
      </label>
      <button class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-4 py-2 rounded-lg w-full">
        <?= $edit ? 'Update User' : 'Create User' ?>
      </button>
      <?php if ($edit): ?><a href="users.php" class="block text-center text-sm text-slate-500">Cancel</a><?php endif; ?>
    </form>
  </div>

  <div class="md:col-span-2 bg-white rounded-xl shadow-sm border border-slate-200">
    <div class="overflow-x-auto"><table class="w-full text-sm">
      <thead class="bg-slate-50 text-slate-500 text-xs uppercase"><tr>
        <th class="text-left px-5 py-2">Username</th><th class="text-left px-5 py-2">Email</th><th class="text-left px-5 py-2">Role</th>
        <th class="text-left px-5 py-2">Department</th><th class="text-right px-5 py-2">Actions</th></tr></thead>
      <tbody>
      <?php foreach ($users as $us): ?>
        <tr class="border-t border-slate-100">
          <td class="px-5 py-2.5"><?= e($us['username']) ?></td>
          <td class="px-5 py-2.5 text-slate-500"><?= e($us['email'] ?? '—') ?></td>
          <td class="px-5 py-2.5 capitalize"><?= e($us['role']) ?></td>
          <td class="px-5 py-2.5"><?= e($us['dept_name'] ?? '—') ?></td>
          <td class="px-5 py-2.5 text-right space-x-3">
            <a href="?edit=<?= $us['id'] ?>" class="text-blue-600 hover:underline">Edit</a>
            <form method="POST" class="inline" onsubmit="return confirm('Reset password to the default?')">
              <input type="hidden" name="form_action" value="reset_password">
              <input type="hidden" name="id" value="<?= $us['id'] ?>">
              <button type="submit" class="text-amber-600 hover:underline">Reset Password</button>
            </form>
          </td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table></div>
  </div>
</div>
<?php include __DIR__ . '/includes/footer.php'; ?>
