<?php
class Student
{
    private $conn;
    public function __construct($conn)
    {
        $this->conn = $conn;
         
    }
    
    public function generateUuidV4()
    {
        // Generate 16 random bytes
        $data = openssl_random_pseudo_bytes(16);
    
        // Set version to 0100 (UUIDv4)
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40);
        // Set variant to 10xxxxxx
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
    
        // Return the formatted UUID
        return sprintf(
            '%08s-%04s-%04s-%04s-%12s',
            bin2hex(substr($data, 0, 4)),
            bin2hex(substr($data, 4, 2)),
            bin2hex(substr($data, 6, 2)),
            bin2hex(substr($data, 8, 2)),
            bin2hex(substr($data, 10, 6))
        );
    }



    public function getStudentRegisteredCourses(){
///*temprary just for Feb exams*/ rc.co_status='1' remove it if not feb
        $query = "SELECT
                        rc.st_id,
                        sc.course_code,
                        sc.title,
                        sc.unit
                        /*,sc.status ,sc.semester, sc.sess_id*/

                    FROM
                            registered_courses rc
                        INNER JOIN
                            payments_tbl pt ON pt.reg_number=rc.st_id   AND  
                          pt.sess_id = (SELECT st.sess_id FROM sessionreg_tbl st INNER JOIN payment_active_activity paa ON paa.session_name=st.session_name  AND service='REGISTRATION' AND paa.is_active='1'  ORDER BY paa.session_name DESC LIMIT 1)
                        AND pt.reg_semester=(SELECT paa.month FROM  payment_active_activity paa WHERE service='REGISTRATION' AND paa.is_active='1'  ORDER BY paa.session_name DESC LIMIT 1)
                                                INNER JOIN 
                            school_curriculum sc ON sc.code = rc.reg_code AND sc.semester=pt.reg_semester AND sc.sess_id=pt.sess_id";

        $result = mysqli_query($this->conn, $query);
        $registeredCourses = [];

        while($row = mysqli_fetch_assoc($result)){

            $registeredCourses[$row['st_id']][] = $row; //Store Registed Course an set examination number (Index Number) as a key of array
        }

        return $registeredCourses;
    }
    
