<?php
session_start();
require '../includes/config.php';

// Restrict to admins
if (!isset($_SESSION['role']) || $_SESSION['role'] !== 'admin') {
    header('Location: index.php');
    exit;
}

// Check if user_id is provided
if (!isset($_GET['user_id'])) {
    header('Location: user_manage.php');
    exit;
}

$user_id = $_GET['user_id'];

// Fetch user details
$query = "SELECT id, first_name, last_name, email FROM users WHERE id = ? AND role = 'student' AND is_deleted = 0";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 's', $user_id);
mysqli_stmt_execute($stmt);
$user = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));

if (!$user) {
    header('Location: user_manage.php');
    exit;
}

// Fetch current class and program
$query = "SELECT class_id, program_id FROM class_program_students WHERE student_id = ?";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, 's', $user_id);
mysqli_stmt_execute($stmt);
$current_assignment = mysqli_fetch_assoc(mysqli_stmt_get_result($stmt));

// Set defaults if no assignment exists
$has_assignment = !is_null($current_assignment);
$current_class_id = $has_assignment ? $current_assignment['class_id'] : '';
$current_program_id = $has_assignment ? $current_assignment['program_id'] : '';

// Fetch available classes and programs
$classes_query = "SELECT class_id, class_name FROM classes ORDER BY class_name";
$classes_result = mysqli_query($conn, $classes_query);
$classes = mysqli_fetch_all($classes_result, MYSQLI_ASSOC);

$programs_query = "SELECT program_id, program_name FROM programs ORDER BY program_name";
$programs_result = mysqli_query($conn, $programs_query);
$programs = mysqli_fetch_all($programs_result, MYSQLI_ASSOC);

// Check if classes or programs are empty
if (empty($classes) || empty($programs)) {
    $error = "No classes or programs available. Please add them in the management section.";
}

$error = '';
$success = '';
$warning = $has_assignment ? '' : 'No class or program assigned to this student. Please select one.';

if ($_SERVER['REQUEST_METHOD'] == 'POST' && empty($error)) {
    $first_name = trim($_POST['first_name']);
    $last_name = trim($_POST['last_name']);
    $email = trim($_POST['email']);
    $class_id = $_POST['class_id'];
    $program_id = $_POST['program_id'];

    // Validate inputs
    if (empty($first_name) || empty($last_name) || empty($email) || empty($class_id) || empty($program_id)) {
        $error = "All fields are required.";
    } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        $error = "Invalid email format.";
    } elseif (!array_key_exists($class_id, array_column($classes, 'class_id', 'class_id'))) {
        $error = "Invalid class selected.";
    } elseif (!array_key_exists($program_id, array_column($programs, 'program_id', 'program_id'))) {
        $error = "Invalid program selected.";
    } else {
        // Check if email is taken by another user
        $query = "SELECT id FROM users WHERE email = ? AND id != ?";
        $stmt = mysqli_prepare($conn, $query);
        mysqli_stmt_bind_param($stmt, 'ss', $email, $user_id);
        mysqli_stmt_execute($stmt);
        if (mysqli_stmt_get_result($stmt)->num_rows > 0) {
            $error = "Email already in use by another user.";
        } else {
            // Update user details
            $query = "UPDATE users SET first_name = ?, last_name = ?, email = ? WHERE id = ?";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 'ssss', $first_name, $last_name, $email, $user_id);
            if (mysqli_stmt_execute($stmt)) {
                // Update or insert class and program assignment
                $query = "REPLACE INTO class_program_students (student_id, class_id, program_id) VALUES (?, ?, ?)";
                $stmt = mysqli_prepare($conn, $query);
                mysqli_stmt_bind_param($stmt, 'sii', $user_id, $class_id, $program_id);
                if (mysqli_stmt_execute($stmt)) {
                    $success = "Student details updated successfully.";
                } else {
                    $error = "Failed to update class and program: " . mysqli_error($conn);
                }
            } else {
                $error = "Failed to update user: " . mysqli_error($conn);
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Edit Student</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/style.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h2>Edit Student</h2>
        <?php if ($success): ?>
            <div class="alert alert-success"><?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        <?php if ($error): ?>
            <div class="alert alert-danger"><?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        <?php if ($warning): ?>
            <div class="alert alert-warning"><?php echo htmlspecialchars($warning); ?></div>
        <?php endif; ?>

        <form method="POST">
            <div class="form-group mb-3">
                <label>ID</label>
                <input type="text" class="form-control" value="<?php echo htmlspecialchars($user['id']); ?>" disabled>
            </div>
            <div class="form-group mb-3">
                <label>First Name</label>
                <input type="text" name="first_name" class="form-control" value="<?php echo htmlspecialchars($user['first_name']); ?>" required>
            </div>
            <div class="form-group mb-3">
                <label>Last Name</label>
                <input type="text" name="last_name" class="form-control" value="<?php echo htmlspecialchars($user['last_name']); ?>" required>
            </div>
            <div class="form-group mb-3">
                <label>Email</label>
                <input type="email" name="email" class="form-control" value="<?php echo htmlspecialchars($user['email']); ?>" required>
            </div>
            <div class="form-group mb-3">
                <label>Class</label>
                <select name="class_id" class="form-control" required>
                    <option value="">Select Class</option>
                    <?php foreach ($classes as $class): ?>
                        <option value="<?php echo $class['class_id']; ?>" <?php echo $current_class_id == $class['class_id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($class['class_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group mb-3">
                <label>Program</label>
                <select name="program_id" class="form-control" required>
                    <option value="">Select Program</option>
                    <?php foreach ($programs as $program): ?>
                        <option value="<?php echo $program['program_id']; ?>" <?php echo $current_program_id == $program['program_id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($program['program_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="submit" class="btn btn-primary">Update</button>
            <a href="user_manage.php" class="btn btn-secondary">Back to Manage Users</a>
        </form>
    </div>
</body>
</html>