<?php
// admin/add_user.php
session_start();
$projectRoot = dirname(__DIR__); 
require_once $projectRoot . '/config/database.php';
require_once $projectRoot . '/config/config.php';

// --- AUTH CHECK ---
// Both admin and subadmin can access, but logic below limits subadmin power
if (!isset($_SESSION['role']) || !in_array($_SESSION['role'], ['admin', 'subadmin'])) {
    header("Location: ../auth/login.php");
    exit();
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $fullname = clean($_POST['fullname']);
    $email = clean($_POST['email']);
    $password = password_hash($_POST['password'], PASSWORD_DEFAULT);
    $role = $_POST['role'];

    // Security: Prevent Sub-Admin from creating an Admin or Sub-Admin via request tampering
    if ($_SESSION['role'] == 'subadmin' && ($role == 'admin' || $role == 'subadmin')) {
        $error = "Security Violation: You do not have permission to create administrative accounts.";
    } else {
        $stmt = $pdo->prepare("INSERT INTO users (fullname, email, password, role) VALUES (?, ?, ?, ?)");
        if ($stmt->execute([$fullname, $email, $password, $role])) {
            $success = "User created successfully!";
        } else {
            $error = "Failed to create user.";
        }
    }
}
?>

<div class="form-group">
    <label>Full Name</label>
    <input type="text" name="fullname" required class="form-control">
</div>

<div class="form-group">
    <label>Email Address</label>
    <input type="email" name="email" required class="form-control">
</div>

<div class="form-group">
    <label>User Role</label>
    <select name="role" class="form-control" required>
        <option value="teacher">Teacher</option>
        
        <?php if ($_SESSION['role'] == 'admin'): ?>
            <option value="subadmin">Sub-Admin (Operations & Results)</option>
            <option value="admin">Super Admin (Full Access)</option>
        <?php endif; ?>
    </select>
</div>