<?php
require_once __DIR__ . '/../includes/auth.php';
requireLogin();
requirePermission('users.manage');

require_once __DIR__ . '/../config/database.php';

/* =============================
   FETCH ROLES
============================= */

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

$message = "";
$error = "";

/* =============================
   HANDLE SUBMISSION
============================= */

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $full_name = trim($_POST['full_name']);
    $email     = trim($_POST['email']);
    $password  = $_POST['password'];
    $role_id   = (int)$_POST['role_id'];
    $status    = $_POST['status'];

    if (!$full_name || !$email || !$password || !$role_id) {
        $error = "All required fields must be completed.";
    } else {

        // Check duplicate email
        $check = $pdo->prepare("SELECT id FROM users WHERE email = ?");
        $check->execute([$email]);

        if ($check->rowCount() > 0) {
            $error = "Email already exists.";
        } else {

            $password_hash = password_hash($password, PASSWORD_DEFAULT);

            $insert = $pdo->prepare("
                INSERT INTO users (full_name, email, password_hash, role_id, status)
                VALUES (?, ?, ?, ?, ?)
            ");

            $insert->execute([
                $full_name,
                $email,
                $password_hash,
                $role_id,
                $status
            ]);

            $message = "User created successfully.";
        }
    }
}

/* =============================
   LOAD MASTER LAYOUT
============================= */

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

<div class="main-content">

    <div class="page-header">
        <h2>Add New User</h2>
        <p class="page-subtitle">
            Create system users with role-based access.
        </p>
    </div>

    <?php if ($error): ?>
        <div class="alert error"><?= $error ?></div>
    <?php endif; ?>

    <?php if ($message): ?>
        <div class="alert success"><?= $message ?></div>
    <?php endif; ?>

    <div class="card-form">

        <form method="POST">

            <label>Full Name *</label>
            <input type="text" name="full_name" required>

            <label>Email *</label>
            <input type="email" name="email" required>

            <label>Password *</label>
            <input type="password" name="password" required>

            <label>Role *</label>
            <select name="role_id" required>
                <option value="">Select Role</option>
                <?php foreach ($roles as $role): ?>
                    <option value="<?= $role['id'] ?>">
                        <?= htmlspecialchars($role['name']) ?>
                    </option>
                <?php endforeach; ?>
            </select>

            <label>Status</label>
            <select name="status">
                <option value="ACTIVE">ACTIVE</option>
                <option value="SUSPENDED">SUSPENDED</option>
            </select>

            <button type="submit" class="btn-primary">
                Create User
            </button>

        </form>

    </div>

</div>

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