<?php
// admin/accounts/delete-deposit.php
require_once __DIR__ . '/../../includes/config.php';
require_once __DIR__ . '/../../includes/functions.php';

if (!isAdmin()) {
    header('Location: ../login.php');
    exit;
}

$id = intval($_GET['id'] ?? 0);
if ($id > 0) {
    try {
        // Get deposit details
        $stmt = $pdo->prepare("SELECT * FROM deposits WHERE id = ?");
        $stmt->execute([$id]);
        $deposit = $stmt->fetch();

        if ($deposit) {
            // Reverse account balance
            $stmt = $pdo->prepare("UPDATE bank_accounts SET current_balance = current_balance - ? WHERE id = ?");
            $stmt->execute([$deposit['amount'], $deposit['account_id']]);

            // Delete deposit
            $stmt = $pdo->prepare("DELETE FROM deposits WHERE id = ?");
            $stmt->execute([$id]);

            // Delete transaction record
            $stmt = $pdo->prepare("DELETE FROM account_transactions WHERE reference_no = ? AND transaction_type = 'deposit'");
            $stmt->execute([$deposit['deposit_no']]);

            $_SESSION['success_msg'] = 'Deposit deleted successfully!';
        }
    } catch (Exception $e) {
        $_SESSION['error_msg'] = 'Error: ' . $e->getMessage();
    }
}

header('Location: deposits.php');
exit;
?>