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

// validation 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';
// dynamic db
require_once $base_path_to_learning_resources . 'includes/specific_db_config.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,["principal"], null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}

$conn_rjllearning_specific = dynamicDbConnection($specific_db_name);

require_once $base_path_to_learning . 'functions/get_branch_functions.php';
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);

// Extract and validate input data
$lesson_category_id= trim($postdata['lesson_category_id']);

$function_type = $postdata['function_type'];

if ($function_type == "fetch_specific_lesson_categories") {
    // Fetch lesson categories
    $sql_fetch_lesson_categories = "SELECT * FROM lesson_categories WHERE  id = ? AND institution_id = ? AND branch_id = ?";
    $array_params_fetch_lesson = [ $lesson_category_id,$institution_id,$branch_id];

    $sql_fetch_lesson_categories_stmt = $conn_rjllearning_specific->prepare($sql_fetch_lesson_categories);
    $sql_fetch_lesson_categories_stmt->execute($array_params_fetch_lesson);
    $lesson_categories = $sql_fetch_lesson_categories_stmt->fetchAll(PDO::FETCH_ASSOC);

    // Check if any lesson categories found
    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'],  
            ];
        }
        successReturn($response);
    } else {
        errorreturn("No lesson category found.");
    }
}
?>
