<?php
ini_set('display_errors', 1);

require_once '../../../resources/base_path_include.php';
require_once $base_path_to_learning_resources  . "includes/connect.php"; // use require for mandatory files
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

//valdation file
require_once $base_path_to_learning_resources . 'lib/validate_function.php';
require_once $base_path_to_learning . 'user_management/authenticate.php';
require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'principal_api/modules/timetable/timetable_functions.php';

//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

$postdata = json_decode(file_get_contents("php://input"), true);

checkIfNoPhpContentsReceive();

if (
    !isset($postdata['faculty_id']) or !checkIfIssetAndNotEmpty($postdata['faculty_id']) or
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type'])  or
    !isset($postdata['jwt_token']) or  !checkIfIssetAndNotEmpty($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}
validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
//then workspace_id is iin decodede data of jwt use from there
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$institution_id = $jwt_validate->data->institution_id;
$branch_id = $jwt_validate->data->branch_id;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["principal"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
require_once $base_path_to_learning . 'user_management/user_versioning.php';

$version = isset($_POST['version']) ? $_POST['version'] : (isset($postdata['version']) ? $postdata['version'] : null);
$updated_time = isset($_POST['updated_time']) ? $_POST['updated_time'] : (isset($postdata['updated_time']) ? $postdata['updated_time'] : null);

$response = user_data_refresh($conn_rjllearning, $conn_rjllearning_specific, $version, $updated_time, $userid, $institution_id);

// preparing query to validate time
$sql_check_time_lapping = "SELECT COUNT(*) as conflict_count FROM timetable WHERE type = 'timetable' AND faculty_id = ? AND academic_session_id = ? AND institution_id = ? AND branch_id = ? AND day = ? AND ((period_start < ? AND end_time > ?))"; // -- Overlapping time range
$check_time_lapping = $conn_rjllearning_specific->prepare($sql_check_time_lapping);

if ($postdata['function_type'] == "create_faculty_role") {

    $faculty_id = trim($postdata['faculty_id']);

    //timetable info
    $timetable_info = $postdata['timetable_info'];
    if (empty($postdata['timetable_info'])) {
        $timetable_info = null;
    }

    $class_incharge = (isset($postdata['class_incharge']) and !empty($postdata['class_incharge'])) ? ($postdata['class_incharge']) : null;
    if ($class_incharge !=  null) {
        if (!is_array($class_incharge)) {
            errorreturn("Invalid class incharge.");
        }
    }

    $academic_id = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($academic_id != true) {
        errorreturn("Access denied. Academic session not active.");
    }

    $sql_faculty = $conn_rjllearning_specific->prepare("SELECT * FROM faculty_info WHERE id = ? and institution_id = ? and branch_id = ?");
    $sql_faculty->execute(array($faculty_id, $institution_id, $branch_id));
    $result_faculty = $sql_faculty->fetchAll();
    if (count($result_faculty) < 1) {
        errorreturn("Faculty does not exists.");
    }

    $class_validated_array = [];
    $section_validated_array = [];
    // Check class info
    function validateClassExistence($conn_rjllearning_specific, $institution_id, $class_id)
    {
        $sql_class_validate = $conn_rjllearning_specific->prepare("SELECT * FROM class_info WHERE id = ? AND institution_id = ?");
        if (!in_array($class_id, $GLOBALS['class_validated_array'])) {
            $sql_class_validate->execute([$class_id, $institution_id]);
            $result_class = $sql_class_validate->fetchAll();
            if (count($result_class) < 1) {
                errorreturn("Class does not exist: $class_id.");
            }
            $GLOBALS['class_validated_array'][] = $class_id;
        }
    }

    // Check section info
    function validateSectionExistence($conn_rjllearning_specific, $institution_id, $section_id)
    {
        $sql_section_validate = $conn_rjllearning_specific->prepare("SELECT * FROM section_info WHERE id = ? AND institution_id = ?");
        if (!in_array($section_id, $GLOBALS['section_validated_array'])) {
            $sql_section_validate->execute([$section_id, $institution_id]);
            $result_section = $sql_section_validate->fetchAll();
            if (count($result_section) < 1) {
                errorreturn("Section does not exist: $section_id.");
            }
            $GLOBALS['section_validated_array'][] = $section_id;
        }
    }


    // Check if $class_incharge has valid data
    if ($class_incharge != null && is_array($class_incharge) && count($class_incharge) > 0) {
        foreach ($class_incharge as $index => $data) {
            // Ensure $data is an array and contains valid keys
            if (!isset($data['class_id']) || !isset($data['section_id']) || empty($data['class_id']) || empty($data['section_id'])) {
                // Skip this iteration if data is invalid
                continue;
            }

            $class_id = $data['class_id'];
            $section_id = $data['section_id'];

            validateClassExistence($conn_rjllearning_specific, $institution_id, $class_id);
            validateSectionExistence($conn_rjllearning_specific, $institution_id, $section_id);
        }
    }

    // Set the isolation level to READ COMMITTED
    $conn_rjllearning_specific->exec("SET TRANSACTION ISOLATION LEVEL READ COMMITTED");
    // Begin a transaction
    $conn_rjllearning_specific->beginTransaction();

    // Delete timetable of that particular faculty (faculty role, timetable)
    $delete_timetable = deleteAllFacultyTimetable($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $branch_id, $academic_id, $faculty_id);

    foreach ($timetable_info as $temp) {
        $class_id = $temp['class_id'];
        $section_id = $temp['section_id'];
        // $subject_id = $temp['subject_id'];
        $subject_id = (isset($temp['subject_id']) && !empty($temp['subject_id'])) ? $temp['subject_id'] : null;
        $period_start = (isset($temp['period_start']) && !empty($temp['period_start'])) ? $temp['period_start'] : null;
        $end_time = (isset($temp['end_time']) && !empty($temp['end_time'])) ? $temp['end_time'] : null;
        $day = (isset($temp['day']) && !empty($temp['day'])) ? $temp['day'] : null;

        // Check if branch, class, subject exist
        $check_branch_class = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, $class_id, $subject_id, $institution_id);
        if (!$check_branch_class) {
            errorreturn("Access denied.");
        }

        // Validate the days input
        $allowedDays = ['1', '2', '3', '4', '5', '6', '7'];
        if ($day != null) {
            foreach ($day as $one_day) {
                if (!in_array($one_day, $allowedDays)) {
                    errorreturn("Invalid input. Please select a valid day.");
                }
            }
            $imploded_string = serialize($day);
        } else {
            $imploded_string = null;
        }



        // Validate class, section, and subject existence
        // class and subject already validated through checkBranchClassSubject
        validateSectionExistence($conn_rjllearning_specific, $institution_id, $section_id);

        // Validate time format and range
        if ($period_start != null && !CheckValidateTime($period_start)) {
            errorreturn('Invalid Start Time Format');
        }

        if ($end_time != null && !CheckValidateTime($end_time)) {
            errorreturn('Invalid End Time Format');
        }

        if ($period_start != null && $end_time != null && $period_start >= $end_time) {
            errorreturn('Invalid Time Range');
        }


        if ($day == null or $period_start == null or $end_time == null or empty($day)) {
            // day has not been alloted this goes to faculty_roles
            if ($day != null and !empty($day)) {
                foreach ($day as $days) {
                    // Insert data for each day
                    $sql_insert = "INSERT INTO timetable (institution_id, branch_id, faculty_id, academic_session_id, class_id, subject_id, section_id, period_start, end_time, day, type, status, date_created, time_created) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                    $stmt_insert = $conn_rjllearning_specific->prepare($sql_insert);
                    $stmt_insert->execute([$institution_id, $branch_id, $faculty_id, $academic_id, $class_id, $subject_id, $section_id, $period_start, $end_time, $days, 'faculty_role', '1', date('Y-m-d'), time()]);
                    
                    updateUserRoleTimestamp($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $faculty_id);
                }
            } else {
                // Insert data for each day
                $sql_insert = "INSERT INTO timetable (institution_id, branch_id, faculty_id, academic_session_id, class_id, subject_id, section_id, period_start, end_time, day, type, status, date_created, time_created) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                $stmt_insert = $conn_rjllearning_specific->prepare($sql_insert);
                $stmt_insert->execute([$institution_id, $branch_id, $faculty_id, $academic_id, $class_id, $subject_id, $section_id, $period_start, $end_time, null, 'faculty_role', '1', date('Y-m-d'), time()]);
                
                updateUserRoleTimestamp($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $faculty_id);
            }
        } else {
            foreach ($day as $days) {
                // preparing query to validate time
                $check_time_lapping->execute(array($faculty_id, $academic_id, $institution_id, $branch_id, $days, $end_time, $period_start));
                if ($check_time_lapping->fetchAll()[0]['conflict_count'] > 0) {
                    // get name for faculty
                    $faculty_name = getFacultyInfo($conn_rjllearning_specific, $institution_id, $faculty_id)['name'];
                    $dateTime = new DateTime();
                    $dateTime->setISODate(2025, 1, $days); // Arbitrary week and year
                    errorreturn($faculty_name . ' has another class in their timetable for ' . $dateTime->format('l') . ' at or conflicting with ' . $period_start . ' - ' . $end_time . ' time slot');
                }

                // Insert data for each day
                $sql_insert = "INSERT INTO timetable (institution_id, branch_id, faculty_id, academic_session_id, class_id, subject_id, section_id, period_start, end_time, day, type, status, date_created, time_created) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
                $stmt_insert = $conn_rjllearning_specific->prepare($sql_insert);
                $stmt_insert->execute([$institution_id, $branch_id, $faculty_id, $academic_id, $class_id, $subject_id, $section_id, $period_start, $end_time, $days, 'timetable', '1', date('Y-m-d'), time()]);
                
                updateUserRoleTimestamp($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $faculty_id);
            }
        }
    }


    // Store class_incharge if applicable
    if ($class_incharge != null) {
        CreateClassIncharge($conn_rjllearning_specific, $institution_id, $branch_id, $academic_id, $faculty_id, $class_incharge);
    }

    $conn_rjllearning_specific->commit();

    $id = $conn_rjllearning_specific->lastInsertId();
    successreturn(['id' => $id, 'successmsg' => "Successfully timetable added."]);
}
