<?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 . "principal_api/principal_function/principal_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 = ['class_id', 'subject_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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_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);
}

$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
$class_id = trim($postdata['class_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'];

$sql_codes = $conn_rjllearning_specific->prepare("SELECT id FROM faculty_info WHERE userid = ? AND institution_id = ? AND branch_id = ?");
$sql_codes->execute(array($userid, $institution_id, $branch_id));

$result_faculty = $sql_codes->fetch(PDO::FETCH_ASSOC);

if ($result_faculty === false) {
    errorreturn("Faculty Not Found.");
}

$faculty_id = $result_faculty['id'];

// function get_lesson_category($conn_rjllearning_specific,$conn_rjllearning,$institution_id,$search_string,$branch_id,$subject_id,$class_id,$function_type,$userid,$limit,$offset) {
//     // Fetch total rows for pagination
//     $sql = "SELECT COUNT(*) as total_rows FROM lesson_categories WHERE institution_id = ? AND branch_id = ? OR branch_id = 'all'";
//     $array_params = [$institution_id, $branch_id];

//     $stmt = $conn_rjllearning_specific->prepare($sql);
//     $stmt->execute($array_params);
//     $total_rows_result = $stmt->fetchAll();
//     $totalrows = $total_rows_result[0]['total_rows'];

//     // Fetch teacher data
//     $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'];

//     // Ensure module access
//     $section_id = $class_section_subjects[0]['section']['section_id'] ?? null;
    
//     $check_faculty_status = checkFacultyModuleGranted($function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, 'all', $subject_id, $conn_rjllearning);
//     if($check_faculty_status == false){
//             errorreturn("Access denied: You do not have the required permissions.");
//     }   
//     // Append faculty filters
//     $sql_append_data = facultyFilterQueryAppend(
//         $sql,
//         $array_params,
//         $function_type,
//         $class_section_subjects,
//         $class_incharge_roles,
//         $staff_access_modules,
//         $class_id,
//         null,
//         $subject_id,
//         $conn_rjllearning,
//         1,
//         1,
//         1,
//         1,
//         true
//     );
    
//     if ($limit == 'all') {
//         // Base query for fetching lesson categories
//         $sql_session = "SELECT * FROM lesson_categories WHERE institution_id = ? AND branch_id = ? OR branch_id = 'all'";
//         $array_params = [$institution_id, $branch_id];
        
//         $sql_append_data = facultyFilterQueryAppend(
//         $sql_session,
//         $array_params,
//         $function_type,
//         $class_section_subjects,
//         $class_incharge_roles,
//         $staff_access_modules,
//         $class_id,
//         null,
//         $subject_id,
//         $conn_rjllearning,
//         1,
//         1,
//         1,
//         1,
//         true
//         );
        
//         $sql_lessons = $sql_append_data['sql']; // Get the modified SQL
//         $array_params = $sql_append_data['array_params'];

//         // Add search filters if applicable
//         if (!empty($search_string)) {
//             $sql_session .= " AND (topic_name LIKE ? OR description LIKE ?)";
//             $array_params[] = '%' . $search_string . '%';
//             $array_params[] = '%' . $search_string . '%';
//         }
//     } else {

//         $sql_session = "SELECT * FROM lesson_categories WHERE institution_id = ? AND branch_id = ? OR branch_id = 'all'";
//         $array_params = [$institution_id, $branch_id];
        
//         $sql_append_data = facultyFilterQueryAppend(
//         $sql_session,
//         $array_params,
//         $function_type,
//         $class_section_subjects,
//         $class_incharge_roles,
//         $staff_access_modules,
//         $class_id,
//         null,
//         $subject_id,
//         $conn_rjllearning,
//         1,
//         1,
//         1,
//         1,
//         true
//         );
        
//         $sql_lessons = $sql_append_data['sql']; // Get the modified SQL
//         $array_params = $sql_append_data['array_params'];

//         // Add search filters if applicable
//         if (!empty($search_string)) {
//             $sql_session .= " AND (topic_name LIKE ? OR description LIKE ?)";
//             $array_params[] = '%' . $search_string . '%';
//             $array_params[] = '%' . $search_string . '%';
//         }

//         $sql = $sql_append_data['sql'];
//         $array_params = $sql_append_data['array_params'];

//         // Add limit and offset for pagination
//         $sql .= " LIMIT " . $offset . ", " . $limit;
//     }


//     // Execute the query and fetch lesson categories
//     $stmt = $conn_rjllearning_specific->prepare($sql);
//     $stmt->execute($array_params);
//     $lesson_categories = $stmt->fetchAll();

//     // Prepare response data
//     $data = [];
//     foreach ($lesson_categories as $category) {
//         $class_info = getClass($conn_rjllearning_specific, $institution_id, $category['class_id']);
        
//         if ($branch_id === 'all') {
//             $branch_info = array('branch_id' => $branch_id, 'name' => ucwords($branch_id));
//         } else {
//             $branch_query = "SELECT * FROM branch WHERE institution_id = ? AND id IN ($branch_id) AND status = ?";
//             $branch_query_params = [$institution_id, '1'];
//             $branch_stmt = $conn_rjllearning_specific->prepare($branch_query);
//             $branch_stmt->execute($branch_query_params);
//             $branch_rows = $branch_stmt->fetchAll();

//             foreach ($branch_rows as $branch) {
//                 $branch_info = array('branch_id' => $branch['id'], 'name' => $branch['name']);
//             }
//         }

//         $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $category['subject_id']);

//         $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'],
//         ];
//     }
//     // return [
//     //     'total_rows' => $total_rows,
//     //     'data' => $data
//     // ];
//     if (count($lesson_categories) < 50) {
//         return array('total_rows' => $totalrows, 'data' => $data, 'maxreach' => 1);
//     } else {
//         return array('total_rows' => $totalrows, 'data' => $data, 'maxreach' => 0);
//     }
// }

function get_lesson_category($conn_rjllearning_specific, $conn_rjllearning, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $function_type, $userid, $limit, $offset) 
{
    // First get teacher data to check section access
    $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 permissions
    $check_faculty_status = checkFacultyModuleGranted($function_type, $class_section_subjects, $class_incharge_roles, $staff_access_modules, $class_id, 'all', $subject_id, $conn_rjllearning);
    if($check_faculty_status == false) {
        errorreturn("Access denied: You do not have the required permissions.");
    }   
    
    // Base query for counting
    $sql = "SELECT COUNT(*) as total_rows FROM lesson_categories WHERE institution_id = ? AND (branch_id = ? OR branch_id = 'all')";
    $array_params = [$institution_id, $branch_id];
    
    // Add class filter
    if ($class_id && $class_id != 'all') {
        $sql .= " AND (class_id = ? OR class_id = 'all')";
        $array_params[] = $class_id;
    }
    
    // Add subject filter if provided
    if ($subject_id && $subject_id != 'all') {
        $sql .= " AND (subject_id = ? OR subject_id = 'all')";
        $array_params[] = $subject_id;
    }

    // Get total rows count
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute($array_params);
    $total_rows_result = $stmt->fetchAll();
    $totalrows = $total_rows_result[0]['total_rows'];

    // Base query for fetching data
    $sql_session = "SELECT * FROM lesson_categories WHERE institution_id = ? AND (branch_id = ? OR branch_id = 'all')";
    $array_params = [$institution_id, $branch_id];
    
    // Add class filter
    if ($class_id && $class_id != 'all') {
        $sql_session .= " AND (class_id = ? OR class_id = 'all')";
        $array_params[] = $class_id;
    }
    
    // Add subject filter if provided
    if ($subject_id && $subject_id != 'all') {
        $sql_session .= " AND (subject_id = ? OR subject_id = 'all')";
        $array_params[] = $subject_id;
    }

    // Add search filter if provided
    if (!empty($search_string)) {
        $sql_session .= " AND (topic_name LIKE ? OR description LIKE ?)";
        $array_params[] = '%' . $search_string . '%';
        $array_params[] = '%' . $search_string . '%';
    }

    // Apply limit if not 'all'
    if ($limit != 'all') {
        $sql_session .= " LIMIT " . $offset . ", " . $limit;
    }

    // Execute the query
    $stmt = $conn_rjllearning_specific->prepare($sql_session);
    $stmt->execute($array_params);
    $lesson_categories = $stmt->fetchAll();

    // Prepare response data
    $data = [];
    foreach ($lesson_categories as $category) {
        $class_info = getClass($conn_rjllearning_specific, $institution_id, $category['class_id']);
        
        if ($branch_id === 'all') {
            $branch_info = array('branch_id' => $branch_id, 'name' => ucwords($branch_id));
        } else {
            $branch_query = "SELECT * FROM branch WHERE institution_id = ? AND id IN ($branch_id) AND status = ?";
            $branch_query_params = [$institution_id, '1'];
            $branch_stmt = $conn_rjllearning_specific->prepare($branch_query);
            $branch_stmt->execute($branch_query_params);
            $branch_rows = $branch_stmt->fetchAll();

            foreach ($branch_rows as $branch) {
                $branch_info = array('branch_id' => $branch['id'], 'name' => $branch['name']);
            }
        }

        $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $category['subject_id']);

        $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'],
        ];
    }

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

if ($postdata['function_type'] == "fetch_lesson_categories") {
    // $institution_id = trim($postdata['institution_id']);
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

    if (isset($postdata['subject_id']) and !empty($postdata['subject_id']) and trim($postdata['subject_id'])) {
        $subject_id = trim($postdata['subject_id']);
    } else {
        $subject_id = null;
    }

    if (isset($postdata['search_string']) and !empty($postdata['search_string'])) {
        $search_string = trim($postdata['search_string']);
    } else {
        $search_string = null;
    }


    if (isset($postdata['class_id']) and !empty($postdata['class_id']) and trim($postdata['class_id'])) {
        $class_id = trim($postdata['class_id']);
    } else {
        $class_id = "all";
    }

    $limit = $postdata['limit'];

    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;

    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
        $response = get_lesson_category($conn_rjllearning_specific, $conn_rjllearning, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $function_type, $userid, $limit, $offset);
        successreturn($response);
    } else {
        $response = get_lesson_category($conn_rjllearning_specific, $conn_rjllearning, $institution_id, $search_string, $branch_id, $subject_id, $class_id, $function_type, $userid, $limit, null);
        successreturn($response);
    }
}
