<?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/Branch.php';
require_once __DIR__ . '/../../classes/Shipment.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: ../../login.php');
    exit();
}
$auth->enforceSuperAdminPrivileges($_SESSION['user_id']);


$branch_id = $_GET['branch_id'] ?? null;
if ($branch_id === null) {
    die("No branch selected.");
}
$branch_id = (int)$branch_id;


$stmt = $conn->prepare("SELECT branch_name FROM branches WHERE branch_id = ?");
$stmt->execute([$branch_id]);
$branch_name = $stmt->fetchColumn();
if (!$branch_name) {
    die("Invalid branch.");
}


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

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


    $items = [];
    foreach ($_POST['items'] as $item_id => $quantity) {
        if ($quantity > 0) {
            $items[] = [
                'item_id' => $item_id,
                'quantity' => $quantity
            ];
        }
    }

    if (empty($items)) {
        $message = '<div class="alert alert-danger">Please select at least one item to ship.</div>';
    } else {

        $result = $shipment->createShipment(null, $branch_id, $_SESSION['user_id'], $items);

        if ($result) {
            $message = '<div class="alert alert-success">Shipment created successfully! Items will be added to branch inventory after verification.</div>';

            $_POST = [];
        } else {
            $message = '<div class="alert alert-danger">Failed to create shipment. Please try again.</div>';
        }
    }
}


$sql = "SELECT i.* FROM items i ORDER BY i.item_name";
$stmt = $conn->prepare($sql);
$stmt->execute();
$items = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>

<?php include __DIR__ . '/../../includes/header.php'; ?>
    <a href="shipment_dashboard.php" class="dashboard-return-link">
        <i class="fas fa-arrow-left"></i> Back to Shipment Dashboard
    </a>

    <div class="container mt-4">
        <h2>Create Shipment to <?php echo htmlspecialchars($branch_name); ?></h2>
        <p class="text-muted">Select items and quantities to ship. Items will be added to branch inventory only after verification at the branch.</p>

        <?php echo $message; ?>

        <form method="post" action="">
            <div class="card mb-4">
                <div class="card-header bg-primary text-white">
                    <h5 class="mb-0">Select Items for Shipment</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover">
                            <thead>
                                <tr>
                                    <th>Item Name</th>
                                    <th>Code</th>
                                    <th>Unit Price</th>
                                    <th width="150">Quantity to Ship</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($items as $item): ?>
                                <tr>
                                    <td><?php echo htmlspecialchars($item['item_name']); ?></td>
                                    <td><?php echo htmlspecialchars($item['unique_code']); ?></td>
                                    <td><?php echo htmlspecialchars($item['unit_price']); ?></td>
                                    <td>
                                        <input type="number" name="items[<?php echo $item['item_id']; ?>]"
                                               class="form-control" min="0" value="<?php echo isset($_POST['items'][$item['item_id']]) ? $_POST['items'][$item['item_id']] : 0; ?>">
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="card-footer">
                    <button type="submit" class="btn btn-primary">Create Shipment</button>
                </div>
            </div>
        </form>
    </div>

<?php include __DIR__ . '/../../includes/footer.php'; ?>