<?php
include 'includes/config.php';

$bank_id = isset($_GET['bank_id']) ? $_GET['bank_id'] : '';

if ($bank_id) {
    // Fetch the start bank balance for the selected bank
    $stmt1 = $conn->prepare("SELECT start_bank_balance FROM banks WHERE id = :bank_id");
    $stmt1->execute(['bank_id' => $bank_id]);
    $bank = $stmt1->fetch();

    // Fetch the sum of amounts from cash_deposit for the selected bank
    $stmt2 = $conn->prepare("SELECT SUM(amount) AS total_deposit FROM cash_deposit WHERE bank_id = :bank_id");
    $stmt2->execute(['bank_id' => $bank_id]);
    $deposit = $stmt2->fetch();

    // Fetch the sum of amounts from bank_debit_amount for the selected bank
    $stmt3 = $conn->prepare("SELECT SUM(amount) AS total_debit FROM bank_debit_amount WHERE bank_id = :bank_id");
    $stmt3->execute(['bank_id' => $bank_id]);
    $debit = $stmt3->fetch();

    // Calculate the remaining amount
    $remaining_amount = ($bank['start_bank_balance'] ?? 0) + ($deposit['total_deposit'] ?? 0) - ($debit['total_debit'] ?? 0);

    // Return the remaining amount
    echo json_encode(['remaining_amount' => $remaining_amount]);
} else {
    echo json_encode(['remaining_amount' => 0]);
}
?>
