<?php
ini_set('display_errors', 1);

require_once '../../../../resources/base_path_include.php';

require_once $base_path_to_learning_resources  . "includes/connect.php";
require_once $base_path_to_learning_resources . 'lib/function.php';
require_once $base_path_to_learning_resources . 'lib/validate_api_signature.php';

// Validation files
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 access
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 = ['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 = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],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';

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


function get_lesson_category($conn_rjllearning_specific, $institution_id, $branch_id, $class_id, $subject_id, $search_string, $limit, $offset)
{
    $sql_count = "SELECT count(*) as total_rows FROM lesson_categories WHERE institution_id = ?";
    $array_params = [$institution_id];
    
    if ($branch_id !== null && $branch_id !== 'all') {
        $sql_count .= " AND branch_id = ?";
        $array_params[] = $branch_id;
    }

    if ($class_id !== null && $class_id !== 'all') {
        $sql_count .= " AND class_id = ?";
        $array_params[] = $class_id;
    }

    if ($subject_id !== null && $subject_id !== 'all') {
        $sql_count .= " AND subject_id = ?";
        $array_params[] = $subject_id;
    }

    if ($search_string !== null) {
        $sql_count .= " AND (lesson_name LIKE ? OR message LIKE ? OR description LIKE ?)";
        $search_param = '%' . $search_string . '%';
        $array_params = array_merge($array_params, [$search_param, $search_param, $search_param]);
    }

    $stmt = $conn_rjllearning_specific->prepare($sql_count);
    $stmt->execute($array_params);
    $result_total = $stmt->fetchAll();
    $totalrows = $result_total[0]['total_rows'];

    if ($limit == 'all') {

        $sql_fetch = "SELECT id, branch_id, class_id, subject_id, topic_name, description FROM lesson_categories WHERE institution_id = ?";
        $array_params_fetch = [$institution_id];
        
        if ($branch_id !== null && $branch_id !== 'all') {
            $sql_fetch .= " AND branch_id = ?";
            $array_params_fetch[] = $branch_id;
        }

        if ($class_id !== null && $class_id !== 'all') {
            $sql_fetch .= " AND class_id = ?";
            $array_params_fetch[] = $class_id;
        }

        if ($subject_id !== null && $subject_id !== 'all') {
            $sql_fetch .= " AND subject_id = ?";
            $array_params_fetch[] = $subject_id;
        }

        if ($search_string !== null) {
            $sql_fetch .= " AND (topic_name LIKE ? OR description LIKE ?)";
            $search_param = '%' . $search_string . '%';
            $array_params_fetch = array_merge($array_params_fetch, [$search_param, $search_param]);
        }
    } else {

        $sql_fetch = "SELECT id, branch_id, class_id, subject_id, topic_name, description FROM lesson_categories WHERE institution_id = ?";
        $array_params_fetch = [$institution_id];
        
        if ($branch_id !== null && $branch_id !== 'all') {
            $sql_fetch .= " AND branch_id = ?";
            $array_params_fetch[] = $branch_id;
        }

        if ($class_id !== null && $class_id !== 'all') {
            $sql_fetch .= " AND class_id = ?";
            $array_params_fetch[] = $class_id;
        }

        if ($subject_id !== null && $subject_id !== 'all') {
            $sql_fetch .= " AND subject_id = ?";
            $array_params_fetch[] = $subject_id;
        }

        if ($search_string !== null) {
            $sql_fetch .= " AND (topic_name LIKE ? OR description LIKE ?)";
            $search_param = '%' . $search_string . '%';
            $array_params_fetch = array_merge($array_params_fetch, [$search_param, $search_param]);
        }

        $sql_fetch .= "LIMIT " . $offset . " ," . $limit . "";
    }
    $stmt_fetch = $conn_rjllearning_specific->prepare($sql_fetch);
    $stmt_fetch->execute($array_params_fetch);
    $lesson_categories = $stmt_fetch->fetchAll(PDO::FETCH_ASSOC);

    $data = [];
    foreach ($lesson_categories as $category) {
        $branch_id = $category['branch_id'];
        $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_info = getBranchInfo($conn_rjllearning_specific, $institution_id, $category['branch_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']);
            }
        }

        if ($category['subject_id'] == 'all') {
            $subject_info = [
                "subject_id" => 'all',
                "subject_name" => 'All Subjects'
            ];
        } else {
            $subject_info = getSubject($conn_rjllearning_specific, $institution_id, $category['subject_id']);
            if (!$subject_info) {
                $subject_info = [
                    "subject_id" => $category['subject_id'],
                    "subject_name" => 'Unknown Subject'
                ];
            }
        }

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

    if (isset($postdata['class_id']) and !empty($postdata['class_id'])) {
        $class_id = trim($postdata['class_id']);
    } else {
        $class_id = null;
    }
    if (isset($postdata['subject_id']) and !empty($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;
    }

    $limit = $postdata['limit'];

    $page = (isset($postdata['page']) and isNumeric($postdata['page'])) ? (int)$postdata['page'] : 1;
    $check_academic_confirmation = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
    if ($check_academic_confirmation != true) {
        errorreturn("Access denied. Academic session not active.");
    }

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