<?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 . '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'];
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);
// Workspace_id, userid, etc., extracted 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;
$branch_id = $jwt_validate->data->branch_id;
$institution_id = $jwt_validate->data->institution_id;

$specific_db_name = validateUserAccess($conn_rjllearning, $userid, $role, $workspace_id,["principal"], 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';
require_once $base_path_to_learning . 'user_management/user_versioning.php';

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

// $institution_id = trim($postdata['institution_id']);
// $branch_id = trim($postdata['branch_id']);
$bus_id = trim($postdata['bus_id']);
$trans_date = isset($postdata['date']) ? $postdata['date'] : date('Y-m-d');
$topup = trim($postdata['topup']);
$meter_reading = isset($postdata['meter_reading']) ? trim($postdata['meter_reading']) : null;
$narration = isset($postdata['narration']) ? trim($postdata['narration']) : null;
$meter_reading_with_unit = !empty($meter_reading) ? $meter_reading . ' Kms' : null;
$topup_with_unit = $topup ;

if ($bus_id === 'miscellaneous' && empty($narration)) {
    errorreturn("Narration is required when bus id is 'miscellaneous'.");
} elseif ($bus_id !== 'miscellaneous' && empty($meter_reading)) {
    errorreturn("Meter reading is required when bus id is not 'miscellaneous'.");
}

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

function isBus_valid($conn_rjllearning_specific, $bus_id, $institution_id, $branch_id)
{
    if ($bus_id === 'miscellaneous') {
        return true;  // Allow 'miscellaneous' as valid
    }
    
    $sql = "SELECT COUNT(*) FROM buses WHERE id = ? AND institution_id = ? AND branch_id = ?";
    $stmt = $conn_rjllearning_specific->prepare($sql);
    $stmt->execute([$bus_id, $institution_id, $branch_id]);
    $count = $stmt->fetchColumn();
    return $count > 0;
}
if (!isBus_valid($conn_rjllearning_specific, $bus_id, $institution_id, $branch_id)) {
    errorreturn("Enter a valid bus id.");
}

$function_type = $postdata['function_type'];

if ($postdata['function_type'] == "create_bus_fuel_topup") {
    try {

        $sql = "INSERT INTO fuel_expense (institution_id, branch_id, bus_id, date, topup, meter_reading, added_by, date_created, time_created, narration, status) 
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

        $stmt = $conn_rjllearning_specific->prepare($sql);
        $stmt->execute(array(
            $institution_id,
            $branch_id,
            $bus_id,
            $trans_date,
            $topup_with_unit,
            $meter_reading_with_unit,
            $username,
            date('Y-m-d'),
            date('H:i:s'),
            $narration,
            1,
        ));

        $id = $conn_rjllearning_specific->lastInsertId();
        successreturn(array('id' => $id, 'successmsg' => "Fuel Topup Added Successfully"));
    } catch (Exception $e) {
        errorreturn("Error: " . $e->getMessage());
    }
} else if ($postdata['function_type'] == "alter_bus_fuel_topup") {
    // Check if expense_id is provided and not empty
    if (!isset($postdata['expense_id']) || !checkIfIssetAndNotEmpty($postdata['expense_id'])) {
        errorreturn('Enter Expense id');
    } else {
        $expense_id = trim($postdata['expense_id']);
    }

    $sql_check = "SELECT COUNT(*) FROM fuel_expense WHERE id = ? AND institution_id = ? AND branch_id = ?";
    $stmt_check = $conn_rjllearning_specific->prepare($sql_check);
    $stmt_check->execute([$expense_id, $institution_id, $branch_id]);
    $exists = $stmt_check->fetchColumn();

    if (!$exists) {
        errorreturn("Expense ID does not exist.");
    }


    try {

        $sql_users = "UPDATE fuel_expense SET bus_id = ?, topup = ?, meter_reading = ? WHERE id = ? AND institution_id = ? AND branch_id = ?";
        $stmt = $conn_rjllearning_specific->prepare($sql_users);
        $stmt->execute(array(
            $bus_id,
            $topup_with_unit,
            $meter_reading_with_unit,
            $expense_id,
            $institution_id,
            $branch_id
        ));

        // Check if any row was affected
        if ($stmt->rowCount() > 0) {
            successreturn("Fuel Expense Updated Successfully.");
        } else {
            errorreturn("No changes were made to the existing record.");
        }
    } catch (Exception $e) {
        errorreturn("Error updating expense: " . $e->getMessage());
    }
} else {
    errorreturn("Invalid Function Type");
}
