<?php
// school_admission/public/admin_edit_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 = '';
$user_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
$user = null;
$branches = [];

if ($user_id === 0) {
    $_SESSION['message'] = "<div class='message error'>Invalid user ID.</div>";
    redirect('admin_manage_users.php');
}

// Prevent editing oneself (for role changes that could lock you out)
if ($user_id == $_SESSION['user_id']) {
    $message = "<div class='message info'>You are currently logged in as this user. Some actions (like changing your own role to something that locks you out) are restricted to prevent self-lockout.</div>";
}


// Fetch existing user data
$stmt = $conn->prepare("SELECT user_id, username, email, role, branch_id FROM users WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 1) {
    $user = $result->fetch_assoc();
} else {
    $_SESSION['message'] = "<div class='message error'>User not found.</div>";
    redirect('admin_manage_users.php');
}
$stmt->close();

// 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']; // Optional, only if changing
    $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($role) || ($role === 'branch_admin' && $branch_id === 0 && !is_null($branch_id))) { // is_null check for 'Select a Branch' which is value ""
        $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 if another user with this username or email already exists (excluding current user)
        $stmt_check = $conn->prepare("SELECT user_id FROM users WHERE (username = ? OR email = ?) AND user_id != ?");
        $stmt_check->bind_param("ssi", $username, $email, $user_id);
        $stmt_check->execute();
        $stmt_check->store_result();

        if ($stmt_check->num_rows > 0) {
            $message = "<div class='message error'>Username or Email already exists for another user.</div>";
        } else {
            $update_password_sql = "";
            $params = [];
            $types = "";

            if (!empty($password)) {
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                $update_password_sql = ", password = ?";
                $params[] = $hashed_password;
                $types .= "s";
            }

            $sql_update = "UPDATE users SET username = ?, email = ?, role = ?, branch_id = ? {$update_password_sql} WHERE user_id = ?";
            $stmt_update = $conn->prepare($sql_update);

            $params_bind = [&$username, &$email, &$role, &$branch_id];
            $types_bind = "sssi";

            if (!empty($password)) {
                $params_bind[] = &$hashed_password;
                $types_bind .= "s";
            }
            $params_bind[] = &$user_id;

            // Dynamically bind parameters
            $ref_params = [];
            foreach ($params_bind as $key => $val) {
                $ref_params[$key] = &$params_bind[$key];
            }
            call_user_func_array([$stmt_update, 'bind_param'], array_merge([$types_bind], $ref_params));


            if ($stmt_update->execute()) {
                $_SESSION['message'] = "<div class='message success'>User <strong>" . htmlspecialchars($username) . "</strong> updated successfully!</div>";
                
                // If the logged-in user edited their own account and changed their role/branch_id, update session
                if ($user_id == $_SESSION['user_id']) {
                    $_SESSION['username'] = $username;
                    $_SESSION['role'] = $role;
                    $_SESSION['branch_id'] = $branch_id;
                }
                
                redirect('admin_manage_users.php');
            } else {
                $message = "<div class='message error'>Error updating user: " . $stmt_update->error . "</div>";
            }
            $stmt_update->close();
        }
        $stmt_check->close();
    }
    // Re-fetch user data if POST failed to show current values
    $stmt = $conn->prepare("SELECT user_id, username, email, role, branch_id FROM users WHERE user_id = ?");
    $stmt->bind_param("i", $user_id);
    $stmt->execute();
    $result = $stmt->get_result();
    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();
    }
    $stmt->close();
}


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

<h2 class="mt-30">Edit User: <?php echo htmlspecialchars($user['username']); ?></h2>

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

<form action="admin_edit_user.php?id=<?php echo $user_id; ?>" method="POST">
    <div class="form-group">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" required value="<?php echo htmlspecialchars($user['username']); ?>">
    </div>
    <div class="form-group">
        <label for="email">Email:</label>
        <input type="email" id="email" name="email" required value="<?php echo htmlspecialchars($user['email']); ?>">
    </div>
    <div class="form-group">
        <label for="password">New Password (leave blank to keep current):</label>
        <input type="password" id="password" name="password">
    </div>
    <div class="form-group">
        <label for="role">Role:</label>
        <select id="role" name="role" required onchange="toggleBranchSelection()" <?php echo ($user_id == $_SESSION['user_id'] ? 'disabled' : ''); // Disable role change if editing self ?>>
            <option value="super_admin" <?php echo ($user['role'] == 'super_admin') ? 'selected' : ''; ?>>Super Admin</option>
            <option value="branch_admin" <?php echo ($user['role'] == 'branch_admin') ? 'selected' : ''; ?>>Branch Admin</option>
        </select>
        <?php if ($user_id == $_SESSION['user_id']): ?>
            <input type="hidden" name="role" value="<?php echo htmlspecialchars($user['role']); ?>">
            <p class="message info">You cannot change your own role to prevent self-lockout.</p>
        <?php endif; ?>
    </div>
    <div class="form-group" id="branch_selection" style="display: <?php echo ($user['role'] == 'branch_admin') ? 'block' : 'none'; ?>;">
        <label for="branch_id">Associate Branch:</label>
        <select id="branch_id" name="branch_id" <?php echo ($user_id == $_SESSION['user_id'] && $user['role'] !== 'super_admin' ? 'disabled' : ''); // Disable if editing self as branch admin? Or only disable for super admin self edit? >
            <option value="">Select a Branch</option>
            <?php foreach ($branches as $branch): ?>
                <option value="<?php echo htmlspecialchars($branch['branch_id']); ?>" <?php echo ($user['branch_id'] == $branch['branch_id']) ? 'selected' : ''; ?>>
                    <?php echo htmlspecialchars($branch['branch_name']); ?>
                </option>
            <?php endforeach; ?>
        </select>
        <?php if ($user_id == $_SESSION['user_id'] && $user['role'] !== 'super_admin'): ?>
             <input type="hidden" name="branch_id" value="<?php echo htmlspecialchars($user['branch_id']); ?>">
             <p class="message info">You cannot change your own associated branch.</p>
        <?php endif; ?>
    </div>
    <div class="form-group">
        <button type="submit" class="btn btn-primary"><i class="fas fa-sync-alt"></i> Update 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');
        const branchIdSelect = document.getElementById('branch_id');

        if (roleSelect.value === 'branch_admin') {
            branchSelectionDiv.style.display = 'block';
            branchIdSelect.setAttribute('required', 'required');
        } else {
            branchSelectionDiv.style.display = 'none';
            branchIdSelect.removeAttribute('required');
            // Optionally, clear selection if switching away from branch admin
            // branchIdSelect.value = '';
        }
    }
    document.addEventListener('DOMContentLoaded', toggleBranchSelection);
</script>

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