<?php
// 1. FORZAR CODIFICACIÓN Y SEGURIDAD
header('Content-Type: text/html; charset=utf-8');
session_start();
if (!isset($_SESSION['Acceso']) || $_SESSION['Acceso'] !== 'AccesoSiqueSi') { die("Acceso denegado."); }

// Prefijo dinámico multiusuario
$idPropietario = $_SESSION['IDUg'] ?? '1'; 
$idUsuarioLogueado = $_SESSION['IDU'] ?? '1'; 
$dbName = $_SESSION['BD'] ?? "MS_Datos"; 
$prefijoTablas = "$idPropietario-"; 
$vendedor = $_SESSION['NombreUsuario'] ?? "Técnico Receptor";

try {
    // Conexión forzada a UTF-8
    $pdo = new PDO("mysql:host=localhost;dbname=$dbName;charset=utf8", "root", "33comRxXMysql");
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // Consulta de órdenes activas
    $sql = "SELECT os.*, c.Nombre as Cliente, c.Telefono, c.Direccion, its.Marca, its.Modelo, its.Categoria, its.Serie_Placas, its.Problema_Reportado
            FROM `{$prefijoTablas}Ordenes_Servicio` os
            INNER JOIN `{$prefijoTablas}Clientes` c ON os.IDC = c.IDC
            INNER JOIN `{$prefijoTablas}Items_Servicio` its ON os.ID_Orden = its.ID_Orden
            WHERE os.Estado NOT IN ('Cancelado', 'Entregado')
            ORDER BY os.Fecha_Ingreso DESC";
    $ordenes = $pdo->query($sql)->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) { die("Error de BD: " . $e->getMessage()); }
?>

<meta charset="UTF-8">

