<?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['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or

    // //  !isset($postdata['subject_id']) or !checkIfIssetAndNotEmpty($postdata['subject_id']) or
    //   !isset($postdata['branch_id']) or !checkIfIssetAndNotEmpty($postdata['branch_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);
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;
$specific_db_name = validateStudentAcess($conn_rjllearning, $role, $workspace_id, ["teacher"] , null, null, $userid);

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 getClassAndSectionForStudent($conn_rjllearning_specific, $user_id, $institution_id,$branch_id) {

//     $sql = "
//         SELECT 
//             class_id, 
//             section_id
//         FROM 
//             students 
//         WHERE 
//             user_id=?
//             AND institution_id = ?
//             and branch_id=?
//     ";

//     // Prepare the SQL statement
//     $stmt = $conn_rjllearning_specific->prepare($sql);

//     // Execute the statement with the provided parameters
//     $stmt->execute([ $user_id, $institution_id ,$branch_id]);

//     // Fetch the result
//     $result = $stmt->fetch(PDO::FETCH_ASSOC);

//     // Return class and section data if found, else return null
//     return $result ?: null;
// }


// function fetchTimeTableForClassSection($conn_rjllearning_specific,$institution_id,$branch_id, $class_id, $section_id) {
//     // SQL query to fetch timetable data for the specified class_id, section_id, and type
//     $sql = "
//         SELECT 
//             *
//         FROM 
//             timetable 
//         WHERE 
//         institution_id = ? 
//             and branch_id=?
//             class_id = ? and
//             section_id = ? and
//             type = 'faculty_role'
//         ORDER BY 
//             period_start,period_end
//     ";

//     // Prepare the SQL statement
//     $stmt = $conn_rjllearning_specific->prepare($sql);

//     // Execute the statement with the provided parameters
//     $stmt->execute([
//         $institution_id,$branch_id, $class_id, $section_id]);

//     // Fetch all matching records
//     $timetable_data = $stmt->fetchAll(PDO::FETCH_ASSOC);

//     // Return the timetable data if found, else return null
//     return $timetable_data ?: null;
// }



/**
 * Fetch the timetable for a student based on user_id, institution_id, and branch_id.
 *
 * @param PDO $conn_rjllearning_specific The PDO database connection object.
 * @param int $user_id The user ID of the student.
 * @param int $institution_id The institution ID.
 * @param int $branch_id The branch ID.
 * @return array|null Returns an array of timetable records with class and section info, or null if none are found.
 */
// function fetchStudentTimetableWithClassSection($conn_rjllearning_specific, $user_id, $institution_id, $branch_id) {
//     // SQL query to join students with timetable based on class_id and section_id
//     $sql = "
//         SELECT 
//             t.*,                       -- All columns from timetable table
//             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 = 'faculty_role'
//         ORDER BY 
//             t.period_start, t.period_end
//     ";

//     // Prepare the SQL statement
//     $stmt = $conn_rjllearning_specific->prepare($sql);

//     // Execute the statement with the provided parameters
//     $stmt->execute([$user_id, $institution_id, $branch_id, $institution_id, $branch_id]);

//     // Fetch all matching timetable records
//     $timetable_data = $stmt->fetchAll(PDO::FETCH_ASSOC);

//     // Return the timetable data if found, else return null
//     return $timetable_data ?: null;
// }

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


    $faculty_query = "SELECT id 
                          FROM faculty_info 
                          WHERE userid = ? 
                            AND institution_id = ? 
                            AND branch_id = ?";
    $faculty_stmt = $conn_rjllearning_specific->prepare($faculty_query);
    $faculty_stmt->execute([$userid, $institution_id, $branch_id]);
    $faculty_info = $faculty_stmt->fetch(PDO::FETCH_ASSOC);

    if (!$faculty_info) {
        return errorreturn("Faculty not found.");
    }

    // Extract faculty ID
    $faculty_id = $faculty_info['id'];

    // Step 2: Use the faculty ID to fetch timetable details
    $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();

    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();
    if (count($rows) >= 1) {

        // foreach($rows as $temp){

        //     if($temp['day'] != null){

        //         $day = unserialize($temp['day']);
        //     }else{
        //         $day =  null;
        //     }

        //     $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']);

        //     $timetable_info[]  = 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);
        // }

        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, and subject_id to group similar entries
                $key = $temp['class_id'] . '-' . $temp['section_id'] . '-' . $temp['subject_id'];

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

        $array_return =  array('faculty_role_id' => $rows[0]['id'], 'faculty_id' => $temp['faculty_id'], 'faculty_timetable' => $timetable_info, "class_incharge" => $faculty_info);
    } else {
        errorreturn("Add new faculty role.");
    }

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

if ($postdata['function_type'] == "fetch_teachers_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;
    }

    $success['data'] = fetchTeachersTimetableWithClassSection($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $userid);
    successreturn($success);
}
