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

// Check if required fields are present
$required_fields = ['institution_id', 'class_id', 'branch_id', 'api_signature', 'function_type', 'jwt_token'];
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;

// Validate user access
$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);
}

require_once $base_path_to_learning . 'functions/get_branch_functions.php';

// Extract and validate input data
$institution_id = trim($postdata['institution_id']);
$class_id = trim($postdata['class_id']);
$branch_id = trim($postdata['branch_id']);
$subject_id = trim($postdata['subject_id']);
// $status = trim($postdata['status']);
if (isset($postdata['search_string']) and !empty($postdata['search_string'])) {
        $search_string = trim($postdata['search_string']);
    } else {
        $search_string = null;
    }


// Check branch class subject
$check_branch_class = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, $class_id, null, $institution_id);
if ($check_branch_class == false) {
    errorreturn("Access denied.");
}

$function_type = $postdata['function_type'];

$response = [];

if ($function_type == "fetch_students_api_lesson_categories") {
    // Fetch lesson categories
    $sql_fetch_lesson_categories = "SELECT id, branch_id, class_id, subject_id, topic_name, description FROM lesson_categories WHERE institution_id = ?";
    
    $array_params_fetch_lesson = [$institution_id];

    if ($branch_id == 'all') {
        $sql_fetch_lesson_categories .= "";
    } else if ($branch_id !=  null  && $branch_id != 'all') {
        $sql_fetch_lesson_categories .= " AND branch_id = ? ";
        $array_params_fetch_lesson[] = $branch_id;
    }
    if ($section_id != null) {
            $sql_session .= " AND section_id LIKE ? ";
            $array_params[] = '%' . $section_id . '%'; 
    }
    if ($class_id == 'all') {
        $sql_fetch_lesson_categories .= "";
    } else if ($class_id !=  null  && $class_id != 'all') {
        $sql_fetch_lesson_categories .= " AND class_id = ? ";
        $array_params_fetch_lesson[] = $class_id;
    }
    
    if ($subject_id == 'all') {
        $sql_fetch_lesson_categories .= "";
    } else if ($subject_id !=  null  && $subject_id != 'all') {
        $sql_fetch_lesson_categories .= " AND subject_id = ? ";
        $array_params_fetch_lesson[] = $subject_id;
    }
    
    if ($search_string != null) {
        $sql_fetch_lesson_categories .= " AND (topic_name LIKE ? OR description LIKE ?)";
        $array_params_fetch_lesson[] = '%' . $search_string . '%';
        $array_params_fetch_lesson[] = '%' . $search_string . '%';
    }

    $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
    $data = [];
    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']);
        
        // Append data to response array
        $data[] = [
            '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'],
        ];
    }

    $response = [
        'data' => $data
    ];

    successReturn($response);
}
?>
