<?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';
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';
require_once $base_path_to_learning_resources . 'includes/specific_db_config.php';
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';
require_once $base_path_to_learning . "admin_api/modules/account_management/expense_group/functions.php";


$postdata = json_decode(file_get_contents("php://input"), true);

checkIfNoPhpContentsReceive();

if (
    !isset($postdata['institution_id']) or !checkIfIssetAndNotEmpty($postdata['institution_id']) or
    !isset($postdata['api_signature']) or !checkIfIssetAndNotEmpty($postdata['api_signature']) or
    !isset($postdata['function_type']) or !checkIfIssetAndNotEmpty($postdata['function_type'])  or
    !isset($postdata['jwt_token']) or  !isset($postdata['jwt_token'])
) {
    errorreturn("All * fields are required.");
}

validateApiSignature($postdata['api_signature']);

$jwttoken = $postdata['jwt_token'];
$jwt_validate = authenticate_jwt($jwttoken);
$userid = $jwt_validate->data->id;
$workspace_id = $jwt_validate->data->workspace_id;
$username = $jwt_validate->data->username;
$role = $jwt_validate->data->role;

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

function get_ledger_groups($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $limit, $offset)
{
    // Fetch total rows for pagination or response info
    $sql = "SELECT COUNT(*) as total_rows FROM act_ledger_group WHERE institution_id = ?";
    $array_params = [$institution_id];

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

    // Main query to fetch ledger groups with parent levels
    $sql_session = "SELECT id AS ledger_group_id, group_name, parent_lvl1, parent_lvl2, parent_lvl3, parent_lvl4, parent_lvl5 FROM act_ledger_group WHERE institution_id = ?";

    $array_params = [$institution_id];

    // Add search string filtering for group_name
    if (!empty($search_string)) {
        $sql_session .= " AND group_name LIKE ?";
        $like_search = '%' . $search_string . '%';
        array_push($array_params, $like_search);
    }

    // Add limit and offset for pagination
    if ($limit !== 'all') {
        $sql_session .= " LIMIT " . (int)$limit . " OFFSET " . (int)$offset;
    }

    $stmt = $conn_rjllearning_specific->prepare($sql_session);
    $stmt->execute($array_params);
    $result = $stmt->fetchAll();

    // Handle no data found case
    if (empty($result)) {
        errorreturn("No Data Found.");
    }

    // Prepare response structure
    $response = [
        "total_rows" => $total_rows,
        "details" => []
    ];

    // Iterate through result set and build the response
    foreach ($result as $rows) {
        $group_hierarchy = [];

        // Loop to fetch the parent level hierarchy
        for ($i = 1; $i <= 5; $i++) {
            $parent_lvl = 'parent_lvl' . $i;
            if (!empty($rows[$parent_lvl])) {
                $group_hierarchy[] = [
                    $parent_lvl => $rows[$parent_lvl],
                    $parent_lvl . '_name' => fetchgroup_name($conn_rjllearning_specific, $rows[$parent_lvl])
                ];
            }
        }

        // Add the fetched data to the response
        $response['details'][] = [
            "ledger_group_id" => $rows['ledger_group_id'],
            "group_name" => $rows['group_name'],
            "parent_levels" => $group_hierarchy,
        ];
    }
    return $response;
}

if ($postdata['function_type'] == "fetch_ledgerGroups") {
    $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.");
    }

    $branch_id = isset($postdata['branch_id']) && !empty($postdata['branch_id']) ? trim($postdata['branch_id']) : null;
    $search_string = isset($postdata['search_string']) && !empty($postdata['search_string']) ? trim($postdata['search_string']) : null;

    $limit = $postdata['limit'];

    $page = (isset($postdata['page']) && is_numeric($postdata['page'])) ? (int)$postdata['page'] : 1;

    if ($limit != 'all') {
        $offset = ($page - 1) * $limit;
        $success['data'] = get_ledger_groups($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $limit, $offset);
    } else {
        $success['data'] = get_ledger_groups($conn_rjllearning_specific, $institution_id, $search_string, $branch_id, $limit, null);
    }

    successreturn([
        "details" => $success,
        "maxreach" => 1
    ]);
} else {
    errorreturn("Invalid Function Type");
}
