<?php
// school_admission/public/admin_add_user.php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once __DIR__ . '/../config/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth_check.php';

requireRole(['super_admin']); // Only Super Admin can access this page

$message = '';
$branches = [];

// Fetch branches for branch_admin role
$branch_result = $conn->query("SELECT branch_id, branch_name FROM branches ORDER BY branch_name ASC");
if ($branch_result) {
    while ($row = $branch_result->fetch_assoc()) {
        $branches[] = $row;
    }
    $branch_result->free();
} else {
    $message .= "<div class='message error'>Error fetching branches: " . $conn->error . "</div>";
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $username = sanitize_input($_POST['username']);
    $email = sanitize_input($_POST['email']);
    $password = $_POST['password']; // Not sanitized, will be hashed
    $role = sanitize_input($_POST['role']);
    $branch_id = null;

    if ($role === 'branch_admin' && isset($_POST['branch_id'])) {
        $branch_id = (int)$_POST['branch_id'];
    }

    if (empty($username) || empty($email) || empty($password) || empty($role) || ($role === 'branch_admin' && $branch_id === 0)) {
        $message = "<div class='message error'>All required fields must be filled, and a branch selected for Branch Admin.</div>";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $message = "<div class='message error'>Please enter a valid email address.</div>";
    } else {
        // Check for duplicate username or email
        $stmt_check = $conn->prepare("SELECT user_id FROM users WHERE username = ? OR email = ?");
        $stmt_check->bind_param("ss", $username, $email);
        $stmt_check->execute();
        $stmt_check->store_result();

        if ($stmt_check->num_rows > 0) {
            $message = "<div class='message error'>Username or Email already exists.</div>";
        } else {
            $hashed_password = password_hash($password, PASSWORD_DEFAULT);

            $stmt = $conn->prepare("INSERT INTO users (username, email, password, role, branch_id) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("ssssi", $username, $email, $hashed_password, $role, $branch_id);

            if ($stmt->execute()) {
                $_SESSION['message'] = "<div class='message success'>User <strong>" . htmlspecialchars($username) . "</strong> added successfully!</div>";
                redirect('admin_manage_users.php');
            } else {
                $message = "<div class='message error'>Error adding user: " . $stmt->error . "</div>";
            }
            $stmt->close();
        }
        $stmt_check->close();
    }
}

include __DIR__ . '/../includes/header.php';
?>

<h2 class="mt-30">Add New User</h2>

<?php if (!empty($message)): ?>
    <?php echo $message; ?>
<?php endif; ?>

<form action="admin_add_user.php" method="POST">
    <div class="form-group">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" required value="<?php echo isset($_POST['username']) ? htmlspecialchars($_POST['username']) : ''; ?>">
    </div>
    <div class="form-group">
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>">
    </div>
    <div class="form-group">
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" required>
    </div>
    <div class="form-group">
        <label for="role">Role:</label>
        <select id="role" name="role" required onchange="toggleBranchSelection()">
            <option value="">Select Role</option>
            <option value="super_admin" <?php echo (isset($_POST['role']) && $_POST['role'] == 'super_admin') ? 'selected' : ''; ?>>Super Admin</option>
            <option value="branch_admin" <?php echo (isset($_POST['role']) && $_POST['role'] == 'branch_admin') ? 'selected' : ''; ?>>Branch Admin</option>
        </select>
    </div>
    <div class="form-group" id="branch_selection" style="display: <?php echo (isset($_POST['role']) && $_POST['role'] == 'branch_admin') ? 'block' : 'none'; ?>;">
        <label for="branch_id">Associate Branch:</label>
        <select id="branch_id" name="branch_id">
            <option value="">Select a Branch</option>
            <?php foreach ($branches as $branch): ?>
                <option value="<?php echo htmlspecialchars($branch['branch_id']); ?>" <?php echo (isset($_POST['branch_id']) && $_POST['branch_id'] == $branch['branch_id']) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($branch['branch_name']); ?>
                </option>
            <?php endforeach; ?>
        </select>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary"><i class="fas fa-plus-circle"></i> Add User</button>
        <a href="admin_manage_users.php" class="btn btn-secondary">Cancel</a>
    </div>
</form>

<script>
    function toggleBranchSelection() {
        const roleSelect = document.getElementById('role');
        const branchSelectionDiv = document.getElementById('branch_selection');
        if (roleSelect.value === 'branch_admin') {
            branchSelectionDiv.style.display = 'block';
            document.getElementById('branch_id').setAttribute('required', 'required');
        } else {
            branchSelectionDiv.style.display = 'none';
            document.getElementById('branch_id').removeAttribute('required');
        }
    }
    // Call on page load to set initial state based on POST if form failed
    document.addEventListener('DOMContentLoaded', toggleBranchSelection);
</script>

<?php
include __DIR__ . '/../includes/footer.php';
$conn->close();
?>