<?php
session_start();
if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header("Location: ../auth/login.php");
    exit();
}

require_once __DIR__ . '/../../controllers/BranchController.php';
require_once __DIR__ . '/../../controllers/ProductController.php';

$branchController = new BranchController();
$productController = new ProductController();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['transfer'])) {
        $branchController->transferProducts($_POST['from_branch_id'], $_POST['to_branch_id'], $_POST['product_id'], $_POST['quantity']);
    }
    header("Location: transfer_products.php");
    exit();
}

$branches = $branchController->getBranches();
$products = $productController->getProducts();
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Traslado de Productos</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
    <div class="container">
        <h1 class="mt-3">Traslado de Productos</h1>
        
        <form method="POST">
            <input type="hidden" name="transfer">
            <div class="mb-3">
                <label for="from_branch_id" class="form-label">Desde Sucursal</label>
                <select class="form-select" id="from_branch_id" name="from_branch_id">
                    <?php foreach ($branches as $branch): ?>
                        <option value="<?php echo $branch['id']; ?>"><?php echo $branch['name']; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="mb-3">
                <label for="to_branch_id" class="form-label">A Sucursal</label>
                <select class="form-select" id="to_branch_id" name="to_branch_id">
                    <?php foreach ($branches as $branch): ?>
                        <option value="<?php echo $branch['id']; ?>"><?php echo $branch['name']; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="mb-3">
                <label for="product_id" class="form-label">Producto</label>
                <select class="form-select" id="product_id" name="product_id">
                    <?php foreach ($products as $product): ?>
                        <option value="<?php echo $product['id']; ?>"><?php echo $product['name']; ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="mb-3">
                <label for="quantity" class="form-label">Cantidad</label>
                <input type="number" class="form-control" id="quantity" name="quantity" required>
            </div>
            <button type="submit" class="btn btn-primary">Trasladar</button>
        </form>

        <a href="dashboard.php" class="btn btn-primary mt-3">Volver al Dashboard</a>
    </div>
</body>
</html>