<?php
session_start();
require_once __DIR__ . '/../../includes/auth.php';
require_once __DIR__ . '/../../classes/Database.php';
require_once __DIR__ . '/../../classes/Request.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);
$request = new Request($conn, $logger);
$branch = new Branch($conn);


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

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

        if (empty($requestId)) {
            throw new Exception("Invalid request ID.");
        }


        $requestData = $request->getRequestById($requestId);
        if (!$requestData) {
            throw new Exception("Request not found.");
        }


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

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


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

        $success = $request->deleteRequest($requestId);

        if ($success) {

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