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


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

$database = new Database();
$conn = $database->getConnection();


if (!$conn) {
    die("Error: Database connection failed.");
}

$auth = new Auth($conn);
$deposit = new Deposit($conn);


$branchId = $auth->getUserBranch($_SESSION['user_id']);
if (!$branchId) {
    die("Error: You are not assigned to any branch.");
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {

        error_log("Starting deposit process for branch ID: " . $branchId);


        $depositDate = isset($_POST['deposit_date']) ? filter_input(INPUT_POST, 'deposit_date', FILTER_SANITIZE_STRING) : date('Y-m-d');
        $amount = isset($_POST['deposit_amount']) ? filter_input(INPUT_POST, 'deposit_amount', FILTER_SANITIZE_NUMBER_FLOAT) : 0;
        $notes = isset($_POST['deposit_notes']) ? filter_input(INPUT_POST, 'deposit_notes', FILTER_SANITIZE_STRING) : '';
        $userId = $_SESSION['user_id'];


        error_log("Received inputs: deposit_date=$depositDate, amount=$amount, notes=$notes, user_id=$userId");


        if ($amount <= 0) {
            throw new Exception("Deposit amount must be greater than zero.");
        }


        $success = $deposit->addDeposit($branchId, $depositDate, $amount, $notes, $userId);


        error_log("addDeposit result: " . ($success ? "Success" : "Failed"));

        if ($success) {

            header('Location: weekly2.php');
            exit();
        } else {
            throw new Exception("Failed to add deposit.");
        }
    } catch (Exception $e) {

        error_log("Error recording deposit: " . $e->getMessage());
        error_log("Stack trace: " . $e->getTraceAsString());


        header('Location: weekly2.php?error=' . urlencode("Error recording deposit. Please try again."));
        exit();
    }
}
?>