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


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


$auth = new Auth($conn);
$order = new Order($conn);
$branch = new Branch($conn);


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

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['order_id'])) {
    try {
        $orderId = filter_input(INPUT_POST, 'order_id', FILTER_SANITIZE_NUMBER_INT);

        if (empty($orderId)) {
            throw new Exception("Invalid order ID provided.");
        }


        $orderData = $order->getOrderById($orderId);
        if (!$orderData) {
            throw new Exception("Order not found.");
        }


        $isSuperAdmin = $auth->isSuperAdmin($_SESSION['user_id']);
        $userBranchId = $auth->getUserBranch($_SESSION['user_id']);
        $orderBranchId = $orderData['branch_id'] ?? null;

        if (!$isSuperAdmin && $userBranchId != $orderBranchId) {
            throw new Exception("You do not have permission to delete this order.");
        }


        $branchId = filter_input(INPUT_POST, 'branch_id', FILTER_SANITIZE_NUMBER_INT) ?? '';
        $searchTerm = filter_input(INPUT_POST, 'search_term', FILTER_SANITIZE_STRING) ?? '';
        $searchField = filter_input(INPUT_POST, 'search_field', FILTER_SANITIZE_STRING) ?? '';


        $conn->beginTransaction();
        $success = $order->deleteOrder($orderId);

        if ($success) {
            $conn->commit();

            $queryParams = http_build_query([
                'success' => 'Order deleted successfully.',
                'branch_id' => $branchId,
                'search_term' => $searchTerm,
                'search_field' => $searchField
            ]);
            header('Location: list_orders.php?' . $queryParams);
        } else {
            $conn->rollBack();
            throw new Exception("Failed to delete the order.");
        }
    } catch (Exception $e) {
        if ($conn->inTransaction()) {
            $conn->rollBack();
        }
        error_log("Error processing order deletion for order_id=$orderId: " . $e->getMessage());
        header('Location: list_orders.php?error=' . urlencode($e->getMessage()));
    }
    exit();
} else {
    $error = 'Invalid request method or missing order ID.';
    error_log($error . " Request method: {$_SERVER['REQUEST_METHOD']}, POST data: " . json_encode($_POST));
    header('Location: list_orders.php?error=' . urlencode($error));
    exit();
}
?>