<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
require_once 'db.php';

$message = "";

// 1. HANDLER: INDIVIDUAL STUDENT FORM PROFILES WITH ENCODED PHOTOS
if (isset($_POST['register_student'])) {
    $imgData = null;
    
    // Process and read the uploaded photograph file field
    if (isset($_FILES['photo_upload']) && $_FILES['photo_upload']['error'] == 0) {
        $imgData = file_get_contents($_FILES['photo_upload']['tmp_name']);
    }
    
    try {
        // Ensure column fields line up perfectly with the photography parameter token slot
        $stmt = $pdo->prepare("INSERT INTO students (matric_number, full_name, sex, department, student_level, program, session, password, photography) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute([
            trim($_POST['m_num']), 
            trim($_POST['f_name']), 
            $_POST['sex_val'], 
            trim($_POST['dept_val']), 
            trim($_POST['lvl_val']), 
            trim($_POST['program_val']), 
            trim($_POST['session_val']), 
            trim($_POST['pass_val']), 
            $imgData // Binds the raw binary picture data directly to your database column slot
        ]);
        $message = "<div style='background:#d4edda;color:#155724;padding:12px;border-radius:4px;margin-bottom:15px;'>✅ Success: Individual Student Account Registered with Photograph Identity!</div>";
    } catch (\PDOException $e) { 
        $message = "<div style='background:#f8d7da;color:#721c24;padding:12px;border-radius:4px;margin-bottom:15px;'>❌ Registration Error: " . htmlspecialchars($e->getMessage()) . "</div>"; 
    }
}

// 2. HANDLER: BULK CSV IMPORT PIPELINE LOGIC (Default profiles skip photos initially)
if (isset($_POST['import_students_csv'])) {
    if ($_FILES['student_csv']['error'] == 0) {
        $file = fopen($_FILES['student_csv']['tmp_name'], "r"); fgetcsv($file); $count = 0;
        try {
            $stmt = $pdo->prepare("INSERT INTO students (matric_number, full_name, sex, department, student_level, program, session, password, photography) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL)");
            while (($row = fgetcsv($file, 1000, ",")) !== FALSE) {
                if (count($row) >= 8) {
                    $stmt->execute([trim($row[0]), trim($row[1]), trim($row[2]), trim($row[3]), trim($row[4]), trim($row[5]), trim($row[6]), trim($row[7])]); $count++;
                }
            }
            $message = "<div style='background:#d4edda;color:#155724;padding:12px;border-radius:4px;margin-bottom:15px;'>✅ Success: Bulk Imported $count Student Profiles from CSV!</div>";
        } catch (\PDOException $e) { $message = "<div style='background:#f8d7da;color:#721c24;padding:12px;border-radius:4px;margin-bottom:15px;'>❌ CSV Error: " . htmlspecialchars($e->getMessage()) . "</div>"; }
        fclose($file);
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <style>
        body { font-family: Arial, sans-serif; background: #fff; padding: 15px; color: #333; }
        .card { background: #fdfdfd; padding: 20px; border: 1px solid #dee2e6; border-radius: 6px; margin-bottom: 20px; box-shadow: 0 1px 3px rgba(0,0,0,0.05); }
        input, select { width: 100%; padding: 10px; margin: 8px 0; box-sizing: border-box; border: 1px solid #ccc; border-radius: 4px; }
        .btn { padding: 10px 20px; background: #007bff; color: white; border: none; cursor: pointer; border-radius: 4px; font-weight: bold; }
        .btn-csv { background: #6f42c1; width: 100%; margin-top: 10px; }
        .csv-note { background: #f8f9fa; border-left: 3px solid #6f42c1; padding: 10px; font-size: 12px; margin: 8px 0; color: #555; }
    </style>
</head>
<body>
    <h2>Student Enrollment Manager</h2>
    <?php echo $message; ?>
    <div class="card" style="border-top: 4px solid #007bff;">
        <h4 style="margin-top:0; color:#007bff;">Option 1: Add Individual Student Manually</h4>
        <!-- CRITICAL REQUIREMENT: enctype="multipart/form-data" must be active to allow file transfers -->
        <form method="POST" enctype="multipart/form-data">
            <div style="display:grid; grid-template-columns: 1fr 1fr; gap:12px;">
                <input type="text" name="m_num" placeholder="Matric Number (Unique ID)" required>
                <input type="text" name="f_name" placeholder="Full Student Name" required>
                <select name="sex_val" required><option value="Male">Male</option><option value="Female">Female</option></select>
                <input type="text" name="dept_val" placeholder="Department (e.g. Computer Science)" required>
                <input type="text" name="lvl_val" placeholder="Level (e.g. ND I, HND II)" required>
                <input type="text" name="program_val" placeholder="Program Track (e.g. Full-Time)" required>
                <input type="text" name="session_val" placeholder="Session Parameter (e.g. 2025/2026)" required>
                <input type="text" name="pass_val" placeholder="Set Plain Text Login Password" required>
            </div>
            <label style="font-size:12px; font-weight:bold; display:block; margin-top:10px;">Upload Candidate Profile Picture (JPG/PNG):</label>
            <input type="file" name="photo_upload" accept="image/*" required>
            <button type="submit" name="register_student" class="btn" style="width:100%; margin-top:12px;">Register Student Profile</button>
        </form>
    </div>
    <div class="card" style="border-top: 4px solid #6f42c1;">
        <h4 style="margin-top:0; color:#6f42c1;">Option 2: Bulk Upload Students via CSV File</h4>
        <div class="csv-note"><strong>Required Columns Order:</strong> matric_number, full_name, sex, department, student_level, program, session, password</div>
        <form method="POST" enctype="multipart/form-data">
            <input type="file" name="student_csv" accept=".csv" required>
            <button type="submit" name="import_students_csv" class="btn btn-csv">Execute Bulk Student Import</button>
        </form>
    </div>
</body>
</html>
