<?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/Shipment.php';
require_once __DIR__ . '/../../classes/MraEisCompliance.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: shipment_dashboard.php');
    exit();
}

$database = new Database();
$conn = $database->getConnection();
$auth = new Auth($conn);
$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'] ?? '', $_SESSION['role'] ?? '');
$shipment = new Shipment($conn, $logger);

$shipmentId = filter_input(INPUT_POST, 'shipment_id', FILTER_VALIDATE_INT);
$redirectTo = $_POST['redirect_to'] ?? 'view_shipments.php';
$redirectPath = parse_url($redirectTo, PHP_URL_PATH);
$redirectBase = basename($redirectPath ?: '');
$redirectHost = parse_url($redirectTo, PHP_URL_HOST);
$allowedRedirects = ['view_shipments.php', 'pending_approvals.php', 'pending_approvals_branch.php', 'shipment_dashboard.php', 'ship_items_form.php'];

if (!in_array($redirectBase, $allowedRedirects, true) || $redirectHost !== null || preg_match('/^https?:\/\//i', $redirectTo)) {
    $redirectTo = 'shipment_dashboard.php';
}

if (!$shipmentId) {
    $_SESSION['error'] = 'Invalid shipment selected for deletion.';
    header('Location: ' . $redirectTo);
    exit();
}

$shipmentDetails = $shipment->getShipmentById($shipmentId);
if (!$shipmentDetails) {
    $_SESSION['error'] = 'Shipment not found.';
    header('Location: ' . $redirectTo);
    exit();
}

if ($shipmentDetails['status'] !== 'pending') {
    $_SESSION['error'] = 'Only pending shipments can be deleted.';
    header('Location: ' . $redirectTo);
    exit();
}

$role = $_SESSION['role'] ?? '';
$userBranchId = $auth->getUserBranch($_SESSION['user_id']);
$canDelete = $auth->isSuperAdmin($_SESSION['user_id'])
    || $auth->isWarehousePersonnel($_SESSION['user_id'])
    || ($role === 'branch' && $userBranchId == $shipmentDetails['from_branch_id']);

if (!$canDelete) {
    $_SESSION['error'] = 'You are not authorized to delete this pending shipment.';
    header('Location: ' . $redirectTo);
    exit();
}

$eisCompliance = new MraEisCompliance($conn);
if ($eisCompliance->transferAlreadySubmitted($shipmentId)) {
    $_SESSION['error'] = "Shipment #{$shipmentId} has already been submitted to MRA EIS as a stock transfer and cannot be undone here. Contact MRA/finance if a correction is needed.";
    header('Location: ' . $redirectTo);
    exit();
}

$result = $shipment->deletePendingShipment($shipmentId, $_SESSION['user_id']);

if ($result === true) {
    $eisCompliance->cancelUnsubmittedTransfer($shipmentId);
    $_SESSION['success'] = "Pending shipment #{$shipmentId} deleted. Items were returned to the origin branch.";
} else {
    $_SESSION['error'] = is_string($result) ? $result : 'Failed to delete pending shipment.';
}

header('Location: ' . $redirectTo);
exit();
?>
