<?php
require 'conexion.php'; // Incluye el archivo de conexión

// Inicializar variables
$mensaje = '';
$resultado = null;
$Pcantidad = $Prowid = $Corigen = '';
$estadoPedido = null; // Variable para almacenar el estado del pedido

// Asegúrate de que las variables están definidas
if (isset($vendedorNombre) && isset($vendedorId)) {
    // Usar las variables
    echo "<h2 style='font-size: 1em;'>Bienvenido al Módulo:</h2>";
    echo "<p style='font-size: 1.2em; color: blue; font-weight: bold;'>" . htmlspecialchars($vendedorNombre) . "</p>";
   
   // Mostrar la fecha y hora en el HTML
//echo "<p style='font-size: 1.2em; color: blue; font-weight: bold;'>" . dol_escape_htmltag($fechaHoraLegible) . "</p>";

     //echo "<h2 style='font-size: 1em;'>Id Detectado:</h2>";
    //echo "<p style='font-size: 1.2em; color: blue; font-weight: bold;'>" . htmlspecialchars($vendedorId) . "</p>";
} else {
    echo "<h2 style='font-size: 1.5em;'>No se han recibido las variables.</h2>";
}

// Procesar búsqueda de factura
if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['id_factura'])) {
    $id_factura = $_POST['id_factura'];


     // Consulta SQL para obtener los detalles del pedido
    $sql = "SELECT 
                cd.rowid AS id_linea,
                s.nom AS Cliente, 
                c.rowid AS id_pedido, 
                c.ref AS Ref_Pedido, 
                c.date_creation AS Fecha_Creacion, 
                p.rowid AS id_producto, 
                p.label AS Producto, 
                cd.description AS descripcion, 
                cd.qty AS Cantidad, 
                u.nom_unidad AS Tipo_despacho, 
                extra2.cantidad_despacho AS Cantidad_Despacho,
                c.fk_statut AS Estado_Pedido
            FROM 
                llx_element_element AS ee
            INNER JOIN 
                llx_commande AS c ON ee.fk_source = c.rowid
            INNER JOIN 
                llx_societe AS s ON c.fk_soc = s.rowid
            INNER JOIN 
                llx_commandedet AS cd ON c.rowid = cd.fk_commande
            LEFT JOIN 
                llx_projet AS pj ON c.fk_projet = pj.rowid
            LEFT JOIN 
                llx_user AS uc ON c.fk_user_author = uc.rowid
            LEFT JOIN 
                llx_user AS uv ON c.fk_user_valid = uv.rowid
            LEFT JOIN 
                llx_commande_extrafields AS extra ON c.rowid = extra.fk_object
            LEFT JOIN 
                llx_commandedet_extrafields AS extra2 ON cd.rowid = extra2.fk_object
            LEFT JOIN 
                llx_udd AS u ON extra2.cestas = u.cod_unidad
            LEFT JOIN 
                llx_product AS p ON cd.fk_product = p.rowid
            LEFT JOIN 
                llx_product_extrafields AS extra3 ON p.rowid = extra3.fk_object
            WHERE 
                ee.fk_target = '$id_factura'
                AND ee.targettype = 'facture'
                AND c.entity IN (1)";

    $result = $conn->query($sql);

    if ($result->num_rows > 0) {
        // Asignar valores a las variables (solo para la primera fila)
        $row = $result->fetch_assoc();
        $Pcantidad = $row['Cantidad'];
        $Prowid = $row['id_producto'];
        $Corigen = $row['id_pedido'];
        $estadoPedido = $row['Estado_Pedido']; // Obtener el estado del pedido

        // Reiniciar el puntero del resultado para iterar desde el principio
        $result->data_seek(0);
    }
}
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Sistema de Gestión de Pedidos</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .logo { width: 180px; margin-bottom: 25px; }
        .title { 
            font-family: 'Segoe UI', sans-serif; 
            font-size: 2.2rem; 
            color: #2c3e50;
            margin-bottom: 35px;
            font-weight: 600;
            text-shadow: 2px 2px 4px rgba(0,0,0,0.1);
        }
        .form-container { 
            background: linear-gradient(145deg, #f8f9fa, #e9ecef);
            border-radius: 12px;
            box-shadow: 0 8px 30px rgba(0,0,0,0.12);
            padding: 25px;
            margin-bottom: 30px;
        }
        .btn-action {
            transition: all 0.3s ease;
            padding: 12px 25px;
            font-size: 1.1rem;
            border-radius: 8px;
            border: none;
        }
        .btn-despacho {
            background: #28a745;
            color: white;
        }
        .btn-devolucion {
            background: #dc3545;
            color: white;
        }
        .btn-cancelar {
            background: #6c757d;
            color: white;
        }
        .btn-action:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.2);
        }
        .table-custom {
            background: white;
            border-radius: 10px;
            overflow: hidden;
            box-shadow: 0 2px 15px rgba(0,0,0,0.1);
        }
        .alert-custom {
            border-radius: 8px;
            padding: 20px;
            margin-top: 25px;
        }
    </style>
