nd<?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';


$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'], ['branch', 'branch'])) {
    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'] ?? [];
    $selected_item_ids = $_POST['selected_item_ids'] ?? [];


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


    if (!$source_branch_id || !$destination_branch_id) {
        $_SESSION['error'] = 'Invalid source or destination branch.';
        header("Location: branch_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: branch_ship_items_form.php?branch_id=$destination_branch_id&mode=$mode");
        exit();
    }


    $item_ids = [];
    foreach ($selected_item_ids as $selected_item_id) {
        if (filter_var($selected_item_id, FILTER_VALIDATE_INT)) {
            $item_ids[] = (int)$selected_item_id;
        }
    }

    foreach ($items as $item_id => $data) {
        if (isset($data['selected']) && $data['selected'] == '1') {
            $posted_item_id = !empty($data['item_id']) ? $data['item_id'] : $item_id;

            if (filter_var($posted_item_id, FILTER_VALIDATE_INT)) {
                $item_ids[] = (int)$posted_item_id;
            }
        }
    }

    $item_ids = array_values(array_unique($item_ids));

    if (empty($item_ids)) {
        $_SESSION['error'] = 'No items selected for shipment.';
        header("Location: branch_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: branch_ship_items_form.php?branch_id=$destination_branch_id&mode=$mode");
        exit();
    }


    $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.";

        // Auto-queue and submit this transfer to MRA EIS. 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 a successful 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.';
                } 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: branch_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: branch_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: branch_ship_items_form.php?branch_id=$destination_branch_id&mode=$mode");
    } else {
        header("Location: add_items_dashboard3.php");
    }
    exit();
}
?>
