<?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';
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";
$postdata = json_decode(file_get_contents("php://input"), true);
// print_r($postdata);die();
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,['teacher'],null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

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);

function getSpecificTimetable($conn_rjllearning_specific, $institution_id, $branch_id, $faculty_id)
{

    $sql = "SELECT count(*) as total_rows FROM  timetable where institution_id =? and branch_id  = ? and faculty_id = ? AND (type = 'faculty_role' OR type = 'timetable')  ";
    $array_params = [$institution_id, $branch_id, $faculty_id];
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];

    $sql_timetable = "SELECT * FROM  timetable where institution_id =? and branch_id  = ? and faculty_id = ? AND (type = 'faculty_role' OR type = 'timetable')";

    $array_params = [$institution_id, $branch_id, $faculty_id];
    $stmt = $conn_rjllearning_specific->prepare($sql_timetable);
    $stmt->execute($array_params);
    $rows = $stmt->fetchAll();

    $sql_faculty = "SELECT * FROM  timetable where institution_id =? and branch_id = ? and faculty_id = ? and type = ? ";
    $array_params = [$institution_id, $branch_id, $faculty_id, 'class_incharge'];
    $stmt_faculty = $conn_rjllearning_specific->prepare($sql_faculty);
    $stmt_faculty->execute($array_params);
    $result_faculty = $stmt_faculty->fetchAll();

    $array_return = [];
    if (count($result_faculty) >= 1) {
        foreach ($result_faculty as $incharge_rows) {
            $faculty_info[] = array(
                "class_incharge_id" => $incharge_rows['id'],
                "class_id" => getClass($conn_rjllearning_specific, $institution_id, $incharge_rows['class_id']),
                "section_id" => getSection($conn_rjllearning_specific, $institution_id, $incharge_rows['section_id'])
            );
        }
    } else {
        $faculty_info = null;
    }
    
    $timetable_info = array();
    $grouped_info = array();  // To hold the grouped data
    
    if (count($rows) >= 1) {
        foreach ($rows as $temp) {
            // If 'day' contains a comma-separated string, convert it into an array
            if ($temp['day'] != null && $temp['day'] != '') {
                $day = explode(',', $temp['day']);
                // Trim any whitespace or extra characters from each day
                $day = array_map('trim', $day);
            } else {
                // If it's null or empty, set day as an empty array
                $day = [];
            }
    
            // Get class, section, and subject info
            $class_info = getClass($conn_rjllearning_specific, $institution_id, $temp['class_id']);
            $section_info = getSection($conn_rjllearning_specific, $institution_id, $temp['section_id']);
            $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $temp['subject_id']);
    
            // Create a unique key for class_id, section_id, subject_id, period_start, and end_time to group similar entries
            $key = $temp['class_id'] . '-' . $temp['section_id'] . '-' . $temp['subject_id'] . '-' . $temp['period_start'] . '-' . $temp['end_time'];
    
            // Check if the key already exists in the grouped_info array
            if (isset($grouped_info[$key])) {
                // Merge the 'day' values (unique values only)
                $grouped_info[$key]['day'] = array_merge($grouped_info[$key]['day'], $day);
                // Remove duplicates from 'day' array
                $grouped_info[$key]['day'] = array_unique($grouped_info[$key]['day']);
            } else {
                // Add the new entry to grouped_info
                $grouped_info[$key] = array(
                    'class_id' => $class_info,
                    'section_id' => $section_info,
                    'subject_id' => $subject_info,
                    'period_start' => $temp['period_start'],
                    'end_time' => $temp['end_time'],
                    'day' => $day
                );
            }
        }
    
        // Prepare the final timetable_info array from grouped_info
        $timetable_info = array_values($grouped_info);
    
        // Prepare the return array
        $array_return = array(
            'faculty_role_id' => $rows[0]['id'],
            'faculty_id' => $rows[0]['faculty_id'],
            'faculty_timetable' => $timetable_info,
            "class_incharge" => $faculty_info
        );
    }

    if (count($rows) < 50) {
        return array('total_rows' => $totalrows, 'faculty_role_info' => $array_return, 'maxreach' => 1);
    } else {
        return array('total_rows' => $totalrows, 'faculty_role_info' => $array_return, 'maxreach' => 0);
    }
}

$function_type = $postdata['function_type'];

if ($function_type == "fetch_faculty_timetable") {

    $faculty_id = trim($postdata['faculty_id']);
    
    $teacher_data = getClassSectionSubjectsAndInChargeRoles($conn_rjllearning, $conn_rjllearning_specific, $institution_id, $userid);
    $class_section_subjects  = $teacher_data['class_section_subjects'];
    $class_incharge_roles = $teacher_data['class_incharge_roles'];
    $staff_access_modules = $teacher_data['staff_access_modules'];

    $check_faculty_status = checkFacultyModuleGranted($function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, null, null, null, $conn_rjllearning);
    if ($check_faculty_status == false) {
        errorreturn("Access denied: You do not have the required permissions.");
    }

    $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, $faculty_id);
    successreturn($success);
}
