<?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';
//db access function
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

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

if (
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_id']) or
    !isset($postdata['class_id']) or !checkIfIssetAndNotEmpty($postdata['class_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);
}
function getSpecificTimetable($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id)
{

    $sql_timetable = "SELECT * FROM  timetable where institution_id =? and branch_id =?  AND type = 'timetable'";
    $array_params = [$institution_id, $branch_id];
    $sql_timetable .= " AND class_id = ? ";
    $array_params[] = $class_id;
    $sql_timetable .= " AND section_id = ? ";
    $array_params[] = $section_id;

    $sql_timetable .= " ORDER BY period_start ASC, end_time ASC";
    $stmt = $conn_rjllearning_specific->prepare($sql_timetable);
    $stmt->execute($array_params);
    $rows = $stmt->fetchAll();

    $timetable_info = array();
    // Initialize an array to store data day-wise
    if (count($rows) >= 1) {
        //print_r($rows);
        $class_info = getClass($conn_rjllearning_specific, $institution_id, $rows[0]['class_id']);
        $section_info = getSection($conn_rjllearning_specific, $institution_id, $rows[0]['section_id']);
        $timetable_entries = array(); // Initialize an array to store multiple timetable entries

        foreach ($rows as $entry) {
            $period_start = $entry['period_start'];
            $end_time = $entry['end_time'];
            $day = $entry['day']; // Get the day

            if ($entry['subject_id'] !=  null and $entry['faculty_id'] != null) {
                $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $entry['subject_id']);
                $faculty_info = getFacultyInfo($conn_rjllearning_specific, $institution_id, $entry['faculty_id']);
            } else {
                $subject_info =  null;
                $faculty_info =  null;
            }
            // Check if timetable entry for this period start and end time already exists
            if (isset($timetable_entries[$period_start])) {
                // If entry exists, append day-wise data
                $timetable_entries[$period_start]['days'][$day] = array(
                    "day" => $day, // Add the day
                    "subject_id" => $subject_info,
                    "faculty_id" => $faculty_info
                );
            } else {
                // Create a new timetable entry
                $timetable_entries[$period_start] = array(
                    "period_start" => $period_start,
                    "end_time" => $end_time,
                    "days" => array(
                        $day => array(
                            "day" => $day, // Add the day
                            "subject_id" => $subject_info,
                            "faculty_id" => $faculty_info
                        )
                    )
                );
            }
        }

        // Convert associative array to indexed array
        $timetable_entries = array_values($timetable_entries);

        $array_return =  array('class_id' => $class_info, 'section_id' => $section_info, 'timetable_info' => $timetable_entries);
    } else {
        errorreturn("Invalid Timetable.");
    }

    return $array_return;
}

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

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

    if (isset($postdata['class_id']) and !empty($postdata['class_id']) and trim($postdata['class_id'])) {
        $class_id = trim($postdata['class_id']);
    } else {
        errorreturn("Class is required");
    }

    if (isset($postdata['section_id']) and !empty($postdata['section_id']) and trim($postdata['section_id'])) {
        $section_id = trim($postdata['section_id']);
    } else {
        errorreturn("Section is required");
    }
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

    $success['data'] = getSpecificTimetable($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $section_id);
    successreturn($success);
}
