<?php
// public/users.php
require_once __DIR__ . '/../helpers/auth.php';
require_role(['admin']);

$pdo = db();
$title = "Users - IMS";

function post_str(string $k): string { return trim((string)($_POST[$k] ?? '')); }
function post_int(string $k): int { return (int)($_POST[$k] ?? 0); }

$error = '';
$success = '';

// Load roles
$roles = $pdo->query("SELECT id, name FROM roles ORDER BY name ASC")->fetchAll();

// ---------------------------
// Create user
// ---------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'create') {
    $role_id = post_int('role_id');
    $full_name = post_str('full_name');
    $username = post_str('username');
    $email = post_str('email');
    $phone = post_str('phone');
    $password = (string)($_POST['password'] ?? '');
    $is_active = isset($_POST['is_active']) ? 1 : 0;

    if ($role_id <= 0 || $full_name === '' || $username === '' || $password === '') {
        $error = "Role, Full Name, Username, and Password are required.";
    } elseif (strlen($password) < 6) {
        $error = "Password must be at least 6 characters.";
    } else {
        try {
            // Optional: restrict creation to staff/driver only
            // If you want that, uncomment below:
            /*
            $roleNameStmt = $pdo->prepare("SELECT name FROM roles WHERE id=:id LIMIT 1");
            $roleNameStmt->execute([':id'=>$role_id]);
            $roleName = $roleNameStmt->fetchColumn();
            if (!in_array($roleName, ['staff','driver'], true)) {
                $error = "You can only create staff or driver accounts.";
            }
            */

            if ($error === '') {
                $hash = password_hash($password, PASSWORD_DEFAULT);

                $stmt = $pdo->prepare("
                    INSERT INTO users (role_id, full_name, username, email, phone, password_hash, is_active)
                    VALUES (:role_id, :full_name, :username, :email, :phone, :hash, :is_active)
                ");
                $stmt->execute([
                    ':role_id' => $role_id,
                    ':full_name' => $full_name,
                    ':username' => $username,
                    ':email' => ($email !== '' ? $email : null),
                    ':phone' => ($phone !== '' ? $phone : null),
                    ':hash' => $hash,
                    ':is_active' => $is_active
                ]);

                $success = "User created successfully.";
            }
        } catch (PDOException $e) {
            $error = "Error creating user: " . $e->getMessage();
        }
    }
}

// ---------------------------
// Toggle active
// ---------------------------
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'toggle') {
    $id = post_int('id');
    $new_active = post_int('is_active');

    if ($id <= 0 || !in_array($new_active, [0,1], true)) {
        $error = "Invalid request.";
    } else {
        try {
            $stmt = $pdo->prepare("UPDATE users SET is_active = :a WHERE id = :id LIMIT 1");
            $stmt->execute([':a' => $new_active, ':id' => $id]);
            $success = "User updated.";
        } catch (PDOException $e) {
            $error = "Error updating user: " . $e->getMessage();
        }
    }
}

// Fetch users list
$users = $pdo->query("
  SELECT u.id, u.full_name, u.username, u.email, u.phone, u.is_active, u.created_at,
         r.name AS role_name
  FROM users u
  JOIN roles r ON r.id = u.role_id
  ORDER BY u.created_at DESC
")->fetchAll();

require_once __DIR__ . '/../templates/header.php';
require_once __DIR__ . '/../templates/sidebar.php';
?>

<main class="col-12 col-md-9 col-lg-10 p-3 p-md-4">
  <h4 class="mb-3">Users</h4>

  <?php if ($error !== ''): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
  <?php endif; ?>

  <?php if ($success !== ''): ?>
    <div class="alert alert-success"><?= htmlspecialchars($success) ?></div>
  <?php endif; ?>

  <div class="row g-3">
    <!-- Create User -->
    <div class="col-12 col-lg-4">
      <div class="card shadow-sm">
        <div class="card-body">
          <h5 class="card-title mb-3">Create User</h5>

          <form method="POST" autocomplete="off">
            <input type="hidden" name="action" value="create">

            <div class="mb-2">
              <label class="form-label">Role *</label>
              <select class="form-select" name="role_id" required>
                <option value="0">-- Select role --</option>
                <?php foreach ($roles as $r): ?>
                  <option value="<?= (int)$r['id'] ?>"><?= htmlspecialchars($r['name']) ?></option>
                <?php endforeach; ?>
              </select>
            </div>

            <div class="mb-2">
              <label class="form-label">Full Name *</label>
              <input class="form-control" name="full_name" required>
            </div>

            <div class="mb-2">
              <label class="form-label">Username *</label>
              <input class="form-control" name="username" required>
            </div>

            <div class="mb-2">
              <label class="form-label">Email</label>
              <input class="form-control" name="email" type="email">
            </div>

            <div class="mb-2">
              <label class="form-label">Phone</label>
              <input class="form-control" name="phone">
            </div>

            <div class="mb-2">
              <label class="form-label">Password *</label>
              <input class="form-control" name="password" type="password" required>
              <div class="form-text">Min 6 chars</div>
            </div>

            <div class="form-check mb-3">
              <input class="form-check-input" type="checkbox" name="is_active" id="is_active" checked>
              <label class="form-check-label" for="is_active">Active</label>
            </div>

            <button class="btn btn-primary w-100" type="submit">Create</button>
          </form>
        </div>
      </div>
    </div>

    <!-- Users Table -->
    <div class="col-12 col-lg-8">
      <div class="card shadow-sm">
        <div class="card-body">
          <h6 class="mb-3">User List</h6>

          <div class="table-responsive">
            <table class="table table-sm align-middle">
              <thead>
                <tr>
                  <th>Name</th>
                  <th>Username</th>
                  <th>Role</th>
                  <th>Active</th>
                  <th>Created</th>
                  <th style="width:160px;"></th>
                </tr>
              </thead>
              <tbody>
                <?php if (!$users): ?>
                  <tr><td colspan="6" class="text-muted">No users yet.</td></tr>
                <?php else: ?>
                  <?php foreach ($users as $u): ?>
                    <tr>
                      <td><?= htmlspecialchars($u['full_name']) ?></td>
                      <td><?= htmlspecialchars($u['username']) ?></td>
                      <td><span class="badge text-bg-secondary"><?= htmlspecialchars($u['role_name']) ?></span></td>
                      <td><?= ((int)$u['is_active'] === 1) ? '✅' : '❌' ?></td>
                      <td class="text-muted small"><?= htmlspecialchars($u['created_at']) ?></td>
                      <td class="text-end">
                        <form method="POST" class="d-inline">
                          <input type="hidden" name="action" value="toggle">
                          <input type="hidden" name="id" value="<?= (int)$u['id'] ?>">
                          <?php if ((int)$u['is_active'] === 1): ?>
                            <input type="hidden" name="is_active" value="0">
                            <button class="btn btn-outline-warning btn-sm" type="submit">Deactivate</button>
                          <?php else: ?>
                            <input type="hidden" name="is_active" value="1">
                            <button class="btn btn-outline-success btn-sm" type="submit">Activate</button>
                          <?php endif; ?>
                        </form>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                <?php endif; ?>
              </tbody>
            </table>
          </div>

          <div class="text-muted small">
            Next improvement: edit user + reset password + audit logs.
          </div>
        </div>
      </div>
    </div>
  </div>
</main>

<?php require_once __DIR__ . '/../templates/footer.php'; ?>
