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


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


$auth = new Auth($conn);


$logger = new Logger($conn, $_SESSION['user_id'], $_SESSION['username'], $_SESSION['role']);
if (!isset($_SESSION['user_id'])) {
    header('Location: /IMS/login.php');
    exit();
}


if (!in_array($_SESSION['role'], ['admin', 'warehouse'])) {
    header('Location: /IMS/unauthorized.php');
    exit();
}


$shipment = new Shipment($conn, $logger);
$branch = new Branch($conn);


if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    $source_branch_id = filter_input(INPUT_POST, 'source_branch_id', FILTER_VALIDATE_INT);
    $destination_branch_id = filter_input(INPUT_POST, 'destination_branch_id', FILTER_VALIDATE_INT);
    $items = $_POST['items'] ?? [];


    $mode = $_POST['mode'] ?? 'manual';

    $itemsPayload = trim((string)($_POST['items_payload'] ?? ''));
    if ($itemsPayload !== '') {
        $decodedItems = json_decode($itemsPayload, true);
        if (!is_array($decodedItems) || json_last_error() !== JSON_ERROR_NONE) {
            $_SESSION['error'] = 'The selected shipment items could not be read. Please select them again.';
            header("Location: ship_items_form.php?branch_id=$destination_branch_id&mode=$mode");
            exit();
        }
        if (count($decodedItems) > 10000) {
            $_SESSION['error'] = 'A shipment can contain at most 10,000 items.';
            header("Location: ship_items_form.php?branch_id=$destination_branch_id&mode=$mode");
            exit();
        }

        $items = [];
        foreach ($decodedItems as $entry) {
            $itemId = filter_var($entry['item_id'] ?? null, FILTER_VALIDATE_INT);
            if (!$itemId || $itemId <= 0) {
                continue;
            }
            $items[$itemId] = ['selected' => '1', 'item_id' => $itemId];
            $priceOverride = $entry['price_override'] ?? null;
            if (is_numeric($priceOverride) && (float)$priceOverride > 0) {
                $items[$itemId]['price_override'] = (float)$priceOverride;
            }
        }
    }


    if (!$source_branch_id || !$destination_branch_id) {
        $_SESSION['error'] = 'Invalid source or destination branch.';
        header("Location: ship_items_form.php?branch_id=$destination_branch_id&mode=$mode");
        exit();
    }

    if ($source_branch_id == $destination_branch_id) {
        $_SESSION['error'] = 'Cannot ship items from a branch to itself.';
        header("Location: ship_items_form.php?branch_id=$destination_branch_id&mode=$mode");
        exit();
    }


    $item_ids = [];
    $price_overrides = [];
    foreach ($items as $item_id => $data) {
        if (isset($data['selected']) && $data['selected'] == '1' && !empty($data['item_id'])) {
            $itemId = (int)$data['item_id'];
            $item_ids[] = $itemId;
            if (isset($data['price_override']) && is_numeric($data['price_override']) && (float)$data['price_override'] > 0) {
                $price_overrides[$itemId] = (float)$data['price_override'];
            }
        }
    }

    if (count($item_ids) > 10000) {
        $_SESSION['error'] = 'A shipment can contain at most 10,000 items.';
        header("Location: ship_items_form.php?branch_id=$destination_branch_id&mode=$mode");
        exit();
    }

    if (empty($item_ids)) {
        $_SESSION['error'] = 'No items selected for shipment.';
        header("Location: ship_items_form.php?branch_id=$destination_branch_id&mode=$mode");
        exit();
    }

    $user_branch_id = $auth->getUserBranch($_SESSION['user_id']);
    if ($_SESSION['role'] === 'admin') {
        $user_branch_id = 7;
    }

    if ($user_branch_id != $source_branch_id) {
        $_SESSION['error'] = 'You are not authorized to ship from this source branch.';
        header("Location: ship_items_form.php?branch_id=$destination_branch_id&mode=$mode");
        exit();
    }

    // Spreadsheet imports explicitly supply the transfer selling price. Manual selection only
    // sends this field when a price is missing, so applying submitted overrides preserves both flows.
    if (!empty($price_overrides)) {
        $inventory = new Inventory($conn);
        $placeholders = implode(',', array_fill(0, count($price_overrides), '?'));
        $priceCheckStmt = $conn->prepare(
            "SELECT item_id FROM items
             WHERE item_id IN ($placeholders) AND current_location_id = ? AND shelf_status = 'on_shelf'"
        );
        $priceCheckStmt->execute(array_merge(array_keys($price_overrides), [$source_branch_id]));
        foreach ($priceCheckStmt->fetchAll(PDO::FETCH_COLUMN) as $itemId) {
            $itemId = (int)$itemId;
            if (isset($price_overrides[$itemId])) {
                $inventory->updateNew($itemId, $price_overrides[$itemId]);
            }
        }
    }


    $result = $shipment->createShipment(
        $source_branch_id,
        $destination_branch_id,
        $_SESSION['user_id'],
        $item_ids
    );


    if (is_numeric($result) && $result > 0) {

        $_SESSION['success'] = "Shipment #$result created successfully with " . count($item_ids) . " items.";
        $_SESSION['last_shipment_id'] = (int)$result;

        // Auto-queue and submit this transfer to MRA EIS (warehouse -> site stock transfer).
        // Never blocks/rolls back the already-successful shipment - these calls only throw if the
        // shipment truly can't be found, which shouldn't happen immediately after createShipment().
        try {
            $eisCompliance = new MraEisCompliance($conn);
            $eisResult = $eisCompliance->prepareTransfer((int)$result, $_SESSION['user_id']);

            if (($eisResult['status'] ?? '') === 'ready' && !empty($eisResult['id'])) {
                $submitResult = $eisCompliance->submitOutbox((int)$eisResult['id'], $_SESSION['user_id']);
                if (!empty($submitResult['success'])) {
                    $_SESSION['success'] .= ' MRA EIS stock transfer submitted successfully.';
                    $_SESSION['transfer_receipt_shipment_id'] = (int)$result;
                } else {
                    $_SESSION['success'] .= ' MRA EIS stock transfer is queued for retry: ' . ($submitResult['message'] ?? 'submission did not complete.');
                }
            } elseif (($eisResult['status'] ?? '') === 'blocked') {
                $_SESSION['success'] .= ' MRA EIS stock transfer could not be queued: ' . ($eisResult['last_error'] ?? 'unknown reason.');
            }
        } catch (Throwable $e) {
            error_log('MRA EIS transfer submission failed for shipment #' . $result . ': ' . $e->getMessage());
            $_SESSION['success'] .= ' MRA EIS stock transfer could not be submitted; it remains queued for retry.';
        }

        header("Location: ship_items_form.php?branch_id=$destination_branch_id&mode=$mode");
        exit();
    } else {

        $error_message = is_string($result) ? $result : 'Failed to create shipment. Please try again.';
        $_SESSION['error'] = $error_message;
        header("Location: ship_items_form.php?branch_id=$destination_branch_id&mode=$mode");
        exit();
    }
} else {

    $destination_branch_id = $_SESSION['last_destination_branch_id'] ?? '';
    $mode = $_SESSION['last_mode'] ?? 'manual';

    $_SESSION['error'] = 'Invalid request method.';

    if ($destination_branch_id) {
        header("Location: ship_items_form.php?branch_id=$destination_branch_id&mode=$mode");
    } else {
        header("Location: add_items_dashboard2.php");
    }
    exit();
}
?>