<?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';

//aws image store
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning . "vendor/autoload.php";

require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

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

if (

    !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  !isset($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}
validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$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;
$class_id = $jwt_validate->data->class;
$section_id = $jwt_validate->data->section;

$specific_db_name = validateStudentAcess($conn_rjllearning, $role, $workspace_id, ["student"], null, null, $userid);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}
validateStudentClassSection($conn_rjllearning_specific, $userid, $institution_id, $branch_id, $class_id, $section_id);

  






function fetchStudentTimetableWithClassSection($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $userid )
{
    

   $sql_timetable = "
        SELECT 
            t.*,                      
            s.class_id, 
            s.section_id
        FROM 
            students s
        JOIN 
            timetable t ON s.class_id = t.class_id 
                       AND s.section_id = t.section_id
        WHERE 
            s.user_id = ? 
            AND s.institution_id = ? 
            AND s.branch_id = ? 
            AND t.institution_id = ? 
            AND t.branch_id = ? 
            AND t.type = 'timetable'
        ORDER BY 
            t.period_start ASC, t.end_time ASC
    ";
    $stmt = $conn_rjllearning_specific->prepare($sql_timetable);
    $stmt->execute([$userid, $institution_id, $branch_id, $institution_id, $branch_id]);
      $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);
        // array_push($array_return, $timetable_info);
    }else{
          errorreturn("Enter Invalid Timetable.");
    }
    
    return $array_return;
}



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

    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }
    if (isset($postdata['search_string']) and !empty($postdata['search_string'])  and ($postdata['search_string'])) {
        $search_string = trim($postdata['search_string']);
    } else {
        $search_string = null;
    }
    // $class_id =trim($postdata['class_Id']);
    
    
        $success['data'] = fetchStudentTimetableWithClassSection($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $userid );
        successreturn($success);
    
}