<?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/get_branch_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 . "user_management/functions/functions.php";

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

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

$required_fields = ['api_signature', 'function_type', 'jwt_token', 'fuel_expense_id'];
foreach ($required_fields as $field) {
    if (!isset($postdata[$field]) || !checkIfIssetAndNotEmpty($postdata[$field])) {
        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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,['superadmin','admin'], $institution_id, $branch_id);
if (!$specific_db_name) {
    errorreturn('Access denied.');
}
$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';
require_once $base_path_to_learning . 'user_management/user_versioning.php';
$institution_id =$postdata['institution_id'];
$branch_id=$postdata['branch_id'];
$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);

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


$function_type = trim($postdata['function_type']);
if ($function_type == "delete_bus_fuel_expense") {

    $fuel_expense_id = intval($postdata['fuel_expense_id']);



    try {
        // Check if record exists for this branch & institution
        $check_sql = "SELECT id FROM fuel_expense WHERE id = ? AND institution_id = ? AND branch_id = ?";
        $check_stmt = $conn_rjllearning_specific->prepare($check_sql);
        $check_stmt->execute([$fuel_expense_id, $institution_id, $branch_id]);
        $record = $check_stmt->fetch(PDO::FETCH_ASSOC);

        if (!$record) {
            errorreturn("Fuel expense record not found or access denied.");
        }

        // Delete record
        $delete_sql = "DELETE FROM fuel_expense WHERE id = ?";
        $delete_stmt = $conn_rjllearning_specific->prepare($delete_sql);
        $delete_stmt->execute([$fuel_expense_id]);

        successreturn(["successmsg" => "Fuel expense deleted successfully"]);
    } catch (Exception $e) {
        errorreturn("Error: " . $e->getMessage());
    }
}
?>
