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


if (!isset($_GET['bank_id'])) {
    header('location: list_banks.php');
    exit();
}

$bank_id = $_GET['bank_id'];

// Default date range (Last month to today)
$end_date_bank = isset($_GET['end_date_bank']) ? $_GET['end_date_bank'] : date('Y-m-d');
$start_date_bank = isset($_GET['start_date_bank']) ? $_GET['start_date_bank'] : '1970-01-01';
// $start_date_bank = isset($_GET['start_date_bank']) ? $_GET['start_date_bank'] : date('Y-m-d', strtotime('-1 month'));

// Fetch bank details including start_bank_date
try {
    $sql = "SELECT * FROM banks WHERE id = :bank_id";
    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':bank_id', $bank_id);
    $stmt->execute();
    $bank = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$bank) {
        echo "Bank not found.";
        exit();
    }

    // Fetch deposit transactions (credits)
    $sql_deposit = "
        SELECT id, amount, status, payment_status, DATE(date_deposit) as date_deposit
        FROM cash_deposit
        WHERE bank_id = :bank_id AND date_deposit BETWEEN :start_date_bank AND :end_date_bank
        ORDER BY date_deposit ASC
    ";
    $stmt_deposit = $conn->prepare($sql_deposit);
    $stmt_deposit->bindParam(':bank_id', $bank_id);
    $stmt_deposit->bindParam(':start_date_bank', $start_date_bank);
    $stmt_deposit->bindParam(':end_date_bank', $end_date_bank);
    $stmt_deposit->execute();
    $deposits = $stmt_deposit->fetchAll(PDO::FETCH_ASSOC);

    // Fetch debit transactions
    $sql_debit = "
        SELECT id, amount, note, DATE(date) as date
        FROM bank_debit_amount
        WHERE bank_id = :bank_id AND date BETWEEN :start_date_bank AND :end_date_bank
        ORDER BY date ASC
    ";
    $stmt_debit = $conn->prepare($sql_debit);
    $stmt_debit->bindParam(':bank_id', $bank_id);
    $stmt_debit->bindParam(':start_date_bank', $start_date_bank);
    $stmt_debit->bindParam(':end_date_bank', $end_date_bank);
    $stmt_debit->execute();
    $debits = $stmt_debit->fetchAll(PDO::FETCH_ASSOC);

    $balance = $bank['start_bank_balance'];
    $start_bank_date = $bank['start_bank_date']; // Fetch the start date for the bank

} catch (PDOException $e) {
    echo "Error: " . $e->getMessage();
    exit();
}

$total_debit = 0;
$total_credit = 0;

$transactions = [];

foreach ($deposits as $deposit) {
    $particulars = !empty($deposit['status']) ? 'Customer Payment' : $deposit['payment_status'];
    $transactions[] = [
        'date' => $deposit['date_deposit'],
        'particulars' => $particulars,
        'debit' => 0,
        'credit' => $deposit['amount'],
        'type' => 'credit',
        'id' => $deposit['id']
    ];
}

foreach ($debits as $debit) {
    $transactions[] = [
        'date' => $debit['date'],
        'particulars' => $debit['note'],
        'debit' => $debit['amount'],
        'credit' => 0,
        'type' => 'debit',
        'id' => $debit['id']
    ];
}

usort($transactions, function ($a, $b) {
    return strcmp($a['date'], $b['date']);
});

$today_date = date('Y-m-d');
$opening_balance_today = $bank['start_bank_balance'];
$closing_balance_today = $bank['start_bank_balance'];

$previous_closing_balance = $bank['start_bank_balance'];

foreach ($transactions as $transaction) {
    if ($transaction['date'] < $today_date) {
        if ($transaction['type'] === 'credit') {
            $previous_closing_balance += $transaction['credit'];
        } elseif ($transaction['type'] === 'debit') {
            $previous_closing_balance -= $transaction['debit'];
        }
    }
}

$opening_balance_today = $previous_closing_balance;

foreach ($transactions as $transaction) {
    if ($transaction['date'] === $today_date) {
        if ($transaction['type'] === 'credit') {
            $closing_balance_today += $transaction['credit'];
        } elseif ($transaction['type'] === 'debit') {
            $closing_balance_today -= $transaction['debit'];
        }
    }
}
?>  <table class="table table-hover table-bordered" style="display: none;">
<thead>
    <tr>
        <th>Date</th>
        <th>Particulars</th>
        <th>Debit</th>
        <th>Credit</th>
        <th>Balance</th>
    </tr>
</thead>
<tbody>
    <?php if ($start_bank_date >= $start_date_bank && $start_bank_date <= $end_date_bank) { ?>
        <tr>
            <td><?php echo htmlspecialchars($start_bank_date); ?></td>
            <td>Bank Start Balance</td>
            <td></td>
            <td><?php echo number_format($balance, 2); ?></td>
            <td><?php echo number_format($balance, 2); ?></td>
        </tr>
    <?php } ?>

    <!-- Display Transactions -->
    <?php
    foreach ($transactions as $transaction) {
        if ($transaction['type'] === 'credit') {
            $balance += $transaction['credit'];
            $total_credit += $transaction['credit'];
        } elseif ($transaction['type'] === 'debit') {
            $balance -= $transaction['debit'];
            $total_debit += $transaction['debit'];
        }
    ?>
        <tr>
            <td><?php echo htmlspecialchars($transaction['date']); ?></td>
            <td><?php echo htmlspecialchars($transaction['particulars']); ?></td>
            <td>
                <?php if ($transaction['debit'] > 0) { ?>
                    <?php echo number_format($transaction['debit'], 2); ?>
                    <div class="dropdown">
                        <button class="dropbtn">...</button>
                        <div class="dropdown-content">
                            <a href="#" class="edit-debit" data-id="<?php echo $transaction['id']; ?>">Edit</a>
                            <a href="#" class="delete-debit" data-id="<?php echo $transaction['id']; ?>">Delete</a>
                        </div>
                    </div>
                <?php } ?>
            </td>
            <td>
                <?php if ($transaction['credit'] > 0) { ?>
                    <?php echo number_format($transaction['credit'], 2); ?>
                    <div class="dropdown">
                        <button class="dropbtn">...</button>
                        <div class="dropdown-content">
                            <a href="#" class="edit-credit" data-id="<?php echo $transaction['id']; ?>">Edit</a>
                            <a href="#" class="delete-credit" data-id="<?php echo $transaction['id']; ?>">Delete</a>
                        </div>
                    </div>
                <?php } ?>
            </td>
            <td><?php echo number_format($balance, 2); ?></td>
        </tr>
    <?php } ?>
</tbody>
<tfoot>
    <tr>
        <td colspan="2"><strong>Total</strong></td>
        <td><strong><?php echo number_format($total_debit, 2); ?></strong></td>
        <td><strong><?php echo number_format($total_credit, 2); ?></strong></td>
        <td><strong><?php echo number_format($balance, 2); ?></strong></td>
    </tr>
</tfoot>
</table>
<div class="balances">
        <div class="balance-box">
            <h3>Today Opening Balance</h3>
            <p><?php echo number_format($opening_balance_today, 2); ?></p>
        </div>
        <div class="balance-box">
            <h3>Today Closing Balance</h3>
            <p><?php echo number_format($balance, 2); ?></p>
        </div>
    </div>
    