<?php
session_start();

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$error = "";

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $teacher_name = trim($_POST['teacher_name'] ?? '');
    $class_name   = trim($_POST['class_name'] ?? '');

    if ($teacher_name === '' || $class_name === '') {
        $error = "Please enter teacher name and class.";
    } elseif (!isset($_FILES['student_csv']) || $_FILES['student_csv']['error'] !== 0) {
        $error = "Please upload a valid CSV file.";
    } else {

        $fileTmp = $_FILES['student_csv']['tmp_name'];
        $students = [];

        if (($handle = fopen($fileTmp, "r")) !== false) {

            $row = 0;
            while (($data = fgetcsv($handle, 1000, ",")) !== false) {
                if ($row === 0) {
                    $row++;
                    continue; // skip header
                }

                $roll = trim($data[0] ?? '');
                $name = trim($data[1] ?? '');

                if ($roll && $name) {
                    $students[] = [
                        'roll' => $roll,
                        'name' => $name
                    ];
                }
            }
            fclose($handle);
        }

        if (count($students) === 0) {
            $error = "CSV file does not contain valid student data.";
        } else {
            // Save session
            $_SESSION['teacher_name'] = $teacher_name;
            $_SESSION['class_name']   = $class_name;
            $_SESSION['students']     = $students;

            header("Location: student_list.php");
            exit();
        }
    }
}
?>

<?php require_once 'includes/header.php'; ?>

<div class="student-wrap">

    <h2>Start Class Session</h2>
    <p class="sub">Enter class details and upload student list.</p>

    <?php if ($error): ?>
        <div class="error-box"><?php echo $error; ?></div>
    <?php endif; ?>

    <form method="POST" enctype="multipart/form-data">

        <label>Teacher Name</label>
        <input type="text" name="teacher_name" placeholder="e.g. Mr. Kumar" required>

        <label>Class / Section</label>
        <input type="text" name="class_name" placeholder="e.g. BCA 2nd Year - A" required>

        <label>Upload Student List (CSV)</label>
        <input type="file" name="student_csv" accept=".csv" required>

        <button type="submit">Start Session</button>
    </form>

    <a href="dashboard.php" class="back-link">← Back to Dashboard</a>
</div>

</body>
</html>
