<?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';
// 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';
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();
// print_r($postdata);
if (
    !isset($postdata['institution_id']) || !checkIfIssetAndNotEmpty($postdata['institution_id']) ||
    !isset($postdata['api_signature']) || !checkIfIssetAndNotEmpty($postdata['api_signature']) ||
    !isset($postdata['function_type']) || !checkIfIssetAndNotEmpty($postdata['function_type']) ||
    !isset($postdata['type']) || !checkIfIssetAndNotEmpty($postdata['type']) ||
    !isset($postdata['jwt_token']) || !checkIfIssetAndNotEmpty($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 fetch_ledger_data($conn_rjllearning_specific, $conn_rjllearning, $institution_id, $type, $limit, $offset)
{
    $params_groups = [$institution_id];

    // SQL to count total rows for ledger heads and ledger groups
    $sql_heads_count = "SELECT COUNT(*) FROM ledgerheads";
    $sql_groups_count = "SELECT COUNT(*) FROM act_ledger_group WHERE institution_id = ?";

    // SQL to fetch ledger heads and ledger groups with limit and offset
    $sql_heads = "SELECT id, ledgerhead_name AS name FROM ledgerheads";
    $sql_groups = "SELECT id, group_name, main_ledgerhead FROM act_ledger_group WHERE institution_id = ?";

    // Add limit and offset if required
    if ($limit !== 'all') {
        $sql_heads .= " LIMIT $offset, $limit";
        $sql_groups .= " LIMIT $offset, $limit";
    }

    // Initialize data arrays
    $data_heads = [];
    $data_groups = [];
    $total_heads = 0;
    $total_groups = 0;

    // Fetch ledger heads and their count if the type is 'all' or 'only_head'
    if ($type === 'all' || $type === 'only_head') {
        // Count total ledger heads
        $stmt_heads_count = $conn_rjllearning->prepare($sql_heads_count);
        $stmt_heads_count->execute();
        $total_heads = $stmt_heads_count->fetchColumn();

        // Fetch ledger heads data with limit and offset
        $stmt_heads = $conn_rjllearning->prepare($sql_heads);
        $stmt_heads->execute();
        $data_heads = $stmt_heads->fetchAll(PDO::FETCH_ASSOC);
    }

    // Fetch ledger groups and their count if the type is 'all' or 'only_groups'
    if ($type === 'all' || $type === 'only_groups') {
        // Count total ledger groups
        $stmt_groups_count = $conn_rjllearning_specific->prepare($sql_groups_count);
        $stmt_groups_count->execute($params_groups);
        $total_groups = $stmt_groups_count->fetchColumn();

        // Fetch ledger groups data with limit and offset
        $stmt_groups = $conn_rjllearning_specific->prepare($sql_groups);
        $stmt_groups->execute($params_groups);
        $data_groups = $stmt_groups->fetchAll(PDO::FETCH_ASSOC);
    }

    // Return the results based on the type requested
    if ($type === 'all') {
        return [
            'ledger_heads' => $data_heads,
            'total_rows' => $total_heads,
            'ledger_groups' => $data_groups,
            'total_rows' => $total_groups
        ];
    }

    return $type === 'only_head' 
        ? ['ledger_heads' => $data_heads, 'total_rows' => $total_heads]
        : ['ledger_groups' => $data_groups, 'total_rows' => $total_groups];
}


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

    $type = trim($postdata['type']);
    $limit = $postdata['limit'];

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

    if ($limit != 'all') {
          $offset = ($page - 1) * $limit;
        $success['data'] = fetch_ledger_data($conn_rjllearning_specific, $conn_rjllearning, $institution_id, $type, (int)$limit, $offset);
    } else {
        $success['data'] = fetch_ledger_data($conn_rjllearning_specific, $conn_rjllearning, $institution_id, $type, $limit, null);
    }

    successreturn($success);
}else{
    errorreturn("Invalid Function Type");
}
