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


header('Content-Type: application/json');


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


$auth = new Auth($conn);
if (!isset($_SESSION['user_id'])) {
    echo json_encode(['error' => 'Authentication required']);
    exit();
}


if ($_SESSION['role'] != 'admin' && $_SESSION['role'] != 'warehouse') {
    echo json_encode(['error' => 'Unauthorized access']);
    exit();
}


if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['error' => 'Invalid request method']);
    exit();
}


$postData = json_decode(file_get_contents('php://input'), true);

if (!$postData) {
    echo json_encode(['error' => 'No data received']);
    exit();
}


$destination_branch_id = isset($postData['destination_branch_id']) ? intval($postData['destination_branch_id']) : 0;
$source_branch_id = isset($postData['source_branch_id']) ? intval($postData['source_branch_id']) : 0;
$items = isset($postData['items']) ? $postData['items'] : [];


if (!$destination_branch_id || !$source_branch_id) {
    echo json_encode(['error' => 'Invalid branch information']);
    exit();
}


if (empty($items)) {

    echo json_encode(['error' => 'No items selected for shipment']);
    exit();
}


$branch = new Branch($conn);
$destination_branch = $branch->getBranchById($destination_branch_id);
$source_branch = $branch->getBranchById($source_branch_id);

if (!$destination_branch || !$source_branch) {
    echo json_encode(['error' => 'Branch information not found']);
    exit();
}


$inventory = new Inventory($conn);


$response = [
    'success' => true,
    'destination' => $destination_branch['branch_name'],
    'source' => $source_branch['branch_name'],
    'items' => [],
    'total_value' => 0
];


foreach ($items as $item_id => $item_data) {

    if (isset($item_data['selected']) && $item_data['selected']) {

        $item_details = $inventory->getItemById($item_id);

        if ($item_details) {

            $quantity = 1;




            $unit_price = floatval($item_details['unit_price']);
            $item_total = $unit_price * $quantity;


            $response['items'][] = [
                'item_id' => $item_id,
                'item_name' => $item_details['item_name'],
                'unique_id' => $item_details['unique_code'] ?? 'N/A',
                'unit_price' => $unit_price,

                'total' => $item_total
            ];


            $response['total_value'] += $item_total;
        } else {

        }
    }
}


if (empty($response['items'])) {
     echo json_encode(['error' => 'No valid items found for shipment.']);
     exit();
}



echo json_encode($response);
exit();
?>