</head>
<body>
    <div class="container">
        <!-- Encabezado -->
        <div class="row justify-content-center mb-5">
            <div class="col-md-10 text-center">
                <img src="logo.png" alt="Logo de la empresa" class="logo">
                <h1 class="title">Gestión Integral de Pedidos</h1>
            </div>
        </div>

        <!-- Formulario de búsqueda -->
        <div class="row justify-content-center">
            <div class="col-md-8">
                <div class="form-container">
                    <form method="post">
                        <div class="form-group">
                            <label for="id_factura" class="font-weight-bold mb-3">Identificación de Factura:</label>
                            <input type="text" 
                                   class="form-control form-control-lg" 
                                   id="id_factura" 
                                   name="id_factura" 
                                   placeholder="Ingrese el ID de la factura"
                                   required>
                        </div>
                        <button type="submit" 
                                class="btn btn-primary btn-block btn-action">
                            <i class="fas fa-search mr-2"></i> Buscar Pedido
                        </button>
                    </form>
                </div>
            </div>
        </div>

        <!-- Resultados y acciones -->
        <?php if ($_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['id_factura'])): ?>
            <div class="row justify-content-center">
                <div >
                    <?php if ($result->num_rows > 0): ?>
                        <!-- Tabla de resultados -->
                        <div class="table-responsive">
                            <table class="table table-hover table-custom">
                                <thead class="bg-light">
                                    <tr>
                                        <th>Cliente</th>
                                        <th>Referencia</th>
                                        <th>Fecha Creación</th>
                                        <th>Producto</th>
                                        <th>Descripción</th>
                                        <th>Cantidad</th>
                                        <th>Tipo Despacho</th>
                                        <th>Cant. Despacho</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php while($row = $result->fetch_assoc()): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($row['Cliente']) ?></td>
                                            <td><?= htmlspecialchars($row['Ref_Pedido']) ?></td>
                                            <td><?= htmlspecialchars($row['Fecha_Creacion']) ?></td>
                                            <td><?= htmlspecialchars($row['Producto']) ?></td>
                                            <td><?= htmlspecialchars($row['descripcion']) ?></td>
                                            <td><?= htmlspecialchars($row['Cantidad']) ?></td>
                                            <td><?= htmlspecialchars($row['Tipo_despacho']) ?></td>
                                            <td><?= htmlspecialchars($row['Cantidad_Despacho']) ?></td>
                                        </tr>
                                    <?php endwhile; ?>
                                </tbody>
                            </table>
                        </div>

                        <!-- Botones de acción según el estado del pedido -->
                        <div class="row mt-4">
                            <?php if ($estadoPedido == 1): ?>
                                <!-- Estado 1: Mostrar botón de Despacho -->
                                <div class="col-md-6 mb-3">
                                    <form method="post" action="despachar.php">
                                        <input type="hidden" name="vendedorNombre" value="<?= $vendedorNombre ?>">
                                        <input type="hidden" name="vendedorId" value="<?= $vendedorId ?>">
                                        <input type="hidden" name="fecha_hora" value="<?= $fechaHoraLegible ?>">
                                        <input type="hidden" name="Corigen" value="<?= $Corigen ?>">
                                        <button type="submit" class="btn btn-despacho btn-block btn-action">
                                            <i class="fas fa-shipping-fast mr-2"></i> Procesar Despacho
                                        </button>
                                    </form>
                                </div>
                            <?php elseif ($estadoPedido == 3): ?>
                                <!-- Estado 3: Mostrar botón de Devolución y Cancelar -->
                                <div class="col-md-6 mb-3">
                                    <form method="post" action="devolucion_pedido.php">
                                        <input type="hidden" name="vendedorNombre" value="<?= $vendedorNombre ?>">
                                        <input type="hidden" name="vendedorId" value="<?= $vendedorId ?>">
                                        <input type="hidden" name="fecha_hora" value="<?= $fechaHoraLegible ?>">
                                        <input type="hidden" name="Corigen" value="<?= $Corigen ?>">
                                        <button type="submit" class="btn btn-devolucion btn-block btn-action">
                                            <i class="fas fa-undo-alt mr-2"></i> Iniciar Devolución
                                        </button>
                                    </form>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <a href="despachoindex.php" class="btn btn-cancelar btn-block btn-action">
                                        <i class="fas fa-times mr-2"></i> Cancelar y Volver
                                    </a>
                                </div>
                            <?php endif; ?>
                        </div>

                    <?php else: ?>
                        <div class="alert alert-warning alert-custom">
                            <h4 class="alert-heading">¡Atención!</h4>
                            <p>No se encontraron pedidos asociados a la factura: <strong><?= htmlspecialchars($id_factura) ?></strong></p>
                            <hr>
                            <p class="mb-0">Verifique que:</p>
                            <ul>
                                <li>El ID de factura sea correcto</li>
                                <li>El pedido esté validado (Estado 1) o despachado (Estado 3)</li>
                                <li>Exista relación factura-pedido</li>
                            </ul>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Scripts -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.9.2/dist/umd/popper.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
<?php
$conn->close();
?>