<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Deposit.php';


if (!isset($_SESSION['user_id'])) {
    header('Location: /IMS/login.php');
    exit();
}

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);
$deposit = new Deposit($conn);

if (!$auth->isBranchManager($_SESSION['user_id'])) {
    header('Location: weekly2.php?error=' . urlencode('Access denied. Only branch managers can delete deposits.'));
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_deposit'], $_POST['deposit_id'])) {
    $depositId = (int)$_POST['deposit_id'];


    if (!$deposit->isDepositUnverified($depositId)) {
        header('Location: weekly2.php?error=' . urlencode('Cannot delete a verified deposit.'));
        exit();
    }


    $depositData = $deposit->getDepositById($depositId);
    if (!$depositData) {
        header('Location: weekly2.php?error=' . urlencode('Deposit not found.'));
        exit();
    }

    $userBranchId = $auth->getUserBranch($_SESSION['user_id']);
    if ($depositData['branch_id'] != $userBranchId) {
        header('Location: weekly2.php?error=' . urlencode('You can only delete deposits for your branch.'));
        exit();
    }


    if ($deposit->deleteDeposit($depositId)) {
        header('Location: weekly2.php?success=' . urlencode('Deposit deleted successfully.'));
    } else {
        header('Location: weekly2.php?error=' . urlencode('Error deleting deposit. Please try again.'));
    }
} else {
    header('Location: weekly2.php?error=' . urlencode('Invalid request.'));
}
exit();
?>