<?php
session_start();

// Enable error reporting for debugging
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

// Log errors to a file
ini_set('log_errors', 1);
ini_set('error_log', '/Applications/XAMPP/xamppfiles/htdocs/appraisal/public/debug.log');

// Log PHP version and extensions
error_log("PHP version: " . phpversion());
$required_extensions = ['zip', 'xml', 'gd', 'mbstring'];
$loaded_extensions = get_loaded_extensions();
$missing_extensions = array_diff($required_extensions, $loaded_extensions);
error_log("Required extensions: " . implode(', ', $required_extensions));
error_log("Missing extensions: " . (empty($missing_extensions) ? 'None' : implode(', ', $missing_extensions)));

// Log Composer version and diagnostics
$composer_version = exec('/Applications/XAMPP/xamppfiles/bin/php /usr/local/bin/composer --version 2>&1');
error_log("Composer version: " . ($composer_version ?: 'Failed to retrieve version'));
$diagnose_file = '/Applications/XAMPP/xamppfiles/htdocs/appraisal/public/composer_diagnose.log';
exec('/Applications/XAMPP/xamppfiles/bin/php /usr/local/bin/composer diagnose > ' . $diagnose_file . ' 2>&1');
error_log("Composer diagnose output written to: $diagnose_file");

try {
    require '../includes/config.php';
} catch (Exception $e) {
    error_log("Config error: " . $e->getMessage());
    die("Error loading configuration. Check debug.log.");
}

// Declare use statements at file level
use PhpOffice\PhpSpreadsheet\IOFactory;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

// Check for dependencies
$autoload_path = '../vendor/autoload.php';
$autoload_exists = file_exists($autoload_path);
$php_spreadsheet_class_exists = class_exists('PhpOffice\PhpSpreadsheet\IOFactory', false);
$phpmailer_class_exists = class_exists('PHPMailer\PHPMailer\PHPMailer', false);
$php_spreadsheet_available = $autoload_exists && $php_spreadsheet_class_exists;
$phpmailer_available = $autoload_exists && $phpmailer_class_exists;

// Check if IOFactory.php exists and is valid
$iofactory_path = '../vendor/phpoffice/phpspreadsheet/src/PhpSpreadsheet/IOFactory.php';
$iofactory_exists = file_exists($iofactory_path);
$iofactory_size = $iofactory_exists ? filesize($iofactory_path) : 0;
error_log("IOFactory.php exists: " . ($iofactory_exists ? 'Yes' : 'No'));
error_log("IOFactory.php size: $iofactory_size bytes");

// Fallback: Manually require IOFactory.php if class not found
if ($iofactory_exists && !$php_spreadsheet_class_exists) {
    try {
        require_once $iofactory_path;
        $php_spreadsheet_class_exists = class_exists('PhpOffice\PhpSpreadsheet\IOFactory', false);
        error_log("Manual require of IOFactory.php: " . ($php_spreadsheet_class_exists ? 'Success' : 'Failed'));
        $php_spreadsheet_available = $autoload_exists && $php_spreadsheet_class_exists;
    } catch (Exception $e) {
        error_log("Manual require error: " . $e->getMessage());
    }
}

// Log dependency check
error_log("Autoloader path: $autoload_path");
error_log("Autoloader exists: " . ($autoload_exists ? 'Yes' : 'No'));
error_log("PhpSpreadsheet class exists: " . ($php_spreadsheet_class_exists ? 'Yes' : 'No'));
error_log("PHPMailer class exists: " . ($phpmailer_class_exists ? 'Yes' : 'No'));

// Check if phpoffice/phpspreadsheet is installed
$composer_json_path = '../composer.json';
$phpspreadsheet_installed = false;
if (file_exists($composer_json_path)) {
    $composer_json = json_decode(file_get_contents($composer_json_path), true);
    $phpspreadsheet_installed = isset($composer_json['require']['phpoffice/phpspreadsheet']);
    error_log("phpoffice/phpspreadsheet in composer.json: " . ($phpspreadsheet_installed ? 'Yes' : 'No'));
}

