<?php
session_start();
require 'db.php';

$success = $_SESSION['upload_success'] ?? "";
$error = $_SESSION['upload_error'] ?? "";
unset($_SESSION['upload_success'], $_SESSION['upload_error']);

if ($_SERVER["REQUEST_METHOD"] === "POST" && isset($_FILES["csv_file"])) {
    $file = $_FILES["csv_file"]["tmp_name"];
    $section_code = trim($_POST["section_code"]);

    if (($handle = fopen($file, "r")) !== false) {
        $header = fgetcsv($handle); // Skip the first row (column titles)
        $successCount = 0;
        $duplicateCount = 0;

        while (($data = fgetcsv($handle, 1000, ",")) !== false) {
            $first_name = trim($data[0]);
            $last_name = trim($data[1]);
            $email = trim($data[2]);
            $password = password_hash(trim($data[3]), PASSWORD_DEFAULT);

            $stmt = $conn->prepare("INSERT INTO Students (first_name, last_name, email, password, section_code) VALUES (?, ?, ?, ?, ?)");
            $stmt->bind_param("sssss", $first_name, $last_name, $email, $password, $section_code);

            if ($stmt->execute()) {
                $successCount++;
            } else {
                if (str_contains($stmt->error, 'Duplicate entry')) {
                    $duplicateCount++;
                } else {
                    $_SESSION['upload_error'] = "Error: " . $stmt->error;
                }
            }

            $stmt->close();
        }

        fclose($handle);
        $_SESSION['upload_success'] = "$successCount students added. $duplicateCount duplicates skipped.";
        header("Location: upload-students.php");
        exit();
    } else {
        $_SESSION['upload_error'] = "Failed to open CSV file.";
        header("Location: upload-students.php");
        exit();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload Students</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            background: #f7f7f7;
            height: 100vh;
            margin: 0;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 0 15px rgba(0,0,0,0.2);
            width: 400px;
            text-align: center;
        }
        input, select {
            width: 100%;
            padding: 10px;
            margin-bottom: 15px;
        }
        input[type="submit"], button {
            background-color: #ff6c2c;
            color: white;
            border: none;
            cursor: pointer;
            padding: 10px;
            width: 48%;
            margin: 5px 1%;
            border-radius: 5px;
        }
        .success { color: green; margin-bottom: 15px; }
        .error { color: red; margin-bottom: 15px; }
    </style>
</head>
<body>
    <div class="container">
        <h2>Upload Students CSV</h2>

        <?php if ($success): ?><p class="success"><?= $success ?></p><?php endif; ?>
        <?php if ($error): ?><p class="error"><?= $error ?></p><?php endif; ?>

        <?php if (!$success): ?>
        <form method="post" enctype="multipart/form-data">
            <input type="text" name="section_code" placeholder="Section Code (e.g., T.00.2025 or A.01.2025)" pattern="[TA]\.\d{2}\.\d{4}" title="Format: T.01.2025 or A.00.2025" required>
            <input type="file" name="csv_file" accept=".csv" required>
            <input type="submit" value="Upload Students">
        </form>
        <?php else: ?>
        <form method="get">
            <button type="submit">Upload Another File</button>
            <button type="button" onclick="window.location.href='admin-dashboard.php'">Done</button>
        </form>
        <?php endif; ?>
    </div>
</body>
</html>


