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

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

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


$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);

$sales = new Sales($conn, $logger);

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

$branchId = $auth->getUserBranch($_SESSION['user_id']);
if (!$branchId) {
    header('Location: weekly2.php?error=' . urlencode('No branch assigned.'));
    exit();
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['delete_sale'])) {
    try {
        $transactionId = filter_input(INPUT_POST, 'transaction_id', FILTER_SANITIZE_STRING);
        if (empty($transactionId)) {
            throw new Exception("Invalid transaction ID.");
        }

        $success = $sales->deleteSaleByTransactionId($transactionId, $branchId);
        if ($success) {
            header('Location: weekly2.php?success=' . urlencode('Sale transaction deleted successfully.'));
        } else {
            throw new Exception("Failed to delete sale transaction.");
        }
    } catch (Exception $e) {
        error_log("Error processing sale deletion: " . $e->getMessage());
        header('Location: weekly2.php?error=' . urlencode($e->getMessage()));
    }
    exit();
}
?>