// Check if vendor/phpoffice/phpspreadsheet exists
$phpspreadsheet_dir = '../vendor/phpoffice/phpspreadsheet';
$phpspreadsheet_dir_exists = is_dir($phpspreadsheet_dir);
error_log("phpoffice/phpspreadsheet directory exists: " . ($phpspreadsheet_dir_exists ? 'Yes' : 'No'));

// Check autoloader classmap for PhpSpreadsheet
$classmap_path = '../vendor/composer/autoload_classmap.php';
$phpspreadsheet_in_classmap = false;
if (file_exists($classmap_path)) {
    $classmap = include $classmap_path;
    $phpspreadsheet_in_classmap = isset($classmap['PhpOffice\PhpSpreadsheet\IOFactory']);
    error_log("PhpOffice\PhpSpreadsheet\IOFactory in autoload_classmap.php: " . ($phpspreadsheet_in_classmap ? 'Yes' : 'No'));
}

// Check PSR-4 autoloader for PhpSpreadsheet
$psr4_path = '../vendor/composer/autoload_psr4.php';
$phpspreadsheet_psr4_mapping = false;
if (file_exists($psr4_path)) {
    $psr4 = include $psr4_path;
    $phpspreadsheet_psr4_mapping = isset($psr4['PhpOffice\\PhpSpreadsheet\\']);
    error_log("PhpOffice\PhpSpreadsheet PSR-4 mapping exists: " . ($phpspreadsheet_psr4_mapping ? 'Yes' : 'No'));
    if ($phpspreadsheet_psr4_mapping) {
        error_log("PhpOffice\PhpSpreadsheet PSR-4 path: " . implode(', ', $psr4['PhpOffice\\PhpSpreadsheet\\']));
    }
}

// Set error message if PhpSpreadsheet is not available
$dependency_error = '';
if (!$php_spreadsheet_available) {
    $dependency_error = "Bulk upload is disabled: PhpSpreadsheet library is not installed. ";
    $dependency_error .= "Autoloader exists: " . ($autoload_exists ? 'Yes' : 'No') . ". ";
    $dependency_error .= "PhpSpreadsheet class exists: " . ($php_spreadsheet_class_exists ? 'Yes' : 'No') . ". ";
    $dependency_error .= "phpoffice/phpspreadsheet in composer.json: " . ($phpspreadsheet_installed ? 'Yes' : 'No') . ". ";
    $dependency_error .= "phpoffice/phpspreadsheet directory exists: " . ($phpspreadsheet_dir_exists ? 'Yes' : 'No') . ". ";
    $dependency_error .= "IOFactory.php exists: " . ($iofactory_exists ? 'Yes' : 'No') . ". ";
    $dependency_error .= "IOFactory.php size: $iofactory_size bytes. ";
    $dependency_error .= "PhpOffice\PhpSpreadsheet\IOFactory in autoload_classmap.php: " . ($phpspreadsheet_in_classmap ? 'Yes' : 'No') . ". ";
    $dependency_error .= "PhpOffice\PhpSpreadsheet PSR-4 mapping exists: " . ($phpspreadsheet_psr4_mapping ? 'Yes' : 'No') . ". ";
    $dependency_error .= "Missing extensions: " . (empty($missing_extensions) ? 'None' : implode(', ', $missing_extensions)) . ". ";
    $dependency_error .= "Composer version: " . ($composer_version ?: 'Failed to retrieve version') . ". ";
    $dependency_error .= "Composer diagnose output: Check $diagnose_file. ";
    $dependency_error .= "Please check debug.log and contact the system administrator.";
}

// Load dependencies
if ($php_spreadsheet_available || $phpmailer_available) {
    try {
        require $autoload_path;
    } catch (Exception $e) {
        error_log("Autoloader error: " . $e->getMessage());
        $dependency_error = "Failed to load autoloader: " . $e->getMessage();
    }
}

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

// Fetch available classes and programs
try {
    $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);
} catch (Exception $e) {
    error_log("Database query error: " . $e->getMessage());
    $dependency_error = "Database error: " . $e->getMessage();
}

// 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 = $dependency_error;
$success = '';
$generated_id = '';
$bulk_errors = [];
$bulk_successes = [];

