<?php

// Display errors for debugging
ini_set('display_errors', 1);

// Include necessary files
require_once '../../../../../resources/base_path_include.php';
require_once $base_path_to_learning_resources . "includes/connect.php"; // Database connection
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_resources . 'lib/common_modules/receipts_expenses/function_receipt_expense_stats.php';

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

checkIfNoPhpContentsReceive();

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

// Validate API signature
validateApiSignature($postdata['api_signature']);

// Decode and validate JWT token
$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;
$name = $jwt_validate->data->name;

$institution_id = trim($postdata['institution_id']);
$branch_id = trim($postdata['branch_id']);

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'],null);
if (!$specific_db_name) {
    errorreturn('Access denied.');
} else {
    $conn_rjllearning_specific = dynamicDbConnection($specific_db_name);
}

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

// Validate institution_id and branch_id
$academicSessionId = CheckAcademicSession($conn_rjllearning_specific, $institution_id);
if (!$academicSessionId) {
    errorreturn("Invalid institution_id");
}

$isBranchClassSubjectValid = checkBranchClassSubject($conn_rjllearning_specific, $branch_id, null, null, $institution_id);
if (!$isBranchClassSubjectValid) {
    errorreturn("Invalid branch_id.");
} 

$response = [];

$function_type = $postdata['function_type'];

if ($function_type === "transaction_stats") {
   
    $min_date = isset($postdata['min_date']) ? $postdata['min_date'] : null;
    $max_date = isset($postdata['max_date']) ? $postdata['max_date'] : null;

    // Validate dates
    if (!$min_date || !$max_date || !strtotime($min_date) || !strtotime($max_date) || $min_date > $max_date) {
        errorreturn("Both min_date and max_date are required and must be valid.");
    }

    successreturn(['data' => getExpenseReceiptStats(
        $conn_rjllearning_specific,
        $institution_id,
        $branch_id,
        $min_date,
        $max_date   
    )]);

} else {
    errorreturn("Invalid function_type");
}
