<?php
//include_once ('../../includes/DB/Connection.php');
include_once __DIR__ . '/../../includes/DB/Connection.php';
//include_once ('../student/classes/Student.php');
include_once __DIR__ . '/../classes/Student.php';

session_start();
// session_destroy();


if (isset($_SESSION['log_session']) && !empty($_SESSION['log_session'] && $_SESSION['log_session']['user_role_id'] == '5')) { // Student

    $user_id = $_SESSION['log_session']['user_id'];
    $user_role_name = $_SESSION['log_session']['user_role_name'];
    $user_role_id = $_SESSION['log_session']['user_role_id'];
    $user_first_name =  $_SESSION['log_session']['user_first_name'];
} else {
    header('Location: ../login.php');
    exit();
}


// Create instance of Connection class
$connection = new Connection();
$db = $connection->connect();

// Create instance of Student class
$student = new Student($db);
$student_id = $user_id;

// Get student details
$studentDetails = $student->getStudentById($student_id);


// Handle form submissions
if ($_SERVER["REQUEST_METHOD"] == "POST") {

    // Check if it's an AJAX request for qualifications
    if (isset($_POST['educationTypeId']) && !isset($_POST['upload'])) {
        $educationTypeId = (int)$_POST['educationTypeId'];
        $qualifications = $student->selectQualificationByTypeId($educationTypeId);
        echo json_encode($qualifications);
        exit();
    }


    if (isset($_POST['upload'])) {

        date_default_timezone_set('Asia/Colombo');
        $server_date = date("Y-m-d");
        $server_time = date("H:i:s");

        // Use server date and time directly
        $education_created_date = $server_date;
        $education_created_time = $server_time;
        $education_updated_date = $server_date;
        $education_updated_time = $server_time;
        // Validate inputs

        $education_institute = htmlspecialchars($_POST['educationInstitute']);
        $education_additional_info = htmlspecialchars($_POST['AdditionalInfo']);
        $education_start_date = htmlspecialchars($_POST['startDate']);
        $education_end_date = htmlspecialchars($_POST['endDate']);
        $education_current_study = htmlspecialchars($_POST['currentStudy']);
        $educationTypeId = (int)$_POST['educationTypeId'];
        $qualification = (int)$_POST['qualification'];

        // Initialize file URL to NULL
        $file_url_campus = NULL;
        $education_doc_status = 0; // Default to 0

        $rootPath = dirname(dirname(dirname(__FILE__)));

        // Relative path from the project root to the base upload directory
        $upload_base_dir = "/student/assets/uploads/documents/education/";

        // Define the target directory
        $target_upload_dir = $rootPath . $upload_base_dir;
         // Create student-specific directory if it doesn't exist
         $student_upload_dir = $target_upload_dir . $student_id . '/';

        if (!file_exists($student_upload_dir)) {
            mkdir($student_upload_dir, 0777, true); // Recursive directory creation
        }

       

        // Check if a file is uploaded
        if (!empty($_FILES['campus_certificate']['name'][0])) {
            // Get the original file name
            $original_file_name = basename($_FILES['campus_certificate']['name'][0]);

            // Extract the file extension
            $file_extension = pathinfo($original_file_name, PATHINFO_EXTENSION);

            // Allow only PDF files
            $allowedFormats = array("pdf");
            if (!in_array($file_extension, $allowedFormats)) {
                echo "<script>alert('Sorry, only PDF files are allowed.');
        window.location.href = 'profile.php'; 
        </script>";
                exit();
            }

            // Generate a unique file name using the uniqueid
            $uniqueid = uniqid();
            $unique_file_name = pathinfo($original_file_name, PATHINFO_FILENAME) . "_" . $uniqueid . "_" . uniqid() . "." . $file_extension;

            // Full path to the upload directory with the new unique file name
            $file_url = $student_upload_dir . $unique_file_name;

            // Get the temporary file path
            $file_tmp_campus = $_FILES['campus_certificate']['tmp_name'][0];

            // Move the uploaded file to the new location
            if (move_uploaded_file($file_tmp_campus, $file_url)) {
                $education_doc_status = 1; // Set status to 1 after successful upload

                $file_url_campus = $upload_base_dir . $student_id . '/' . $unique_file_name;
            } else {
                echo "<script>alert('Error uploading document. Please try again.');
                window.location.href = 'profile.php'; 
                </script>";
                exit();
            }
           
        } 
        

        // Insert into database
        if ($student->insertEducationDetails(
            $education_created_date,
            $education_created_time,
            $education_updated_date,
            $education_updated_time,
            $education_additional_info,
            $education_institute,
            $education_start_date,
            $education_end_date,
            $education_current_study,
            $educationTypeId,
            $qualification,
            $file_url_campus,
            $education_doc_status,
            $student_id
        )) {
            header("Location: profile.php?upload_success=1");
            exit();
        } else {
            $upload_error = "Error inserting education details into the database. Please try again.";
            error_log($upload_error);
        }
    }


    // Check if the form is submitted for gender update
    if (isset($_POST['gender'])) {
        $selectedGender = $_POST['gender'];
        if ($student->updateGender($student_id, $selectedGender)) {
            $studentDetails = $student->getStudentById($student_id);
            header("Location: profile.php?gender_update_success=1");
            exit();
        } else {
            $gender_update_error = "Error updating gender. Please try again.";
        }
    }


    if (isset($_POST['phone3'])) {
        $newPhone3 = $_POST['phone3'];

        if ($student->updateContactInfo($student_id, $newPhone3)) {
            $studentDetails = $student->getStudentById($student_id);
            header("Location: profile.php?contact_update_success=1");
            exit();
        } else {
            $contact_update_error = "Error updating phone number. Please try again.";
        }
    }
}




// if(isset($_POST['educationTypeId'])) {
// $selectedTypeId = $_POST['educationTypeId'];
// ($student->selectQualificationByTypeId($selectedTypeId));
// exit();
// }



// if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['educationTypeId'])) {
// $educationTypeId = (int)$_POST['educationTypeId'];
// $qualifications = $student->selectQualificationByTypeId($educationTypeId);
// echo json_encode($qualifications);
// exit();
//