// Function to generate unique ID
function generateUniqueID($conn, $prefix = 'S') {
    $attempts = 0;
    $max_attempts = 10;
    do {
        $random_num = mt_rand(1, 99999);
        $id = $prefix . str_pad($random_num, 5, '0', STR_PAD_LEFT);
        $query = "SELECT id FROM users WHERE id = ?";
        $stmt = mysqli_prepare($conn, $query);
        mysqli_stmt_bind_param($stmt, 's', $id);
        mysqli_stmt_execute($stmt);
        $result = mysqli_stmt_get_result($stmt);
        $attempts++;
    } while ($result->num_rows > 0 && $attempts < $max_attempts);
    return ($attempts < $max_attempts) ? $id : false;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (isset($_FILES['excel_file']) && $_FILES['excel_file']['error'] == UPLOAD_ERR_OK) {
        // Handle bulk upload
        if (!$php_spreadsheet_available) {
            $error = "Bulk upload is disabled: PhpSpreadsheet library is not installed. ";
            $error .= "Autoloader exists: " . ($autoload_exists ? 'Yes' : 'No') . ". ";
            $error .= "PhpSpreadsheet class exists: " . ($php_spreadsheet_class_exists ? 'Yes' : 'No') . ". ";
            $error .= "phpoffice/phpspreadsheet in composer.json: " . ($phpspreadsheet_installed ? 'Yes' : 'No') . ". ";
            $error .= "phpoffice/phpspreadsheet directory exists: " . ($phpspreadsheet_dir_exists ? 'Yes' : 'No') . ". ";
            $error .= "IOFactory.php exists: " . ($iofactory_exists ? 'Yes' : 'No') . ". ";
            $error .= "IOFactory.php size: $iofactory_size bytes. ";
            $error .= "PhpOffice\PhpSpreadsheet\IOFactory in autoload_classmap.php: " . ($phpspreadsheet_in_classmap ? 'Yes' : 'No') . ". ";
            $error .= "PhpOffice\PhpSpreadsheet PSR-4 mapping exists: " . ($phpspreadsheet_psr4_mapping ? 'Yes' : 'No') . ". ";
            $error .= "Missing extensions: " . (empty($missing_extensions) ? 'None' : implode(', ', $missing_extensions)) . ". ";
            $error .= "Composer version: " . ($composer_version ?: 'Failed to retrieve version') . ". ";
            $error .= "Composer diagnose output: Check $diagnose_file. ";
            $error .= "Please check debug.log and contact the system administrator.";
        } else {
            $upload_dir = '../public/uploads/';
            if (!is_dir($upload_dir)) {
                mkdir($upload_dir, 0755, true);
            }
            $file_name = $upload_dir . uniqid() . '.xlsx';
            if (move_uploaded_file($_FILES['excel_file']['tmp_name'], $file_name)) {
                try {
                    $spreadsheet = IOFactory::load($file_name);
                    $sheet = $spreadsheet->getActiveSheet();
                    $rows = $sheet->toArray(null, true, true, true);
                    $header = array_shift($rows); // Remove header row

                    // Expected columns: ID, First Name, Last Name, Email, Password, Class ID, Program ID
                    $expected_columns = ['ID', 'First Name', 'Last Name', 'Email', 'Password', 'Class ID', 'Program ID'];
                    if (array_map('strtolower', $header) !== array_map('strtolower', $expected_columns)) {
                        $error = "Invalid Excel format. Expected columns: " . implode(', ', $expected_columns);
                    } else {
                        $class_ids = array_column($classes, 'class_id');
                        $program_ids = array_column($programs, 'program_id');
                        $row_number = 2; // Start after header

                        foreach ($rows as $row) {
                            $id = trim($row['A'] ?? '');
                            $first_name = trim($row['B'] ?? '');
                            $last_name = trim($row['C'] ?? '');
                            $email = trim($row['D'] ?? '');
                            $password = $row['E'] ?? '';
                            $class_id = trim($row['F'] ?? '');
                            $program_id = trim($row['G'] ?? '');

                            // Validate inputs
                            $row_error = '';
                            if (empty($first_name) || empty($last_name) || empty($email) || empty($password) || empty($class_id) || empty($program_id)) {
                                $row_error = "Row $row_number: All fields are required.";
                            } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                                $row_error = "Row $row_number: Invalid email format.";
                            } elseif (!in_array($class_id, $class_ids)) {
                                $row_error = "Row $row_number: Invalid class ID.";
                            } elseif (!in_array($program_id, $program_ids)) {
                                $row_error = "Row $row_number: Invalid program ID.";
                            } else {
                                // Check if email exists
                                $query = "SELECT id FROM users WHERE email = ?";
                                $stmt = mysqli_prepare($conn, $query);
                                mysqli_stmt_bind_param($stmt, 's', $email);
                                mysqli_stmt_execute($stmt);
                                if (mysqli_stmt_get_result($stmt)->num_rows > 0) {
                                    $row_error = "Row $row_number: Email already registered.";
                                } else {
                                    // Handle ID
                                    if (empty($id)) {
                                        $id = generateUniqueID($conn);
                                        if (!$id) {
                                            $row_error = "Row $row_number: Unable to generate unique ID.";
                                        }
                                    } else {
                                        $query = "SELECT id FROM users WHERE id = ?";
                                        $stmt = mysqli_prepare($conn, $query);
                                        mysqli_stmt_bind_param($stmt, 's', $id);
                                        mysqli_stmt_execute($stmt);
                                        if (mysqli_stmt_get_result($stmt)->num_rows > 0) {
                                            $row_error = "Row $row_number: ID already exists.";
                                        }
                                    }

                                    if (empty($row_error)) {
                                        // Register student
                                        $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                                        $query = "INSERT INTO users (id, first_name, last_name, email, password, role, class_id) VALUES (?, ?, ?, ?, ?, ?, ?)";
                                        $stmt = mysqli_prepare($conn, $query);
                                        $role = 'student';
                                        mysqli_stmt_bind_param($stmt, 'ssssssi', $id, $first_name, $last_name, $email, $hashed_password, $role, $class_id);
                                        if (mysqli_stmt_execute($stmt)) {
                                            // Assign class and program
                                            $query = "INSERT INTO class_program_students (student_id, class_id, program_id) VALUES (?, ?, ?)";
                                            $stmt = mysqli_prepare($conn, $query);
                                            mysqli_stmt_bind_param($stmt, 'sii', $id, $class_id, $program_id);
                                            if (mysqli_stmt_execute($stmt)) {
                                                // Get class and program names for email
                                                $class_name = $classes[array_search($class_id, array_column($classes, 'class_id'))]['class_name'];
                                                $program_name = $programs[array_search($program_id, array_column($programs, 'program_id'))]['program_name'];
                                                // Send confirmation email
                                                if ($phpmailer_available) {
                                                    $mail = new PHPMailer(true);
                                                    try {
                                                        $mail->isSMTP();
                                                        $mail->Host = 'localhost';
                                                        $mail->Port = 1025;
                                                        $mail->SMTPAuth = false;
                                                        $mail->SMTPSecure = '';
                                                        $mail->setFrom('no-reply@appraisal.local', 'Appraisal System');
                                                        $mail->addAddress($email, "$first_name $last_name");
                                                        $mail->Subject = 'Registration Confirmation';
                                                        $mail->Body = "Dear $first_name $last_name,\n\nYour student account has been created successfully.\nID: $id\nClass: $class_name\nProgram: $program_name\n\nLogin at http://localhost/appraisal/public\n\nBest regards,\nAppraisal System";
                                                        $mail->AltBody = $mail->Body;
                                                        $mail->send();
                                                        $bulk_successes[] = "Row $row_number: Registered $first_name $last_name (ID: $id, Class: $class_name, Program: $program_name)";
                                                    } catch (Exception $e) {
                                                        $bulk_successes[] = "Row $row_number: Registered $first_name $last_name (ID: $id, Class: $class_name, Program: $program_name), but failed to send email: " . $mail->ErrorInfo;
                                                    }
                                                } else {
                                                    $bulk_successes[] = "Row $row_number: Registered $first_name $last_name (ID: $id, Class: $class_name, Program: $program_name), but email sending is disabled.";
                                                }
                                            } else {
                                                $row_error = "Row $row_number: Failed to assign class/program: " . mysqli_error($conn);
                                            }
                                        } else {
                                            $row_error = "Row $row_number: Failed to register: " . mysqli_error($conn);
                                        }
                                    }
                                }
                            }
                            if (!empty($row_error)) {
                                $bulk_errors[] = $row_error;
                            }
                            $row_number++;
                        }
                    }
                } catch (Exception $e) {
                    $error = "Failed to process Excel file: " . $e->getMessage();
                    error_log("Excel processing error: " . $e->getMessage());
                }
                unlink($file_name); // Delete temporary file
            } else {
                $error = "Failed to upload file.";
                error_log("File upload error: Failed to move uploaded file.");
            }
        }
    } else {
        // Handle single student registration
        $first_name = trim($_POST['first_name'] ?? '');
        $last_name = trim($_POST['last_name'] ?? '');
        $email = trim($_POST['email'] ?? '');
        $password = $_POST['password'] ?? '';
        $id = isset($_POST['id']) ? trim($_POST['id']) : '';
        $class_id = $_POST['class_id'] ?? '';
        $program_id = $_POST['program_id'] ?? '';
        $role = 'student';

        // Validate inputs
        if (empty($first_name) || empty($last_name) || empty($email) || empty($password) || 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 exists
            $query = "SELECT id FROM users WHERE email = ?";
            $stmt = mysqli_prepare($conn, $query);
            mysqli_stmt_bind_param($stmt, 's', $email);
            mysqli_stmt_execute($stmt);
            if (mysqli_stmt_get_result($stmt)->num_rows > 0) {
                $error = "Email already registered.";
            } else {
                // Generate or validate ID
                if (empty($id)) {
                    $id = generateUniqueID($conn);
                    if (!$id) {
                        $error = "Unable to generate a unique ID. Please try again or enter a manual ID.";
                    }
                } else {
                    $query = "SELECT id FROM users WHERE id = ?";
                    $stmt = mysqli_prepare($conn, $query);
                    mysqli_stmt_bind_param($stmt, 's', $id);
                    mysqli_stmt_execute($stmt);
                    if (mysqli_stmt_get_result($stmt)->num_rows > 0) {
                        $error = "ID already exists. Choose another.";
                    } elseif (empty($id)) {
                        $error = "ID cannot be empty if provided.";
                    }
                }

                if (empty($error)) {
                    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
                    $query = "INSERT INTO users (id, first_name, last_name, email, password, role, class_id) VALUES (?, ?, ?, ?, ?, ?, ?)";
                    $stmt = mysqli_prepare($conn, $query);
                    mysqli_stmt_bind_param($stmt, 'ssssssi', $id, $first_name, $last_name, $email, $hashed_password, $role, $class_id);
                    if (mysqli_stmt_execute($stmt)) {
                        $query = "INSERT INTO class_program_students (student_id, class_id, program_id) VALUES (?, ?, ?)";
                        $stmt = mysqli_prepare($conn, $query);
                        mysqli_stmt_bind_param($stmt, 'sii', $id, $class_id, $program_id);
                        if (mysqli_stmt_execute($stmt)) {
                            $generated_id = $id;
                            $class_name = $classes[array_search($class_id, array_column($classes, 'class_id'))]['class_name'];
                            $program_name = $programs[array_search($program_id, array_column($programs, 'program_id'))]['program_name'];
                            if ($phpmailer_available) {
                                $mail = new PHPMailer(true);
                                try {
                                    $mail->isSMTP();
                                    $mail->Host = 'localhost';
                                    $mail->Port = 1025;
                                    $mail->SMTPAuth = false;
                                    $mail->SMTPSecure = '';
                                    $mail->setFrom('no-reply@appraisal.local', 'Appraisal System');
                                    $mail->addAddress($email, "$first_name $last_name");
                                    $mail->Subject = 'Registration Confirmation';
                                    $mail->Body = "Dear $first_name $last_name,\n\nYour student account has been created successfully.\nID: $id\nClass: $class_name\nProgram: $program_name\n\nLogin at http://localhost/appraisal/public\n\nBest regards,\nAppraisal System";
                                    $mail->AltBody = $mail->Body;
                                    $mail->send();
                                    $success = "Student registered successfully! A confirmation email has been sent. User ID: $id, Class: $class_name, Program: $program_name";
                                } catch (Exception $e) {
                                    $success = "Student registered successfully, but failed to send email: " . $e->getMessage() . " User ID: $id, Class: $class_name, Program: $program_name";
                                    error_log("Email error: " . $e->getMessage());
                                }
                            } else {
                                $success = "Student registered successfully, but email sending is disabled. User ID: $id, Class: $class_name, Program: $program_name";
                            }
                        } else {
                            $error = "Failed to assign class and program: " . mysqli_error($conn);
                            error_log("Class/program assignment error: " . mysqli_error($conn));
                        }
                    } else {
                        $error = "Failed to register: " . mysqli_error($conn);
                        error_log("Registration error: " . mysqli_error($conn));
                    }
                }
            }
        }
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Register Student</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="../css/register.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h2>Register 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 (!empty($bulk_successes)): ?>
            <div class="alert alert-success">
                <h4>Bulk Registration Successes</h4>
                <ul>
                    <?php foreach ($bulk_successes as $success_msg): ?>
                        <li><?php echo htmlspecialchars($success_msg); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>
        <?php if (!empty($bulk_errors)): ?>
            <div class="alert alert-danger">
                <h4>Bulk Registration Errors</h4>
                <ul>
                    <?php foreach ($bulk_errors as $error_msg): ?>
                        <li><?php echo htmlspecialchars($error_msg); ?></li>
                    <?php endforeach; ?>
                </ul>
            </div>
        <?php endif; ?>

        <!-- Single Student Registration Form -->
        <h3>Register Single Student</h3>
        <form method="POST">
            <div class="form-group mb-3">
                <label>ID (Optional, leave blank to auto-generate)</label>
                <input type="text" name="id" class="form-control" value="<?php echo isset($_POST['id']) ? htmlspecialchars($_POST['id']) : ''; ?>" placeholder="Enter any unique ID or leave blank">
            </div>
            <div class="form-group mb-3">
                <label>First Name</label>
                <input type="text" name="first_name" class="form-control" value="<?php echo isset($_POST['first_name']) ? htmlspecialchars($_POST['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 isset($_POST['last_name']) ? htmlspecialchars($_POST['last_name']) : ''; ?>" required>
            </div>
            <div class="form-group mb-3">
                <label>Email</label>
                <input type="email" name="email" class="form-control" value="<?php echo isset($_POST['email']) ? htmlspecialchars($_POST['email']) : ''; ?>" required>
            </div>
            <div class="form-group mb-3">
                <label>Password</label>
                <input type="password" name="password" class="form-control" 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 isset($_POST['class_id']) && $_POST['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 isset($_POST['program_id']) && $_POST['program_id'] == $program['program_id'] ? 'selected' : ''; ?>>
                            <?php echo htmlspecialchars($program['program_name']); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <button type="submit" class="btn btn-primary">Register</button>
            <a href="dashboard.php" class="btn btn-secondary">Back to Dashboard</a>
        </form>

        <!-- Bulk Upload Form -->
        <h3 class="mt-5">Bulk Register Students</h3>
        <?php if (!$php_spreadsheet_available): ?>
            <div class="alert alert-warning">
                <?php echo htmlspecialchars($error); ?>
            </div>
        <?php else: ?>
            <form method="POST" enctype="multipart/form-data">
                <div class="form-group mb-3">
                    <label>Upload Excel File (.xlsx, .xls)</label>
                    <input type="file" name="excel_file" class="form-control" accept=".xlsx,.xls" required>
                    <small class="form-text text-muted">
                        Excel file must have columns: ID (optional), First Name, Last Name, Email, Password, Class ID, Program ID.
                        <a href="../public/templates/student_upload_template.xlsx" download>Download template</a>.
                    </small>
                </div>
                <button type="submit" class="btn btn-primary">Upload and Register</button>
            </form>
        <?php endif; ?>
    </div>
</body>
</html>