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


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


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


$auth = new Auth($conn);
$quotation = new Quotation($conn, $logger);
$branch = new Branch($conn);


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

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

        if (empty($quotationId)) {
            throw new Exception("Invalid quotation ID.");
        }


        $quotationData = $quotation->getQuotationById($quotationId);
        if (!$quotationData) {
            throw new Exception("Quotation not found.");
        }


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

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


        $branchId = $_POST['branch_id'] ?? '';
        $searchTerm = $_POST['search_term'] ?? '';
        $searchField = $_POST['search_field'] ?? '';

        $success = $quotation->deleteQuotation($quotationId);

        if ($success) {

            $queryParams = http_build_query([
                'success' => 'Quotation deleted successfully.',
                'branch_id' => $branchId,
                'search_term' => $searchTerm,
                'search_field' => $searchField
            ]);
            header('Location: list_quotations.php?' . $queryParams);
        } else {
            throw new Exception("Failed to delete the quotation.");
        }
    } catch (Exception $e) {
        error_log("Error processing quotation deletion: " . $e->getMessage());
        header('Location: list_quotations.php?error=' . urlencode($e->getMessage()));
    }
    exit();
} else {
    header('Location: list_quotations.php?error=' . urlencode('Invalid request method.'));
    exit();
}
?>