public function getAllStudentsAsZip() {
    require '../aws/app/start.php'; // AWS S3 SDK initialization

    $studentRegisteredCourses = $this->getStudentRegisteredCourses();

    // SQL query
    $query = "SELECT * FROM registered_student_for_api";
    
    // Execute the query and check for errors
    $result = mysqli_query($this->conn, $query);

    // Check if the query execution is successful
    if (!$result) {
        die("Database query failed: " . mysqli_error($this->conn));
    }

    // Temporary folder to store images
    $tempDir = sys_get_temp_dir() . '/student_passports/';
    if (!file_exists($tempDir)) {
        mkdir($tempDir, 0777, true);
    }

    $zip = new ZipArchive();
    $zipFileName = $tempDir . 'student_passports.zip';

    // Open the zip archive
    if ($zip->open($zipFileName, ZipArchive::CREATE) !== TRUE) {
        die("Could not create zip file.");
    }

    // Fetch data
    while ($row = mysqli_fetch_assoc($result)) {

        $examinationNumber = $row['examination_number']; // Examination Number

        // Check if passport (image key) exists and is valid
        if (!empty($row['passport'])) {
            // Fetch image from S3
            try {
                // Get the image content from S3
                $resultS3 = $s3->getObject([
                    'Bucket' => $config['s3']['bucket'],
                    'Key'    => $row['passport'], // The passport image path from the database
                ]);
            
                // Get the binary content of the image
                $imageData = $resultS3['Body']->getContents();

                // Create a local file with the passport name
                $imageFilePath = $tempDir . $row['passport'];
                file_put_contents($imageFilePath, $imageData);

                // Add the file to the zip archive
                $zip->addFile($imageFilePath, $row['passport']);
            } catch (Aws\Exception\AwsException $e) {
                // Handle S3 exception
                continue; // Skip this image if there's an error
            }
        }
    }

    // Close the zip file
    $zip->close();

    // Force download the zip file
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="student_passports.zip"');
    header('Content-Length: ' . filesize($zipFileName));
    readfile($zipFileName);

    // Clean up: Delete temporary images and zip file
    array_map('unlink', glob("$tempDir/*.*"));
    rmdir($tempDir);
}


    public function getAllStudents(){
        
        $studentRegisteredCourses = $this->getStudentRegisteredCourses();
        

        $query = "SELECT * FROM registered_student_for_api";
        $result = mysqli_query($this->conn, $query);
        $students = [];
        while($row = mysqli_fetch_assoc($result)){

            $examinationNumber = $row['examination_number'];//Examination Number (Index Number)
            
            if(isset($studentRegisteredCourses[$examinationNumber])){//Check if Array Key of Examination number (Index Number) Exist
               
                $registeredCourses = ["registered_courses"=> $studentRegisteredCourses[$examinationNumber]]; //Get Student Registered Course

            }else{//Else assign Empty Array

                $registeredCourses = [];

            }

           $students[] = array_merge($row, $registeredCourses);
            
        }

        return $students;
        
    }
    
    public function studentPassports(){
        $query = "SELECT * FROM picture_strings limit 4";
        $result = mysqli_query($this->conn, $query);
        $passportData = [];
       while($row = mysqli_fetch_assoc($result)){
           $passportData []= [
                    "exam_number"=>$row['pic_form_no'],
                    "passport"=>$row['pic_name'],
               ];
           
       }
       
       return $passportData;
    }
    
    public function storeImageString($picName, $picString){
        $query = "INSERT IGNORE INTO picture_strings(`pic_form_no`, `pic_name`) VALUES ('$picName', '$picString')";
        $result = mysqli_query($this->conn, $query);
    }
    
    public function temQuery(){
        $query = "SELECT * FROM copy_registration_vs_result r INNER JOIN payments_tbl p ON r.index_number=p.reg_number AND p.reg_semester='FEBRUARY' AND p.sess_id='6'  WHERE `is_equal` = '0' AND `result_courses` != ''";
        $result = mysqli_query($this->conn, $query);
        $sn=0;
         $is=0;
        while($fetch = mysqli_fetch_assoc($result)){
            $sn++;
            
            $indexNumber = $fetch['index_number'];
            $resultCourses = $fetch['result_courses'];
            $courseCodeArray = json_decode($resultCourses);
            $deptId = $fetch['course_id'];
            
            foreach($courseCodeArray as $courseCode){
                $is++;
                $queryCurr = "SELECT * FROM `school_curriculum` WHERE semester='FEBRUARY' AND sess_id='6' AND  dept_id='$deptId' AND course_code='$courseCode'";
                $resultCurr = mysqli_query($this->conn, $queryCurr);
                $fetchRegCode = mysqli_fetch_assoc($resultCurr);
                $regCode = $fetchRegCode['code'];
                
                $insertQuery = "INSERT INTO `registered_courses` (`st_id`, `reg_code`, `co_status`) VALUES ('$indexNumber', '$regCode', '1')";
                $resultinsertQuery = mysqli_query($this->conn, $insertQuery);
                
                echo "$is, $indexNumber, $courseCode, $regCode";

                echo "<br/>";
            }
        }
        
        exit;
        
    }
    
     public function selectImageString(){
        $query = "SELECT * FROM picture_strings";
        $result = mysqli_query($this->conn, $query);
        return $result;
    }
    
     public function compareRegExam(){
        $query = "SELECT * FROM payments_tbl WHERE `being_pay_for` = 'REGISTRATION' AND `sess_id` = '6' AND `reg_semester` = 'FEBRUARY'";
        $result = mysqli_query($this->conn, $query);
        return $result;
    }
    
