<?php
include "db.php";

session_start();

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

$db = mysqli_connect($host, $username, $password, $dbname);
if (!$db) {
    die("Database connection failed: " . mysqli_connect_error());
}

// Handle blank CSV template download
if (isset($_GET['download']) && $_GET['download'] === 'blank_csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="blank_student_template.csv"');

    $header = [
        'student_name',
        'course_name',
        'mobile_number',
        'email_id',
        'current_address',
        'permanent_address',
        'parents_contact_number',
        'aadhaar_number',
        'date_of_joining',
        'father_name',
        'mother_name',
        'date_of_birth'
    ];

    $output = fopen('php://output', 'w');
    fputcsv($output, $header);
    fclose($output);
    exit();
}

// Handle CSV upload for bulk insert
if ($_SERVER["REQUEST_METHOD"] === "GET" && isset($_GET['upload_csv'])) {
    if (isset($_FILES['csv_file']) && $_FILES['csv_file']['error'] === UPLOAD_ERR_OK) {
        $fileTmpPath = $_FILES['csv_file']['tmp_name'];
        $file = fopen($fileTmpPath, 'r');

        $header = fgetcsv($file);
        $expectedHeader = [
            'student_name',
            'course_name',
            'mobile_number',
            'email_id',
            'current_address',
            'permanent_address',
            'parents_contact_number',
            'aadhaar_number',
            'date_of_joining',
            'father_name',
            'mother_name',
            'date_of_birth'
        ];

        if ($header !== $expectedHeader) {
            $error_message = "CSV header does not match expected format.";
        } else {
            $prefix = "RT23";
            $next_id = 1;

            $query = "SELECT student_id FROM students WHERE student_id LIKE '$prefix%'";
            $result = mysqli_query($db, $query);
            $last_id = 0;
            while ($row = mysqli_fetch_assoc($result)) {
                $current_id = intval(substr($row["student_id"], strlen($prefix)));
                if ($current_id > $last_id) {
                    $last_id = $current_id;
                }
            }
            $next_id = $last_id + 1;

            $insertedCount = 0;
            $errorRows = [];

            while (($row = fgetcsv($file)) !== false) {
                if (count($row) !== count($expectedHeader)) {
                    $errorRows[] = "Invalid column count in row: " . implode(',', $row);
                    continue;
                }

                list(
                    $student_name,
                    $course_name,
                    $mobile_number,
                    $email_id,
                    $current_address,
                    $permanent_address,
                    $parents_contact_number,
                    $aadhaar_number,
                    $date_of_joining,
                    $father_name,
                    $mother_name,
                    $date_of_birth
                ) = $row;

                $student_id = $prefix . str_pad($next_id, 4, "0", STR_PAD_LEFT);
                $next_id++;

                $query = "INSERT INTO students (student_id, student_name, course_name, mobile_number, email_id, current_address, permanent_address, parents_contact_number, aadhaar_number, date_of_joining, father_name, mother_name, date_of_birth, isCertIssued) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 0)";
                $stmt = mysqli_prepare($db, $query);
                mysqli_stmt_bind_param($stmt, "sssssssssssss", $student_id, $student_name, $course_name, $mobile_number, $email_id, $current_address, $permanent_address, $parents_contact_number, $aadhaar_number, $date_of_joining, $father_name, $mother_name, $date_of_birth);
                if (mysqli_stmt_execute($stmt)) {
                    $insertedCount++;
                } else {
                    $errorRows[] = "Failed to insert row with student name: $student_name";
                }
                mysqli_stmt_close($stmt);
            }
            fclose($file);

            if (empty($errorRows)) {
                $success_message = "CSV uploaded successfully. $insertedCount students inserted.";
            } else {
                $error_message = "CSV upload completed with errors: " . implode('; ', $errorRows);
            }
        }
    } else {
        $error_message = "Error uploading CSV file.";
    }
}

// Handle single student registration form submission
if ($_SERVER["REQUEST_METHOD"] === "GET" && !isset($_GET['upload_csv'])) {
    // Retrieve form data
    $student_name = $_GET["student_name"];
    $course_name = $_GET["course_name"];
    $mobile_number = $_GET["mobile_number"];
    $email_id = $_GET["email_id"];
    $current_address = $_GET["current_address"];
    $permanent_address = $_GET["permanent_address"];
    $parents_contact_number = $_GET["parents_contact_number"];
    $aadhaar_number = $_GET["aadhaar_number"];
    $date_of_joining = $_GET["date_of_joining"];

    $father_name = $_GET["father_name"];
    $mother_name = $_GET["mother_name"];
    $date_of_birth = $_GET["date_of_birth"];

    // Generate student ID
    $prefix = "RT23"; // Prefix for student ID
    $next_id = 1; // Starting number for student ID

    // Check if the generated ID already exists
    $query = "SELECT student_id FROM students WHERE student_id LIKE '$prefix%'";
    $result = mysqli_query($db, $query);
    $num_rows = mysqli_num_rows($result);

    if ($num_rows > 0) {
        // Extract the numeric part of the last student ID and increment it
        $last_id = 0;
        while ($row = mysqli_fetch_assoc($result)) {
            $current_id = intval(substr($row["student_id"], strlen($prefix)));
            $last_id = max($last_id, $current_id);
        }
        $next_id = $last_id + 1;
    }

    $student_id = $prefix . str_pad($next_id, 4, "0", STR_PAD_LEFT);

    // Insert new student into database
    $query = "INSERT INTO students (student_id, student_name, course_name, mobile_number, email_id, current_address, permanent_address, parents_contact_number, aadhaar_number, date_of_joining, father_name, mother_name, date_of_birth, isCertIssued) VALUES ('$student_id', '$student_name', '$course_name', '$mobile_number', '$email_id', '$current_address', '$permanent_address', '$parents_contact_number', '$aadhaar_number', '$date_of_joining', '$father_name', '$mother_name', '$date_of_birth', 0)";
    if (mysqli_query($db, $query)) {
        $success_message = "Student registered successfully.";
    } else {
        $error_message = "Error: " . mysqli_error($db);
    }
}
?>

<!DOCTYPE html>
<html>
<head>
    <title>Registration Result</title>
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
</head>
<body>
    <?php include "nav.php"; ?>
    <div class="container mt-5">
        <?php if (isset($success_message)): ?>
            <div class="alert alert-success" role="alert">
                <?php echo $success_message; ?>
            </div>
        <?php endif; ?>
        <?php if (isset($error_message)): ?>
            <div class="alert alert-danger" role="alert">
                <?php echo $error_message; ?>
            </div>
        <?php endif; ?>
        <a href="register-student.php" class="btn btn-primary">Back to Registration</a>
    </div>
    <!-- Bootstrap JS -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
