<?php
error_reporting(0);
require_once("../../public/connection.php");
require_once("../../public/functions.php");

$date = date('d-M-Y');
$select = "--select--";

if(isset($_POST["upload_subject_sheet_btn"])){
    $class = htmlentities(trim(mysqli_real_escape_string($connection, $_POST['class'])));
    $term = htmlentities(trim(mysqli_real_escape_string($connection, $_POST['term'])));
    $session = htmlentities(trim(mysqli_real_escape_string($connection, $_POST['session'])));
    $subject = htmlentities(trim(mysqli_real_escape_string($connection, $_POST['subject'])));
    
    if($class === $select || $term === $select || $session === $select || $subject === $select){
        echo "<script type=\"text/javascript\" style='background-color:red;'>
                alert(\"Sorry: All fields must be selected.\");
                window.location = \"modules.php?register_student_subject\";
              </script>";
    } else {
        // Check if file is uploaded without errors
        if ($_FILES["uploadFile"]["error"] == UPLOAD_ERR_OK && is_uploaded_file($_FILES["uploadFile"]["tmp_name"])) {
            $fileName = explode(".", $_FILES["uploadFile"]["name"]);
            $filename = $_FILES["uploadFile"]["tmp_name"];

            // Check if the file has a .csv extension
            if (isset($fileName[1]) && $fileName[1] == "csv") {
                $query = "SELECT * FROM subjects WHERE class = '{$class}' AND subjects = '{$subject}' AND term = '{$term}' AND session = '{$session}' ";
                $run_query = mysqli_query($connection, $query);

                if(mysqli_num_rows($run_query) > 0){
                    echo "<script type=\"text/javascript\" style='background-color:red;'>
                            alert(\"Sorry: Subject has been registered for this Particular Class and Term in this Session.\");
                            window.location = \"modules.php?register_student_subject\";
                          </script>";
                } else {
                    if($_FILES["uploadFile"]["size"] > 0){
                        $openFile = fopen($filename, "r");
                        $number = 0;

                        while($dataFile = fgetcsv($openFile, 3000, ",")){
                            $number++;

                            if($number != 1){
                                // Insert a row into the subjects table from the CSV file
                                $sql = "INSERT INTO subjects(`reg_number`, `name`, `class`, `subjects`, `term`, `session`, `registration_date`) 
                                        VALUES ('{$dataFile[1]}', '{$dataFile[2]}', '{$dataFile[3]}', '{$dataFile[4]}', '{$dataFile[5]}', '{$dataFile[6]}', '{$date}')";
                                $result = mysqli_query($connection, $sql);

                                if(! $result){
                                    echo "<script type=\"text/javascript\">
                                            alert(\"Invalid File: Please Upload a CSV File.\");
                                            window.location = \"modules.php?register_student_subject\";
                                          </script>";
                                    exit;
                                }
                            }
                        }
                        fclose($openFile);

                        // Success message
                        echo "<script type=\"text/javascript\">
                                alert(\"CSV File has been successfully Imported.\");
                                window.location = \"modules.php?register_student_subject\";
                              </script>";

                        // Close the database connection
                        mysqli_close($connection);
                    }
                }
            } else {
                echo "<script type=\"text/javascript\" style='background-color:red;'>
                        alert(\"Sorry: The file must be a CSV file.\");
                        window.location = \"modules.php?register_student_subject\";
                      </script>";
            }
        } else {
            echo "<script type=\"text/javascript\" style='background-color:red;'>
                    alert(\"Sorry: You must choose a file.\");
                    window.location = \"modules.php?register_student_subject\";
                  </script>";
        }
    }
}
?>
