<?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 . 'admin_api/modules/timetable/timetable_functions.php';

require_once $base_path_to_learning . 'user_management/user_versioning.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['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['class_id']) or !checkIfIssetAndNotEmpty($postdata['class_id']) or
    !isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id']) or
    !isset($postdata['section_id']) or !checkIfIssetAndNotEmpty($postdata['section_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;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],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';

if (empty($postdata['timetable_info'])) {
    errorreturn("Timetable required.");
}

$institution_id = trim($postdata['institution_id']);
$class_id = trim($postdata['class_id']);
$section_id = trim($postdata['section_id']);
$branch_id = trim($postdata['branch_id']);

//timetable info
$timetable_info = $postdata['timetable_info'];
// print_r($timetable_info);die();

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

$check_branch_class = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, $class_id, null, $institution_id);
if ($check_branch_class == false) {
    errorreturn("Access denied");
}


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

// Begin a transaction
$conn_rjllearning_specific->beginTransaction();

$sql_table = $conn_rjllearning_specific->prepare("SELECT * FROM  timetable WHERE  institution_id = ? AND branch_id = ? AND academic_session_id = ?   AND  class_id = ? AND section_id= ? and type = 'timetable' ");
$sql_table->execute(array($institution_id, $branch_id, $academic_id, $class_id, $section_id));
$result1 = $sql_table->fetchAll();
$timetable_changed = false;
if (count($result1) >= 1) {

    //delete timetable of that particular class
    $delete_timetable = deleteAllTimetable($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $branch_id, $academic_id, $class_id, $section_id);
    if ($delete_timetable != true) {
        errorreturn("Access denied");
    }
}

$checked_branch_class_subject_pool = [];
// 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_timetable") {
    // validating timing clash i the request
    foreach ($timetable_info as $key => $temp) {
        $period_start = (isset($temp['period_start']) and !empty($temp['period_start'])) ? trim($temp['period_start']) : errorreturn('Start time cannot be left empty.');
        $end_time = (isset($temp['end_time']) and !empty($temp['end_time'])) ? trim($temp['end_time']) : errorreturn('End time cannot be left empty.');

        if ($key > 0) {
            for ($i = 0; $i < $key; $i++) {
                if (($period_start >= $timetable_info[$i]['period_start'] and $period_start <= $timetable_info[$i]['end_time']) or ($end_time >= $timetable_info[$i]['period_start'] and $end_time <= $timetable_info[$i]['end_time'])) {
                    errorreturn('You cannot have conflicting times while creating the time table.');
                }
            }
        }
    }
    foreach ($timetable_info as $temp) {

        $period_start = trim($temp['period_start']);
        $end_time = trim($temp['end_time']);
        foreach ($temp['days'] as $dayrow) {
            if ($dayrow['faculty_id'] != null and $dayrow['subject_id'] != null) {
                $faculty_id = (isset($dayrow['faculty_id']['id']) and !empty($dayrow['faculty_id']['id'])) ? $dayrow['faculty_id']['id'] : null;
                $subject_id = (isset($dayrow['subject_id']['subject_id']) and !empty($dayrow['subject_id']['subject_id'])) ? $dayrow['subject_id']['subject_id'] : null;
            } else {
                $faculty_id =  null;
                $subject_id =  null;
            }
            $day = (isset($dayrow['day']) and !empty($dayrow['day'])) ? $dayrow['day'] : null;

            if (!in_array($branch_id . '_' . $class_id . '_' . $subject_id, $checked_branch_class_subject_pool)) {
                // created a pool to check locally cause of repetition
                $check_branch_class_subject = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, $class_id, $subject_id, $institution_id);

                if ($check_branch_class_subject == false) {
                    errorreturn("Access denied");
                } else {
                    $checked_branch_class_subject_pool[] = $branch_id . '_' . $class_id . '_' . $subject_id;
                }
            }
            $allowedDays = ['1', '2', '3', '4', '5', '6', '7'];
            if ($day !=  null) {
                // Validate if the input is a valid day
                if (!in_array($day, $allowedDays)) {
                    errorreturn("Invalid input. Please select a valid day.");
                }
            } else {
                $day = null;
            }

            if ($period_start !=  null) {
                if (!CheckValidateTime($period_start)) {

                    errorreturn('Invalid Start Time Format');
                }
            }
            if ($end_time !=  null) {
                //validating-24-hour-time-format
                if (!CheckValidateTime($end_time)) {

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

            // checking if this faculty has some other class at this time
            if ($faculty_id != null and $subject_id != null) {
                $check_time_lapping->execute(array($faculty_id, $academic_id, $institution_id, $branch_id, $day, $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, $day); // 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');
                }
            }

            validateBranchClassSection($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id, $support_branch_all = 0, $checkClass = 0, $support_class_all = 0, $checkSection = 1,  $support_section_all = 0);
            if ($timetable_changed == true) {
                $sql = "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 =  $conn_rjllearning_specific->prepare($sql);
                $stmt->execute(array($institution_id, $branch_id, $faculty_id, $academic_id, $class_id, $subject_id, $section_id, $period_start, $end_time, $day, 'timetable', '1', date('Y-m-d'), time()));
                
                updateUserRoleTimestamp($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $faculty_id);
            } else {

                $sql = "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 =  $conn_rjllearning_specific->prepare($sql);
                $stmt->execute(array($institution_id, $branch_id, $faculty_id, $academic_id, $class_id, $subject_id, $section_id, $period_start, $end_time, $day, 'timetable', '1', date('Y-m-d'), time()));
                
                updateUserRoleTimestamp($conn_rjllearning, $conn_rjllearning_specific, $workspace_id, $institution_id, $faculty_id);
            }
        }
    }
    $conn_rjllearning_specific->commit();
    $id = $conn_rjllearning_specific->lastInsertId();
    successreturn(array('id' => $id, 'successmsg' => "Successfully timetable added."));
}
