<?php
session_start();
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') { die("Acceso Denegado"); }

$db_usuarios = "MS_Usuario";
$db_datos = "MS_Datos";
$prefijo = $_SESSION['IDU'] ?? '1'; // El # de tus tablas
$IDUg = $_SESSION['IDUg'] ?? 1;
?>

<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>AquaWash - Registro de Entrada</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        :root { --primary: #2563eb; --dark: #0f172a; }
        body { background: #f1f5f9; font-family: 'Inter', sans-serif; }
        .main-card { background: white; border-radius: 35px; box-shadow: 0 20px 40px rgba(0,0,0,0.1); padding: 2.5rem; }
        .selector-item { cursor: pointer; border: 2px solid #e2e8f0; border-radius: 20px; padding: 15px; text-align: center; transition: 0.2s; }
        .selector-item.active { border-color: var(--primary); background: #eff6ff; color: var(--primary); }
        .color-dot { width: 45px; height: 45px; border-radius: 50%; display: inline-block; margin: 8px; cursor: pointer; border: 3px solid white; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .color-dot.active { border-color: var(--primary); transform: scale(1.15); }
        .form-control-lg { border-radius: 15px; border: 2px solid #e2e8f0; padding: 1.2rem; font-weight: 700; }
    </style>
</head>
<body>

<div class="container py-5">
    <div class="row justify-content-center">
        <div class="col-lg-10 col-xl-8">
            <div class="main-card">
                <h2 class="fw-bold text-center mb-5"><i class="fas fa-car-side text-primary me-2"></i>NUEVO SERVICIO</h2>
                
                <div class="row g-4">
                    <div class="col-md-7">
                        <label class="fw-bold mb-2">1. MARCA Y MODELO</label>
                        <input type="text" id="AutoModelo" class="form-control form-control-lg shadow-sm mb-3" placeholder="Ej: Audi Q5">
                        
                        <label class="fw-bold mb-2">CATEGORÍA</label>
                        <div class="row g-2 mb-4">
                            <div class="col-4"><div class="selector-item active" onclick="setCat('Sedan', this)"><i class="fas fa-car d-block mb-1"></i>Sedán</div></div>
                            <div class="col-4"><div class="selector-item" onclick="setCat('SUV', this)"><i class="fas fa-truck-monster d-block mb-1"></i>SUV</div></div>
                            <div class="col-4"><div class="selector-item" onclick="setCat('Pickup', this)"><i class="fas fa-truck-pickup d-block mb-1"></i>Pickup</div></div>
                        </div>

                        <label class="fw-bold mb-2">SERVICIO</label>
                        <select id="ServicioSelect" class="form-select form-select-lg shadow-sm" onchange="actualizarPrecio()"></select>
                    </div>

                    <div class="col-md-5 text-center">
                        <label class="fw-bold mb-2">2. PLACA</label>
                        <input type="text" id="Placa" class="form-control form-control-lg text-center fs-1 mb-4" placeholder="---" maxlength="10">
                        
                        <label class="fw-bold mb-2">LAVADOR</label>
                        <select id="LavadorSelect" class="form-select form-select-lg shadow-sm mb-4"></select>

                        <label class="fw-bold mb-2">COLOR DEL AUTO</label>
                        <div class="bg-light p-3 rounded-4 border">
                            <div class="color-dot active" style="background: white;" onclick="setColor('Blanco','#ffffff', this)"></div>
                            <div class="color-dot" style="background: black;" onclick="setColor('Negro','#000000', this)"></div>
                            <div class="color-dot" style="background: grey;" onclick="setColor('Gris','#808080', this)"></div>
                            <div class="color-dot" style="background: red;" onclick="setColor('Rojo','#ef4444', this)"></div>
                        </div>
                    </div>

                    <div class="col-12 mt-5">
                        <button class="btn btn-primary w-100 py-3 rounded-4 fw-bold fs-4 shadow-lg" onclick="registrarEntrada()">
                            REGISTRAR ENTRADA <i class="fas fa-rocket ms-2"></i>
                        </button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    let config = { cat: 'Sedan', color: 'Blanco', hex: '#ffffff' };

    $(document).ready(function() {
        cargarLavadores();
        cargarServicios();
    });

    function setCat(v, el) { $(".selector-item").removeClass("active"); $(el).addClass("active"); config.cat = v; }
    function setColor(n, h, el) { $(".color-dot").removeClass("active"); $(el).addClass("active"); config.color = n; config.hex = h; }

    function cargarLavadores() {
        const sql = `SELECT u.IDU, u.Nombre FROM Usuarios u INNER JOIN Usuarios_Datos d ON u.IDU = d.IDU WHERE d.IDUg = <?php echo $IDUg; ?> AND d.Estado = 'Activo'`;
        $.post('../librerias/AJAX/Select.php', { sql: sql, db: "<?php echo $db_usuarios; ?>" }, function(r) {
            const res = JSON.parse(r);
            res.data.forEach(l => { $("#LavadorSelect").append(`<option value="${l.IDU}">${l.Nombre}</option>`); });
        });
    }

    function cargarServicios() {
        const sql = `SELECT c.sku, c.nombre, i.precio_venta FROM \`<?php echo $prefijo; ?>-Productos_Catalogo\` c INNER JOIN \`<?php echo $prefijo; ?>-Productos_Inventario\` i ON c.sku = i.sku WHERE c.tipo_item = 'servicio'`;
        $.post('../librerias/AJAX/Select.php', { sql: sql, db: "<?php echo $db_datos; ?>" }, function(r) {
            const res = JSON.parse(r);
            res.data.forEach(s => { $("#ServicioSelect").append(`<option value="${s.sku}" data-precio="${s.precio_venta}">${s.nombre} ($${s.precio_venta})</option>`); });
        });
    }

    function registrarEntrada() {
        const mod = $("#AutoModelo").val();
        const pla = $("#Placa").val();
        const washer = $("#LavadorSelect").val();
        const servSku = $("#ServicioSelect").val();
        const servNom = $("#ServicioSelect option:selected").text();
        const costo = $("#ServicioSelect option:selected").data('precio');

        if(!mod || !pla) return Swal.fire('Error', 'Faltan datos', 'error');

        const sql = `INSERT INTO \`<?php echo $prefijo; ?>-Servicios_Patio\` 
            (IDU_Washer, SKU_Servicio, Nombre_Servicio, Placa, Modelo, Categoria, Color_Nombre, Color_Hex, Costo) 
            VALUES (${washer}, '${servSku}', '${servNom}', '${pla}', '${mod}', '${config.cat}', '${config.color}', '${config.hex}', ${costo})`;

        $.post('../librerias/AJAX/Execute.php', { sql: sql, db: "<?php echo $db_datos; ?>" }, function() {
            Swal.fire('¡Éxito!', 'Vehículo registrado en patio', 'success').then(() => location.reload());
        });
    }
</script>
</body>
</html>