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

//dynemic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';

require_once $base_path_to_learning . "vendor/autoload.php";
require_once $base_path_to_learning_resources . 'lib/bucket_functions/bucket_functions.php';
require_once $base_path_to_learning_resources . 'includes/aws_bucket_config.php';
require_once $base_path_to_learning . "faculty_api/faculty_function/common_faculty_function.php";

require_once $base_path_to_learning . 'functions/common_functions.php';
require_once $base_path_to_learning . 'functions/get_branch_functions.php';
require_once $base_path_to_learning . 'user_management/user_versioning.php';

// Decode JSON post data
$postdata = json_decode(file_get_contents("php://input"), true);
checkIfNoPhpContentsReceive();

// Check if required fields are present
$required_fields = ['api_signature', 'function_type', 'jwt_token', 'lesson_category_id'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        errorreturn("All * fields are required.");
    }
}

// Validate API signature
validateApiSignature($postdata['api_signature']);

// Authenticate JWT token
$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);

// Extract data from JWT token
$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;
// Validate user access
$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["teacher"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}

$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

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


$lesson_category_id = trim($postdata['lesson_category_id']);

$response = [];

function fetch_specific_lesson_categories($lesson_category_id, $conn_rjllearning_specific, $institution_id, $branch_id)
{
    // Base SQL query
    $sql_fetch_lesson_categories = "SELECT * FROM lesson_categories WHERE id = ? AND institution_id = ? AND branch_id = ?";
    $array_params = [$lesson_category_id, $institution_id, $branch_id];

    // $timetable_query = "SELECT class_id, subject_id 
    //                     FROM timetable 
    //                     WHERE institution_id = ? AND branch_id = ? AND faculty_id = ? 
    //                     AND type IN ('timetable', 'faculty_role')";
    // $timetable_stmt = $conn_rjllearning_specific->prepare($timetable_query);
    // $timetable_stmt->execute([$institution_id, $branch_id, $faculty_id]);
    // $timetable_data = $timetable_stmt->fetchAll(PDO::FETCH_ASSOC);

    // // Organize timetable data into unique class, section, and subject sets
    // $valid_class_ids = [];
    // $valid_section_ids = [];
    // $valid_subject_ids = [];
    // foreach ($timetable_data as $row) {
    //     $valid_class_ids[] = $row['class_id'];
    //     // $valid_section_ids[] = $row['section_id'];
    //     $valid_subject_ids[] = $row['subject_id'];
    // }

    // // Remove duplicates
    // $valid_class_ids = array_unique($valid_class_ids);
    // $valid_section_ids = array_unique($valid_section_ids);
    // $valid_subject_ids = array_unique($valid_subject_ids);

    // // Class filter (if specified and valid)
    // if ($class_id !== 'all' && $class_id !== null && in_array($class_id, $valid_class_ids)) {
    //     $sql_fetch_lesson_categories .= " AND class_id = ?";
    //     $array_params[] = $class_id;
    // } elseif ($class_id === 'all') {
    //     if (!empty($valid_class_ids)) {
    //         $sql_fetch_lesson_categories .= " AND class_id IN (" . implode(',', array_fill(0, count($valid_class_ids), '?')) . ")";
    //         $array_params = array_merge($array_params, $valid_class_ids);
    //     } else {
    //         $sql_fetch_lesson_categories .= " AND 1 = 0"; // No valid classes, return no records
    //     }
    // }

    // // Subject filter (if specified and valid)
    // if ($subject_id !== 'all' && $subject_id !== null && in_array($subject_id, $valid_subject_ids)) {
    //     $sql_fetch_lesson_categories .= " AND subject_id = ?";
    //     $array_params[] = $subject_id;
    // } elseif ($subject_id === 'all') {
    //     if (!empty($valid_subject_ids)) {
    //         $sql_fetch_lesson_categories .= " AND subject_id IN (" . implode(',', array_fill(0, count($valid_subject_ids), '?')) . ")";
    //         $array_params = array_merge($array_params, $valid_subject_ids);
    //     } else {
    //         $sql_fetch_lesson_categories .= " AND 1 = 0"; // No valid subjects, return no records
    //     }
    // }

    // Section filter (if specified and valid)
    // if ($section_id !== 'all' && $section_id !== null && in_array($section_id, $valid_section_ids)) {
    //     $sql_fetch_lesson_categories .= " AND section_id = ?";
    //     $array_params[] = $section_id;
    // } elseif ($section_id === 'all') {
    //     if (!empty($valid_section_ids)) {
    //         $sql_fetch_lesson_categories .= " AND section_id IN (" . implode(',', array_fill(0, count($valid_section_ids), '?')) . ")";
    //         $array_params = array_merge($array_params, $valid_section_ids);
    //     } else {
    //         $sql_fetch_lesson_categories .= " AND 1 = 0"; // No valid sections, return no records
    //     }
    // }

    // Prepare and execute the query
    $sql_fetch_lesson_categories_stmt = $conn_rjllearning_specific->prepare($sql_fetch_lesson_categories);
    $sql_fetch_lesson_categories_stmt->execute($array_params);
    $lesson_categories = $sql_fetch_lesson_categories_stmt->fetchAll(PDO::FETCH_ASSOC);

    if (!empty($lesson_categories)) {
        
        foreach ($lesson_categories as $category) {
            $class_info = getClass($conn_rjllearning_specific, $institution_id, $category['class_id']);
            $branch_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $category['branch_id']);
            $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $category['subject_id']);


            $response = [
                'lesson_category_id' => $category['id'],
                'class_info' => $class_info,
                'branch_info' => $branch_info,
                'subject_info' => $subject_info,
                'topic_name' => $category['topic_name'],
                'description' => $category['description'],
            ];
        }
        return $response;
    } else {
        errorreturn("No lesson category found.");
    }
}

if ($postdata['function_type'] == "fetch_specific_lesson_categories") {
    $lesson_category_id = trim($postdata['lesson_category_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($postdata['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.");
    }
    
    $specific_lesson_category_data = fetch_specific_lesson_categories($lesson_category_id, $conn_rjllearning_specific, $institution_id, $branch_id);
    successreturn($specific_lesson_category_data);
}