<style>
    .hub-wrapper { width: 100%; background: #f0f2f5; min-height: 100vh; padding: 15px; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; }
    .hub-header { background: white; border-radius: 12px; padding: 15px 25px; box-shadow: 0 2px 8px rgba(0,0,0,0.05); margin-bottom: 20px; }
    
    .kanban-flex { display: flex; gap: 20px; height: calc(100vh - 150px); overflow-x: auto; }
    .kanban-column { flex: 1; min-width: 350px; background: #ebedf0; border-radius: 15px; padding: 15px; display: flex; flex-direction: column; }
    .card-list { flex: 1; overflow-y: auto; padding-right: 5px; }

    .order-card { 
        background: white; border-radius: 12px; border: none; margin-bottom: 12px; 
        box-shadow: 0 2px 5px rgba(0,0,0,0.05); cursor: pointer; border-left: 6px solid #ccc;
        transition: 0.2s;
    }
    .order-card:hover { transform: translateY(-3px); box-shadow: 0 8px 15px rgba(0,0,0,0.1); }
    
    /* Colores por estado */
    .st-Recibido { border-left-color: #6c757d; }
    .st-Diagnostico { border-left-color: #f1c40f; }
    .st-EnReparacion { border-left-color: #3498db; }
    .st-Listo { border-left-color: #2ecc71; }

    /* Drawer Lateral */
    .modal.drawer { display: none; }
    .modal.drawer .modal-dialog {
        position: fixed; margin: auto; width: 50%; height: 100%; right: -50%;
        transition: right 0.3s ease-out;
    }
    .modal.drawer.show .modal-dialog { right: 0; }
    .modal.drawer .modal-content { height: 100%; border-radius: 0; border: none; border-left: 5px solid #f26522; overflow-y: auto; }

    .data-pill { background: #f8f9fa; border-radius: 8px; padding: 12px; border: 1px solid #eee; margin-bottom: 15px; }
    .money-hub { background: #2c3e50; color: white; border-radius: 10px; padding: 15px; display: flex; justify-content: space-around; }
    .money-hub div { text-align: center; }
    .money-hub b { display: block; font-size: 1.2rem; }
    .resta-txt { color: #ff4757; }

    .timeline-v { border-left: 2px solid #e9ecef; margin-left: 20px; padding-left: 25px; position: relative; }
    .tm-item { position: relative; margin-bottom: 20px; }
    .tm-item::before { 
        content: ""; position: absolute; left: -34px; top: 5px; width: 16px; height: 16px; 
        background: #fff; border: 3px solid #f26522; border-radius: 50%; 
    }

    @media (max-width: 1100px) { .modal.drawer .modal-dialog { width: 100%; right: -100%; } }
</style>

<div class="hub-wrapper">
    <div class="hub-header d-flex justify-content-between align-items-center">
        <h4 class="m-0 font-weight-bold text-dark"><i class="feather icon-cpu text-primary mr-2"></i>Gestión Técnica</h4>
        <div class="w-50">
            <input type="text" id="k-search" class="form-control form-control-lg border-0 bg-light" placeholder="Filtrar por cliente o folio...">
        </div>
    </div>

    <div class="kanban-flex">
        <div class="kanban-column">
            <h6 class="font-weight-bold text-muted mb-3">TALLER / PROCESO <span class="badge badge-dark ml-2" id="cntW">0</span></h6>
            <div class="card-list" id="listWorkshop"></div>
        </div>
        <div class="kanban-column" style="background: #d4edda;">
            <h6 class="font-weight-bold text-success mb-3">LISTO PARA ENTREGA <span class="badge badge-success ml-2" id="cntR">0</span></h6>
            <div class="card-list" id="listReady"></div>
        </div>
    </div>
</div>

<div class="modal fade drawer" id="modalOS" tabindex="-1" role="dialog" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content shadow-lg">
            <div class="modal-header bg-dark text-white p-4">
                <div>
                    <h3 class="modal-title font-weight-bold" id="detFolio">---</h3>
                    <span class="badge badge-primary" id="detStatusBadge">---</span>
                </div>
                <button type="button" class="close text-white" data-dismiss="modal"><span>&times;</span></button>
            </div>
            <div class="modal-body p-4">
                
                <div class="money-hub mb-4 shadow-sm">
                    <div><small>PRESUPUESTO</small><b id="detTotal">$0.00</b></div>
                    <div class="text-success"><small>ANTICIPO</small><b id="detPagado">$0.00</b></div>
                    <div class="resta-txt"><small>RESTA</small><b id="detResta">$0.00</b></div>
                </div>

                <div class="row">
                    <div class="col-md-6 mb-3">
                        <div class="data-pill h-100">
                            <small class="text-muted font-weight-bold">CLIENTE</small>
                            <h5 class="font-weight-bold m-0" id="detCliNom">---</h5>
                            <p class="text-primary m-0" id="detCliTel">---</p>
                        </div>
                    </div>
                    <div class="col-md-6 mb-3">
                        <div class="data-pill h-100">
                            <small class="text-muted font-weight-bold">EQUIPO</small>
                            <h5 class="font-weight-bold m-0" id="detEquipo">---</h5>
                            <small class="text-muted d-block" id="detSerie">---</small>
                        </div>
                    </div>
                </div>

                <div class="data-pill bg-light border-danger">
                    <small class="text-danger font-weight-bold">FALLA REPORTADA</small>
                    <p class="m-0" id="detFalla">---</p>
                </div>

                <hr>

                <div class="bg-light p-3 rounded mb-5 border">
                    <h6 class="font-weight-bold mb-3"><i class="feather icon-edit-2 mr-2"></i>Actualizar Seguimiento</h6>
                    <div class="row">
                        <div class="col-md-6 mb-2">
                            <select id="updEstado" class="form-control font-weight-bold">
                                <option value="Recibido">Recibido</option>
                                <option value="Diagnostico">Diagnóstico</option>
                                <option value="En Reparacion">En Reparación</option>
                                <option value="Listo">Listo para Entrega</option>
                                <option value="Entregado">Entregado</option>
                            </select>
                        </div>
                        <div class="col-md-12 mb-3">
                            <textarea id="updNota" class="form-control" rows="2" placeholder="Escriba aquí los avances técnicos..."></textarea>
                        </div>
                        <div class="col-md-12">
                            <button class="btn btn-primary btn-block btn-lg font-weight-bold" onclick="osEngine.save()">
                                GUARDAR AVANCE
                            </button>
                        </div>
                    </div>
                </div>

                <h5 class="font-weight-bold mb-4"><i class="feather icon-clock mr-2"></i>Línea de Tiempo del Servicio</h5>
                <div id="detTimeline" class="timeline-v"></div>

            </div>
        </div>
    </div>
</div>

<?php include_once('../librerias/Modulos/Impresora.php'); ?>

<script>
// Motor de Gestión Técnica
function startOsEngine() {
    if (typeof jQuery === 'undefined') { setTimeout(startOsEngine, 100); return; }

    const osEngine = (function($) {
        const data = <?php echo json_encode($ordenes); ?>;
        const CFG = { 
            db: '<?php echo $dbName; ?>', 
            px: '<?php echo $prefijoTablas; ?>', 
            tech: '<?php echo $vendedor; ?>', 
            idu: '<?php echo $idUsuarioLogueado; ?>' 
        };
        let currentId = null;

        const api = async (f, sql) => {
            const fd = new FormData(); fd.append('sql', sql); fd.append('db', CFG.db);
            return fetch(`../librerias/AJAX/${f}`, { method: 'POST', body: fd }).then(r => r.json());
        };

        const money = n => new Intl.NumberFormat('es-MX', { style: 'currency', currency: 'MXN' }).format(n);

        return {
            init: function() {
                this.render(data);
                $('#k-search').on('keyup', (e) => {
                    const v = e.target.value.toUpperCase().trim();
                    this.render(data.filter(o => o.Folio.includes(v) || o.Cliente.toUpperCase().includes(v)));
                });
            },

            render: function(list) {
                const boxW = $('#listWorkshop'), boxR = $('#listReady');
                boxW.empty(); boxR.empty();
                let cW = 0, cR = 0;

                list.forEach(o => {
                    const cleanState = o.Estado.replace(/\s+/g, '');
                    const card = `
                        <div class="card order-card st-${cleanState} p-3" onclick="osEngine.open(${o.ID_Orden})">
                            <div class="d-flex justify-content-between mb-2 small font-weight-bold">
                                <span>${o.Folio}</span>
                                <span class="text-muted">${o.Fecha_Ingreso.split(' ')[0]}</span>
                            </div>
                            <h6 class="m-0 font-weight-bold text-dark">${o.Marca} ${o.Modelo}</h6>
                            <p class="small text-muted mb-2">${o.Cliente}</p>
                            <div class="d-flex justify-content-between align-items-center">
                                <span class="badge border py-1 px-2">${o.Estado.toUpperCase()}</span>
                                <b class="text-danger">${money(o.Total_Estimado - o.Anticipo)}</b>
                            </div>
                        </div>`;
                    if(o.Estado === 'Listo') { boxR.append(card); cR++; }
                    else { boxW.append(card); cW++; }
                });
                $('#cntW').text(cW); $('#cntR').text(cR);
            },

            open: async function(id) {
                currentId = id;
                const item = data.find(x => x.ID_Orden == id);
                
                $('#detFolio').text(item.Folio);
                $('#detStatusBadge').text(item.Estado);
                $('#detCliNom').text(item.Cliente);
                $('#detCliTel').text("📞 " + item.Telefono);
                $('#detEquipo').text(`${item.Marca} ${item.Modelo}`);
                $('#detSerie').text("S/N: " + (item.Serie_Placas || 'N/A'));
                $('#detFalla').text(item.Problema_Reportado);
                
                const total = parseFloat(item.Total_Estimado), pagado = parseFloat(item.Anticipo);
                $('#detTotal').text(money(total));
                $('#detPagado').text(money(pagado));
                $('#detResta').text(money(total - pagado));
                $('#updEstado').val(item.Estado);

                // Cargar Historial
                const h = await api('Select.php', `SELECT * FROM \`${CFG.px}Ordenes_Historial\` WHERE ID_Orden = ${id} ORDER BY Fecha_Cambio DESC`);
                const tl = $('#detTimeline'); tl.empty();
                if(h.data && h.data.length) {
                    h.data.forEach(log => {
                        tl.append(`<div class="tm-item">
                            <small class="text-muted d-block">${log.Fecha_Cambio}</small>
                            <span class="font-weight-bold text-dark">${log.Estado_Nuevo}</span>
                            <div class="bg-light p-2 rounded small mt-1 border">${log.Comentario || 'Sin notas.'}</div>
                        </div>`);
                    });
                }
                $('#modalOS').modal('show');
            },

            save: async function() {
                const estado = $('#updEstado').val();
                const nota = $('#updNota').val();
                if(!nota) return alert("Por favor, ingrese una nota de avance.");

                await api('Execute.php', `UPDATE \`${CFG.px}Ordenes_Servicio\` SET Estado = '${estado}' WHERE ID_Orden = ${currentId}`);
                await api('Execute.php', `INSERT INTO \`${CFG.px}Ordenes_Historial\` (ID_Orden, Estado_Nuevo, Comentario, ID_Usuario) VALUES (${currentId}, '${estado}', '${nota.replace(/'/g, "")}', '${CFG.idu}')`);
                
                location.reload();
            }
        };
    })(jQuery);

    window.osEngine = osEngine;
    osEngine.init();
}

startOsEngine();
</script>