public function getAllStudentsTem() {

    require '../aws/app/start.php'; // AWS S3 SDK initialization

    $studentRegisteredCourses = $this->getStudentRegisteredCourses();

    // SQL query
    $query = "SELECT * FROM registered_student_for_api";
    
    // Execute the query and check for errors
    $result = mysqli_query($this->conn, $query);

    // Check if the query execution is successful
    if (!$result) {
        die("Database query failed: " . mysqli_error($this->conn));
    }

    $students = [];

    // Fetch data
    while ($row = mysqli_fetch_assoc($result)) {

        $examinationNumber = $row['examination_number']; // Examination Number
        
        // Check if student has registered courses
        $registeredCourses = isset($studentRegisteredCourses[$examinationNumber])
            ? ["registered_courses" => $studentRegisteredCourses[$examinationNumber]]
            : [];

        // Check if passport (image key) exists and is valid
        if (!empty($row['passport'])) {
            // Fetch image from S3
            try {
                // Get the image content from S3
                $resultS3 = $s3->getObject([
                    'Bucket' => $config['s3']['bucket'],
                    'Key'    => $row['passport'], // The passport image path from the database
                ]);
            
                // Get the binary content of the image
                $imageData = $resultS3['Body']->getContents();

                // Convert image content to Base64
                $passportBase64 = base64_encode($imageData);

            } catch (Aws\Exception\AwsException $e) {
                // Handle S3 exception
                $passportBase64 = ''; // Set to empty if the image is not found or another error occurs
            }
        } else {
            // If passport key is empty, set the Base64 string as empty
            $passportBase64 = '';
        }

        // Prepare student data
        $studentDataArray = [
            "candidate_name" => $row['candidate_name'],
            "state" => $row['state'],
            "school" => $row['school'],
            "examination_number" => $row['examination_number'],
            "passport" => $passportBase64, // Add the Base64-encoded image or an empty string
        ];
        
        $this->storeImageString($row['examination_number'], $passportBase64);

        // Merge student data with registered courses and push to array
        $students[] = array_merge($studentDataArray, $registeredCourses);
    }

    return $students; // Return all students with their data
}


    public function getStudentById($examinationNumber){

        $studentRegisteredCourses = $this->getStudentRegisteredCourses();

        $realExaminationNumber = str_replace("_", "/", $examinationNumber);
        
        $query = "SELECT * FROM registered_student_for_api WHERE examination_number = '$realExaminationNumber'";
        $result = mysqli_query($this->conn, $query);
        $student = mysqli_fetch_assoc($result);
       
        $examinationNumber = $student['examination_number'];//Examination Number (Index Number)
        
        if(isset($studentRegisteredCourses[$examinationNumber])){//Check if Array Key of Examination number (Index Number) Exist
           
            $registeredCourses = ["registered_courses"=> $studentRegisteredCourses[$examinationNumber]]; //Get Student Registered Course

        }else{//Else assign Empty Array

            $registeredCourses = [];
            
        }

        return array_merge($student, $registeredCourses);
        //return array_merge($student, $registeredCourses);
    }

    public function addStudentResult($studentResults){
         $uuid = $this->generateUuidV4();
        
         foreach($studentResults as $studentResult){
             $examinationNumber = strtoupper(mysqli_real_escape_string($this->conn,$studentResult['examination_number']));
             $month = strtoupper(mysqli_real_escape_string($this->conn,$studentResult['month']));
             $year = strtoupper(mysqli_real_escape_string($this->conn,$studentResult['year']));
             $results = $studentResult['results'];


             foreach($results as $result){
                 $courseCode = strtoupper(mysqli_real_escape_string($this->conn,$result['course_code']));
                 $score = strtoupper(mysqli_real_escape_string($this->conn,$result['score']));
                //Insert Reord
                $query = "INSERT INTO api_student_scores(index_number, month, year, course_code, score, created_at, pulling_uuid) VALUES ('$examinationNumber', '$month',  '$year', '$courseCode', '$score', '".date("d-m-Y h:i:s a")."', '$uuid')";
                $result = mysqli_query($this->conn, $query);
             }
             

          

            
        
         }
        echo "Record Inserted Successfully <br/> <a href='push.php?puuid=$uuid'>Click here to push it to live</a>";
       
       
        // if($result){
        //     return true;
        // }else{
        //     return false;
        // }
    }
    
    public function pushStudentResult($pullingUuid){
        $query = "INSERT IGNORE INTO exams( reg_no, exam_code, exam, upload_by, upload_dateTime, approval_status, approved_by, approval_dateTime, is_cbt_score, api_student_score_id, api_student_score_pulling_uuid)
                  SELECT reg_no, exam_code, exam, upload_by, upload_dateTime, approval_status, approved_by, approval_dateTime, is_cbt_score, api_student_score_id, api_student_score_pulling_uuid FROM api_student_score_filter a WHERE api_student_score_pulling_uuid LIKE '$pullingUuid' AND payment_status = '1' AND curriculum_status ='1' AND course_status = 1";
        $result = mysqli_query($this->conn, $query);
        
        echo "Data has been push successfully to live";
        
    }
    
 
    
    // public function updateStudent($id, $data){

    // }

    // public function deleteStudentById($id){
    //     $query = "DELETE FROM registered_student_for_api WHERE id = $id";
    //     $result = mysqli_query($this->conn, $query);

    //     if($result){
    //         return true;
    //     }else{
    //         return false;
    //     }
    // }
}