<?php
session_start();
require 'config.php';
if(!isset($_SESSION["usuario"])){header("Location: login.php");exit;}

$usuario  = $_SESSION["usuario"];
$rol      = $_SESSION["rol"];
$sucursal = $_SESSION["sucursal"];

// Sucursal del usuario
$stmtSuc = $pdo->prepare("SELECT nombre,direccion,telefono FROM sucursales WHERE nombre=? LIMIT 1");
$stmtSuc->execute([$sucursal]);
$dataSuc = $stmtSuc->fetch() ?: ['nombre'=>$sucursal,'direccion'=>'—','telefono'=>'—'];

// NIP aleatorio
$nip = str_pad(rand(0,999999),6,'0',STR_PAD_LEFT);

// Siguiente folio
$folio = $pdo->query("SELECT COALESCE(MAX(id_orden_serv),0)+1 FROM ordenes_de_servicio")->fetchColumn();
$folio = str_pad($folio,6,'0',STR_PAD_LEFT);

// Fecha límite +20 días
$diasES  = ['Sunday'=>'DOMINGO','Monday'=>'LUNES','Tuesday'=>'MARTES','Wednesday'=>'MIÉRCOLES','Thursday'=>'JUEVES','Friday'=>'VIERNES','Saturday'=>'SÁBADO'];
$mesesES = [1=>'ENERO',2=>'FEBRERO',3=>'MARZO',4=>'ABRIL',5=>'MAYO',6=>'JUNIO',7=>'JULIO',8=>'AGOSTO',9=>'SEPTIEMBRE',10=>'OCTUBRE',11=>'NOVIEMBRE',12=>'DICIEMBRE'];
$limite      = time()+(20*86400);
$fecLimite   = $diasES[date('l',$limite)]." ".date('j',$limite)." DE ".$mesesES[(int)date('n',$limite)]." DEL ".date('Y',$limite)." A LAS ".date('h:i A',$limite);
$fecLimiteMySQL = date('Y-m-d H:i:s',$limite);

// ===== VALIDACION TICKET =====
$ticketInput  = trim($_POST['ticket_buscar'] ?? $_GET['ticket'] ?? '');
$ticketValido = false;
$ticketMsg    = '';
$ticketMsgType= '';
$ticketData   = null;

if($ticketInput !== ''){
    $stmtT = $pdo->prepare("SELECT * FROM anticipo_revision WHERE folio_de_ticket=? LIMIT 1");
    $stmtT->execute([$ticketInput]);
    $ticketData = $stmtT->fetch();
    if(!$ticketData){
        $ticketMsg     = 'Ticket no encontrado. Registre el pago primero en <a href="dashboard.php?vista=anticipo" style="color:var(--azul);font-weight:700;text-decoration:underline">Pago para Revisión</a>.';
        $ticketMsgType = 'error';
    } elseif(!empty($ticketData['id_orden_serv_aplicado'])){
        $ticketMsg     = 'Ticket ya utilizado en la orden <strong>OS-'.str_pad($ticketData['id_orden_serv_aplicado'],6,'0',STR_PAD_LEFT).'</strong>. Ingrese otro ticket válido.';
        $ticketMsgType = 'used';
    } else {
        $ticketValido  = true;
        $ticketMsgType = 'ok';
    }
}

// Catálogos (solo si ticket válido)
$empleados=$clientes=$marcas=$tipos=$accesorios=$sucursalesAll=[];
if($ticketValido){
    $empleados    = $pdo->query("SELECT CONCAT(primer_nombre,' ',primer_apellido) as nombre FROM alta_de_empleados WHERE STATUS <> 'RENUNCIADO' ORDER BY primer_nombre")->fetchAll();
    $clientes     = $pdo->query("SELECT id_cliente,nombre_cliente_completo,email_cliente,empresa_ref_cliente,telefono FROM clientes_tec ORDER BY nombre_cliente_completo")->fetchAll();
    $marcas       = $pdo->query("SELECT nombre_marcas FROM marcas ORDER BY nombre_marcas")->fetchAll();
    $tipos        = $pdo->query("SELECT nombre_de_equipos FROM tipos_de_equipo ORDER BY nombre_de_equipos")->fetchAll();
    $accesorios   = $pdo->query("SELECT name FROM accesorios ORDER BY name")->fetchAll();
    $sucursalesAll= $pdo->query("SELECT nombre FROM sucursales ORDER BY nombre")->fetchAll();
}

// Upload helper
function subirFoto($fileKey,$ordenId){
    if(empty($_FILES[$fileKey]['name'])) return '';
    $ext=strtolower(pathinfo($_FILES[$fileKey]['name'],PATHINFO_EXTENSION));
    if(!in_array($ext,['jpg','jpeg','png','gif','webp','heic'])) return '';
    $dir=__DIR__.'/uploads/evidencias/';
    if(!is_dir($dir)) mkdir($dir,0755,true);
    $name='ev_'.$ordenId.'_'.$fileKey.'_'.time().'.'.$ext;
    move_uploaded_file($_FILES[$fileKey]['tmp_name'],$dir.$name);
    return 'uploads/evidencias/'.$name;
}

// Procesar guardado
$msg=''; $msgType='';
if($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['guardar_orden']) && $ticketValido){
    try{
        $pdo->beginTransaction();
        $fecha_c = ($rol==='ADMINISTRADOR' && !empty($_POST['fecha_creacion'])) ? $_POST['fecha_creacion'] : date('Y-m-d H:i:s');
        $asesor     = $_POST['asesor_que_atiende'] ?? '';
        $nom_cli    = $_POST['nombre_cliente'] ?? '';
        $email_c    = $_POST['email_cliente_tec'] ?? '';
        $empresa_c  = $_POST['empresa_referencia'] ?? '';
        $tel_c      = $_POST['telefono_cliente'] ?? '';
        $instruc    = $_POST['instrucciones_cliente'] ?? '';
        $equipo_acc = $_POST['equipo_con_accesorios'] ?? 'NO';
        $referenciado= $_POST['referenciado'] ?? '';
        $firma_cli  = $_POST['firma_cliente'] ?? '';
        $nip_g      = $_POST['nip'] ?? $nip;

        $sql="INSERT INTO ordenes_de_servicio
            (fecha_creacion,asesor_que_atiende,nombre_cliente,email_cliente_tec,
             empresa_referencia,telefono_cliente,instrucciones_cliente,equipo_con_accesorios,
             creado_por,estado,nip,referenciado,sucursal,
             ticket_anticipo,feclimiterecoje,firma_cliente)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
        $pdo->prepare($sql)->execute([$fecha_c,$asesor,$nom_cli,$email_c,$empresa_c,$tel_c,
            $instruc,$equipo_acc,$usuario,'EN REVISION',$nip_g,$referenciado,$sucursal,
            $ticketInput,$fecLimiteMySQL,$firma_cli]);
        $id_orden=$pdo->lastInsertId();

        // Marcar ticket como usado
        $pdo->prepare("UPDATE anticipo_revision SET id_orden_serv_aplicado=?, estatus='USADO' WHERE folio_de_ticket=?")
            ->execute([$id_orden,$ticketInput]);

        // Fotos evidencia
        $ev1=subirFoto('evidencia_recibido_1',$id_orden);
        $ev2=subirFoto('evidencia_recibido_2',$id_orden);
        $ev3=subirFoto('evidencia_recibido_3',$id_orden);
        $ev4=subirFoto('evidencia_recibido_4',$id_orden);

        // Insertar refequipo
        $pdo->prepare("INSERT INTO refequipo
            (id_orden_serv,tipo_de_equipo,marca_de_equipo,modelo_del_equipo,
             estado_fisico_de_recepcion,numero_de_serie_del_equipo,prende_completamente,
             password,argumento_de_la_falla,solicita_respaldo,
             evidencia_recibido_1,evidencia_recibido_2,evidencia_recibido_3,evidencia_recibido_4)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)")
        ->execute([$id_orden,
            $_POST['tipo_de_equipo']??'',$_POST['marca_de_equipo']??'',
            $_POST['modelo_del_equipo']??'',$_POST['estado_fisico_de_recepcion']??'',
            $_POST['numero_de_serie_del_equipo']??'',$_POST['prende_completamente']??'NO',
            $_POST['password']??'',$_POST['argumento_de_la_falla']??'',
            $_POST['solicita_respaldo']??'NO',$ev1,$ev2,$ev3,$ev4]);

        // Accesorios
        if($equipo_acc==='SI' && !empty($_POST['acc_nombre'])){
            $stmtAcc=$pdo->prepare("INSERT INTO refaccesorios (id_orden_serv,accesorio_recibido,numero_de_serie_de_accesorio) VALUES (?,?,?)");
            foreach($_POST['acc_nombre'] as $i=>$n){
                if(!empty($n)) $stmtAcc->execute([$id_orden,$n,$_POST['acc_serie'][$i]??'']);
            }
        }
        $pdo->commit();
        // Redirigir a ver_orden con folio y NIP para imprimir
        $yr_new = date('Y');
        $fol_new = $yr_new.'-'.str_pad($id_orden,4,'0',STR_PAD_LEFT);
        header("Location: ver_orden.php?id=".$id_orden."&nuevo=1");
        exit;
    }catch(Exception $e){
        $pdo->rollBack();
        $msg="❌ Error: ".$e->getMessage();
        $msgType='error';
    }
}
?><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1">
<title>Nueva Orden — PROCEIN 2026</title>
<link href="https://fonts.googleapis.com/css2?family=Exo+2:wght@400;600;700;800&family=Inter:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{
  --azul:#1565C0;--azul2:#1E88E5;--acento:#29B6F6;
  --fondo:#EBF5FF;--blanco:#fff;--texto:#0D2A4A;--muted:#5A7FA8;
  --borde:#C5DDF9;--verde:#2E7D32;--rojo:#C62828;--sidebar-w:230px;
}
html,body{min-height:100vh;background:var(--fondo);font-family:"Inter",sans-serif;color:var(--texto)}
body{display:flex}

.sidebar{width:var(--sidebar-w);min-height:100vh;background:#0D1B30;position:fixed;left:0;top:0;bottom:0;z-index:100;box-shadow:4px 0 24px rgba(0,0,0,.25);display:flex;flex-direction:column;transition:transform .3s}
.sidebar-logo{padding:18px 16px 14px;border-bottom:1px solid rgba(41,182,246,.1);display:flex;align-items:center;gap:10px}
.sidebar-logo img{height:34px;filter:drop-shadow(0 0 6px rgba(41,182,246,.3))}
.sidebar-logo-text{font-family:"Exo 2",sans-serif;font-size:11px;font-weight:800;color:#fff;line-height:1.3}
.sidebar-logo-text span{color:var(--acento);font-size:9px;letter-spacing:2px;font-weight:600;display:block}
.sidebar-user{padding:10px 14px;background:rgba(41,182,246,.06);border-bottom:1px solid rgba(41,182,246,.08);display:flex;align-items:center;gap:10px}
.user-avatar{width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,var(--azul),var(--acento));display:flex;align-items:center;justify-content:center;font-family:"Exo 2",sans-serif;font-size:13px;font-weight:800;color:#fff;flex-shrink:0}
.user-name{font-size:11px;font-weight:600;color:#E8F2FF;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.user-role{font-size:9px;color:var(--acento);letter-spacing:1px;text-transform:uppercase;font-weight:600}
.nav{flex:1;padding:10px 0;overflow-y:auto}
.nav-label{font-family:"Exo 2",sans-serif;font-size:9px;font-weight:700;letter-spacing:2px;text-transform:uppercase;color:rgba(144,202,249,.35);padding:8px 14px 4px}
.menu-btn{width:100%;display:flex;align-items:center;gap:9px;padding:10px 14px;background:none;border:none;cursor:pointer;color:#90CAF9;font-family:"Exo 2",sans-serif;font-size:12px;font-weight:600;text-align:left;transition:background .15s}
.menu-btn:hover,.menu-btn.active{background:rgba(41,182,246,.1);color:#fff}
.menu-btn .icon{width:28px;height:28px;border-radius:7px;background:rgba(41,182,246,.1);display:flex;align-items:center;justify-content:center;font-size:12px;flex-shrink:0}
.menu-btn .arrow{margin-left:auto;font-size:10px;transition:transform .2s;color:rgba(144,202,249,.5)}
.menu-btn.open .arrow{transform:rotate(90deg)}
.submenu{max-height:0;overflow:hidden;transition:max-height .3s;background:rgba(0,0,0,.15)}
.submenu.open{max-height:200px}
.sub-item{display:flex;align-items:center;gap:8px;padding:8px 14px 8px 42px;color:#6A8BAE;font-size:12px;text-decoration:none;transition:background .15s,color .15s;border-left:2px solid transparent;margin-left:12px}
.sub-item:hover{background:rgba(41,182,246,.07);color:#C5E3FF}
.sub-item.active{color:var(--acento);border-left-color:var(--acento);background:rgba(41,182,246,.08)}
.sub-item i{font-size:10px;width:13px;text-align:center;color:var(--acento);opacity:.7}
.sidebar-footer{padding:10px 12px;border-top:1px solid rgba(41,182,246,.08)}
.logout-btn{width:100%;display:flex;align-items:center;gap:9px;padding:8px 11px;border-radius:8px;background:rgba(220,50,50,.08);border:1px solid rgba(220,50,50,.15);color:#FF7777;font-family:"Exo 2",sans-serif;font-size:11px;font-weight:600;cursor:pointer;text-decoration:none;transition:background .15s}
.logout-btn:hover{background:rgba(220,50,50,.18)}

.main{margin-left:var(--sidebar-w);flex:1;display:flex;flex-direction:column;min-height:100vh}
.topbar{background:#fff;border-bottom:1px solid #D6ECFF;padding:11px 20px;display:flex;align-items:center;gap:12px;box-shadow:0 2px 10px rgba(21,101,192,.07);position:sticky;top:0;z-index:50}
.topbar-title{font-family:"Exo 2",sans-serif;font-size:16px;font-weight:800;color:var(--azul)}
.topbar-title em{color:var(--acento);font-style:normal}
.topbar-back{display:flex;align-items:center;gap:6px;padding:7px 13px;border-radius:8px;background:#EBF5FF;border:1px solid var(--borde);color:var(--azul);font-size:12px;font-weight:600;text-decoration:none;font-family:"Exo 2",sans-serif;margin-left:auto}
.topbar-back:hover{background:#D6ECFF}
.hamburger{display:none;background:none;border:none;cursor:pointer;color:var(--azul);font-size:20px}

.banner-suc{background:linear-gradient(135deg,var(--azul) 0%,var(--azul2) 60%,var(--acento) 100%);margin:16px 20px 0;border-radius:12px;padding:14px 20px;display:flex;align-items:center;gap:16px;flex-wrap:wrap;box-shadow:0 6px 20px rgba(21,101,192,.25);color:#fff}
.suc-name{font-family:"Exo 2",sans-serif;font-size:15px;font-weight:800}
.suc-det{font-size:12px;opacity:.85;margin-top:2px}
.suc-det span{margin-right:14px}

.content{padding:16px 20px 48px;flex:1}
.msg{padding:12px 16px;border-radius:10px;margin-bottom:16px;font-size:14px;font-weight:500;display:flex;align-items:center;gap:10px}
.msg.success{background:#E8F5E9;border:1px solid #A5D6A7;color:#2E7D32}
.msg.error{background:#FFEBEE;border:1px solid #EF9A9A;color:#C62828}

/* TICKET VALIDATION */
.ticket-box{background:#fff;border-radius:14px;border:2px solid var(--acento);padding:28px;margin-bottom:20px;box-shadow:0 4px 20px rgba(41,182,246,.15)}
.ticket-box h3{font-family:"Exo 2",sans-serif;font-size:16px;font-weight:800;color:var(--azul);margin-bottom:6px}
.ticket-box p{font-size:13px;color:var(--muted);margin-bottom:18px}
.ticket-input-row{display:flex;gap:10px;flex-wrap:wrap}
.ticket-input{flex:1;min-width:180px;padding:12px 16px;background:#F5FAFF;border:2px solid var(--borde);border-radius:10px;font-size:18px;font-family:"Exo 2",sans-serif;font-weight:700;letter-spacing:3px;color:var(--texto);outline:none;transition:border-color .2s;text-align:center}
.ticket-input:focus{border-color:var(--azul2);background:#fff}
.btn-validar{padding:12px 24px;background:linear-gradient(135deg,var(--azul),var(--acento));border:none;border-radius:10px;color:#fff;font-family:"Exo 2",sans-serif;font-size:14px;font-weight:700;letter-spacing:1px;cursor:pointer;white-space:nowrap;box-shadow:0 4px 14px rgba(21,101,192,.3)}
.btn-validar:hover{transform:translateY(-1px)}

.ticket-ok{background:#E8F5E9;border:2px solid #A5D6A7;border-radius:12px;padding:14px 18px;display:flex;align-items:center;gap:12px;margin-bottom:20px}
.ticket-ok i{font-size:24px;color:#2E7D32;flex-shrink:0}
.ticket-ok strong{font-family:"Exo 2",sans-serif;font-size:14px;color:#1B5E20;display:block}
.ticket-ok span{font-size:12px;color:#388E3C}
.ticket-err{background:#FFEBEE;border:2px solid #FFCDD2;border-radius:12px;padding:14px 18px;display:flex;align-items:flex-start;gap:12px;margin-top:14px}
.ticket-err i{font-size:20px;color:#C62828;flex-shrink:0;margin-top:2px}
.ticket-used{background:#FFF8E1;border:2px solid #FFE082;border-radius:12px;padding:14px 18px;display:flex;align-items:flex-start;gap:12px;margin-top:14px}
.ticket-used i{font-size:20px;color:#F57F17;flex-shrink:0;margin-top:2px}

.section{background:#fff;border-radius:14px;border:1px solid var(--borde);margin-bottom:16px;box-shadow:0 2px 10px rgba(21,101,192,.06)}
.section.hidden-section{display:none}
.section-header{padding:12px 18px;background:linear-gradient(90deg,#EBF5FF,#F5FAFF);border-bottom:1px solid var(--borde);display:flex;align-items:center;gap:10px}
.section-num{width:26px;height:26px;border-radius:50%;background:linear-gradient(135deg,var(--azul),var(--acento));color:#fff;font-family:"Exo 2",sans-serif;font-size:11px;font-weight:800;display:flex;align-items:center;justify-content:center;flex-shrink:0}
.section-title{font-family:"Exo 2",sans-serif;font-size:13px;font-weight:700;color:var(--azul)}
.section-body{padding:16px 18px}

.form-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:14px}
.form-grid.col2{grid-template-columns:1fr 1fr}
.form-grid.col3{grid-template-columns:1fr 1fr 1fr}
.form-group{display:flex;flex-direction:column;gap:5px}
.form-group.full{grid-column:1/-1}
.form-group label{font-family:"Exo 2",sans-serif;font-size:9px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:var(--muted)}
.form-group label .req{color:var(--rojo)}

input[type=text],input[type=email],input[type=datetime-local],select,textarea{padding:10px 12px;background:#F5FAFF;border:1.5px solid var(--borde);border-radius:8px;color:var(--texto);font-size:14px;font-family:"Inter",sans-serif;outline:none;transition:border-color .2s,box-shadow .2s;width:100%;-webkit-appearance:none}
input[type=text]:focus,input[type=email]:focus,input[type=datetime-local]:focus,select:focus,textarea:focus{border-color:var(--azul2);background:#fff;box-shadow:0 0 0 3px rgba(30,136,229,.1)}
input[readonly]{background:#EEF4FB;color:#7A9ABE;cursor:default}
textarea{resize:vertical;min-height:76px}
select{background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8'%3E%3Cpath d='M1 1l5 5 5-5' stroke='%235A7FA8' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 11px center;padding-right:30px;background-color:#F5FAFF}

.field-readonly{padding:10px 12px;background:#EEF4FB;border:1.5px solid #D6ECFF;border-radius:8px;color:#5A7FA8;font-size:13px;min-height:42px;display:flex;align-items:center}
.badge-folio{display:inline-flex;align-items:center;gap:8px;background:linear-gradient(135deg,var(--azul),var(--azul2));color:#fff;border-radius:8px;padding:8px 12px;font-family:"Exo 2",sans-serif;font-size:14px;font-weight:800;letter-spacing:1px;box-shadow:0 4px 12px rgba(21,101,192,.25)}
.badge-nip{display:inline-flex;align-items:center;gap:8px;background:linear-gradient(135deg,#1B5E20,#2E7D32);color:#fff;border-radius:8px;padding:8px 12px;font-family:"Exo 2",sans-serif;font-size:15px;font-weight:800;letter-spacing:3px;box-shadow:0 4px 12px rgba(46,125,50,.25)}

.foto-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px}
.foto-item{position:relative}
.foto-label{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px;padding:16px 10px;background:#F5FAFF;border:2px dashed var(--borde);border-radius:10px;cursor:pointer;transition:all .2s;min-height:120px;text-align:center}
.foto-label:hover{border-color:var(--azul2);background:#EBF5FF}
.foto-label i{font-size:28px;color:var(--acento)}
.foto-label span{font-size:11px;color:var(--muted);font-family:"Exo 2",sans-serif;font-weight:600}
.foto-label small{font-size:9px;color:#A0B4CC}
.foto-label input[type=file]{display:none}
.foto-preview{display:none;width:100%;height:120px;object-fit:cover;border-radius:10px;border:2px solid var(--acento)}
.foto-item.has-photo .foto-label{display:none}
.foto-item.has-photo .foto-preview{display:block}
.foto-remove{display:none;position:absolute;top:6px;right:6px;width:26px;height:26px;border-radius:50%;background:#C62828;border:none;color:#fff;font-size:11px;cursor:pointer;align-items:center;justify-content:center;z-index:2}
.foto-item.has-photo .foto-remove{display:flex}

.acc-row{display:grid;grid-template-columns:1fr 1fr auto;gap:10px;align-items:end;margin-bottom:8px}
.btn-add-acc{display:inline-flex;align-items:center;gap:6px;padding:8px 14px;background:#EBF5FF;border:1.5px dashed var(--acento);border-radius:8px;color:var(--azul2);font-size:12px;font-weight:600;cursor:pointer;font-family:"Exo 2",sans-serif;transition:background .15s}
.btn-del{width:34px;height:34px;border-radius:7px;background:#FFEBEE;border:1px solid #FFCDD2;color:#C62828;cursor:pointer;display:flex;align-items:center;justify-content:center;font-size:13px;flex-shrink:0}
.toggle-group{display:flex;gap:8px}
.toggle-opt{flex:1;padding:9px;border:1.5px solid var(--borde);border-radius:8px;text-align:center;cursor:pointer;font-family:"Exo 2",sans-serif;font-size:12px;font-weight:700;color:var(--muted);transition:all .2s;user-select:none}
.toggle-opt.selected-si{border-color:#2E7D32;background:#E8F5E9;color:#2E7D32}
.toggle-opt.selected-no{border-color:#C62828;background:#FFEBEE;color:#C62828}
#seccionAccesorios{display:none}
.fecha-limite-display{background:linear-gradient(135deg,#E3F2FD,#EBF5FF);border:1.5px solid var(--acento);border-radius:10px;padding:12px 16px;font-family:"Exo 2",sans-serif;font-size:13px;font-weight:700;color:var(--azul);text-align:center}

/* FIRMA — touch habilitado */
.canvas-wrap{position:relative;background:#F5FAFF;border:1.5px solid var(--borde);border-radius:10px}
canvas#firmaCanvas{display:block;width:100%;cursor:crosshair;touch-action:none}
.canvas-toolbar{display:flex;gap:8px;padding:8px 10px;background:#EBF5FF;border-top:1px solid var(--borde);flex-wrap:wrap}
.btn-canvas{padding:7px 12px;border-radius:6px;border:1px solid var(--borde);background:#fff;color:var(--azul);font-size:12px;font-weight:600;cursor:pointer;font-family:"Exo 2",sans-serif}
.btn-canvas.danger{border-color:#FFCDD2;color:#C62828;background:#FFF0F0}

.alert-seleccione{background:linear-gradient(135deg,#E3F2FD,#EBF5FF);border:2px solid var(--acento);border-radius:12px;padding:20px;text-align:center;margin-bottom:16px}
.alert-seleccione i{font-size:32px;color:var(--acento);display:block;margin-bottom:8px}
.alert-seleccione p{font-family:"Exo 2",sans-serif;font-size:14px;font-weight:700;color:var(--azul)}
.alert-seleccione small{font-size:12px;color:var(--muted)}

.submit-bar{display:flex;align-items:center;gap:12px;flex-wrap:wrap;padding:16px 0 0}
.btn-submit{display:inline-flex;align-items:center;gap:9px;padding:13px 28px;background:linear-gradient(135deg,var(--azul),var(--azul2),var(--acento));background-size:200%;border:none;border-radius:10px;color:#fff;font-family:"Exo 2",sans-serif;font-size:14px;font-weight:700;letter-spacing:1.5px;cursor:pointer;transition:background-position .4s,transform .15s,box-shadow .2s;box-shadow:0 4px 20px rgba(21,101,192,.3)}
.btn-submit:hover{background-position:100%;transform:translateY(-2px)}
.btn-cancel{display:inline-flex;align-items:center;gap:8px;padding:12px 20px;border-radius:10px;border:1.5px solid var(--borde);background:#fff;color:var(--muted);font-family:"Exo 2",sans-serif;font-size:13px;font-weight:600;text-decoration:none}

@media(max-width:900px){.form-grid.col3{grid-template-columns:1fr 1fr}}
@media(max-width:640px){
  .form-grid.col2,.form-grid.col3{grid-template-columns:1fr}
  .acc-row{grid-template-columns:1fr auto}
  .foto-grid{grid-template-columns:1fr 1fr}
  .content{padding:12px 12px 48px}
  .banner-suc{margin:12px 12px 0}
  .section-body{padding:14px}
  .ticket-input-row{flex-direction:column}
  .btn-validar{width:100%}
}
@media(max-width:768px){
  .sidebar{transform:translateX(-100%)}
  .sidebar.open{transform:translateX(0)}
  .main{margin-left:0}
  .hamburger{display:block}
}
.overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:99}
@media(max-width:768px){.overlay{display:block;opacity:0;pointer-events:none;transition:opacity .3s}.overlay.open{opacity:1;pointer-events:all}}
</style>
</head>
<body>
<div class="overlay" id="overlay" onclick="closeSidebar()"></div>

<aside class="sidebar" id="sidebar">
  <div class="sidebar-logo">
    <img src="data:image/jpeg;base64,[encoded data, 19656 characters]" alt="VANTECC">
    <div class="sidebar-logo-text">PROCEIN 2026 PRO<span>CompuJuárez · Vantecc</span></div>
  </div>
  <div class="sidebar-user">
    <div class="user-avatar"><?= strtoupper(substr($usuario,0,1)) ?></div>
    <div style="min-width:0">
      <div class="user-name"><?= htmlspecialchars($usuario) ?></div>
      <div class="user-role"><?= htmlspecialchars($rol) ?></div>
    </div>
  </div>
  <nav class="nav">
    <div class="nav-label">Módulos</div>
    <div>
      <button class="menu-btn open active" onclick="toggleMenu(this)">
        <span class="icon"><i class="fas fa-laptop-code"></i></span>
        Servicios Técnicos
        <i class="fas fa-chevron-right arrow"></i>
      </button>
      <div class="submenu open">
        <a href="dashboard.php?vista=ordenes" class="sub-item active"><i class="fas fa-file-alt"></i> Órdenes de Servicio</a>
        <a href="dashboard.php?vista=anticipo" class="sub-item"><i class="fas fa-dollar-sign"></i> Registrar Anticipo</a>
        <a href="dashboard.php?vista=clientes" class="sub-item"><i class="fas fa-users"></i> Clientes</a>
      </div>
    </div>
  </nav>
  <div class="sidebar-footer">
    <a href="logout.php" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Cerrar Sesión</a>
  </div>
</aside>

<div class="main">
  <div class="topbar">
    <button class="hamburger" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
    <div class="topbar-title">Nueva Orden de <em>Servicio</em></div>
    <a href="dashboard.php?vista=ordenes" class="topbar-back"><i class="fas fa-arrow-left"></i> Volver</a>
  </div>

  <div class="banner-suc">
    <div><i class="fas fa-store" style="font-size:24px;opacity:.8"></i></div>
    <div>
      <div class="suc-name"><?= htmlspecialchars($dataSuc['nombre']) ?></div>
      <div class="suc-det">
        <span><i class="fas fa-map-marker-alt"></i> <?= htmlspecialchars($dataSuc['direccion']) ?></span>
        <span><i class="fas fa-phone"></i> <?= htmlspecialchars($dataSuc['telefono']) ?></span>
      </div>
    </div>
  </div>

  <div class="content">
    <?php if($msg): ?><div class="msg <?= $msgType ?>"><?= htmlspecialchars($msg) ?></div><?php endif; ?>

    <!-- ===== PASO 0: VALIDAR TICKET ===== -->
    <!-- ===== PASO 0: VALIDAR TICKET ===== -->
    <div style="background:#fff;border-radius:16px;border:1px solid var(--borde);margin-bottom:20px;overflow:hidden;box-shadow:0 4px 20px rgba(21,101,192,.1)">
      <div style="background:linear-gradient(135deg,#1565C0 0%,#1E88E5 60%,#29B6F6 100%);padding:16px 22px;display:flex;align-items:center;gap:14px;color:#fff">
        <div style="width:44px;height:44px;border-radius:12px;background:rgba(255,255,255,.15);display:flex;align-items:center;justify-content:center;font-size:20px;flex-shrink:0"><i class="fas fa-ticket-alt"></i></div>
        <div>
          <div style="font-family:'Exo 2',sans-serif;font-size:15px;font-weight:800;margin-bottom:2px">Paso 1 — Validar Ticket de Pago</div>
          <div style="font-size:12px;opacity:.85">Ingrese el folio del anticipo para habilitar la orden de servicio</div>
        </div>
      </div>
      <div style="padding:22px 24px">
        <form method="POST" id="formTicket">
          <input type="hidden" name="ticket_buscar" id="hidTicketBuscar" value="<?= htmlspecialchars($ticketInput) ?>">
          <div style="display:flex;gap:10px;flex-wrap:wrap">
            <input type="text" id="ticketField"
                   value="<?= htmlspecialchars($ticketInput) ?>"
                   placeholder="Folio del ticket Ej. 123456"
                   maxlength="20"
                   <?= $ticketValido ? 'readonly' : '' ?>
                   oninput="this.value=this.value.replace(/[^0-9]/g,'')"
                   style="flex:1;min-width:180px;padding:13px 18px;background:#F0F8FF;border:2px solid var(--borde);border-radius:10px;font-size:20px;font-family:'Exo 2',sans-serif;font-weight:700;letter-spacing:3px;color:var(--azul);outline:none;transition:border-color .2s;text-align:center">
            <?php if(!$ticketValido): ?>
            <button type="button" onclick="validarTicket()"
                    style="padding:13px 24px;background:linear-gradient(135deg,#1565C0,#29B6F6);border:none;border-radius:10px;color:#fff;font-family:'Exo 2',sans-serif;font-size:14px;font-weight:700;letter-spacing:1px;cursor:pointer;white-space:nowrap;box-shadow:0 4px 14px rgba(21,101,192,.3)">
              <i class="fas fa-search"></i> Validar Ticket
            </button>
            <?php else: ?>
            <button type="button" onclick="cambiarTicket()"
                    style="padding:13px 20px;background:none;border:1.5px solid var(--borde);border-radius:10px;color:var(--muted);font-family:'Exo 2',sans-serif;font-size:13px;font-weight:600;cursor:pointer;white-space:nowrap">
              <i class="fas fa-exchange-alt"></i> Cambiar
            </button>
            <?php endif; ?>
          </div>

          <?php if($ticketValido): ?>
          <div style="display:flex;align-items:flex-start;gap:12px;margin-top:14px;background:#E8F5E9;border:1.5px solid #A5D6A7;border-radius:12px;padding:14px 16px">
            <i class="fas fa-check-circle" style="font-size:22px;color:#2E7D32;flex-shrink:0;margin-top:1px"></i>
            <div>
              <div style="font-family:'Exo 2',sans-serif;font-size:13px;font-weight:800;color:#1B5E20;margin-bottom:6px">Ticket #<?= htmlspecialchars($ticketInput) ?> disponible</div>
              <div style="display:flex;gap:8px;flex-wrap:wrap">
                <span style="display:inline-flex;align-items:center;gap:5px;background:rgba(255,255,255,.8);border:1px solid rgba(0,0,0,.07);border-radius:20px;padding:3px 10px;font-size:11px;font-weight:600"><i class="fas fa-dollar-sign" style="color:#1E88E5;font-size:10px"></i> $<?= number_format((float)($ticketData['total_pagado']??0)) ?></span>
                <span style="display:inline-flex;align-items:center;gap:5px;background:rgba(255,255,255,.8);border:1px solid rgba(0,0,0,.07);border-radius:20px;padding:3px 10px;font-size:11px;font-weight:600"><i class="fas fa-store" style="color:#1E88E5;font-size:10px"></i> <?= htmlspecialchars($ticketData['sucursal']??'—') ?></span>
                <span style="display:inline-flex;align-items:center;gap:5px;background:rgba(255,255,255,.8);border:1px solid rgba(0,0,0,.07);border-radius:20px;padding:3px 10px;font-size:11px;font-weight:600"><i class="fas fa-user" style="color:#1E88E5;font-size:10px"></i> <?= htmlspecialchars($ticketData['creado_por']??'—') ?></span>
              </div>
            </div>
          </div>
          <?php elseif($ticketMsgType==='error'): ?>
          <div style="display:flex;align-items:flex-start;gap:12px;margin-top:14px;background:#FFEBEE;border:1.5px solid #FFCDD2;border-radius:12px;padding:14px 16px">
            <i class="fas fa-times-circle" style="font-size:20px;color:#C62828;flex-shrink:0;margin-top:1px"></i>
            <div>
              <div style="font-family:'Exo 2',sans-serif;font-size:13px;font-weight:800;color:#B71C1C;margin-bottom:3px">Ticket no encontrado</div>
              <div style="font-size:12px;color:#5A7FA8">Registre el pago en <a href="dashboard.php?vista=anticipo" style="color:#1565C0;font-weight:700">Pago para Revisión</a> antes de iniciar la orden.</div>
            </div>
          </div>
          <?php elseif($ticketMsgType==='used'): ?>
          <div style="display:flex;align-items:flex-start;gap:12px;margin-top:14px;background:#FFF8E1;border:1.5px solid #FFE082;border-radius:12px;padding:14px 16px">
            <i class="fas fa-exclamation-triangle" style="font-size:20px;color:#F57F17;flex-shrink:0;margin-top:1px"></i>
            <div>
              <div style="font-family:'Exo 2',sans-serif;font-size:13px;font-weight:800;color:#E65100;margin-bottom:3px">Ticket ya utilizado</div>
              <div style="font-size:12px;color:#5A7FA8"><?= $ticketMsg ?></div>
            </div>
          </div>
          <?php endif; ?>

        </form>
      </div>
    </div>
    <?php if($ticketValido): ?>
    <!-- ===== FORMULARIO COMPLETO ===== -->
    <form method="POST" id="formOrden" enctype="multipart/form-data">
    <input type="hidden" name="guardar_orden" value="1">
    <input type="hidden" name="ticket_buscar" value="<?= htmlspecialchars($ticketInput) ?>">
    <input type="hidden" name="firma_cliente" id="firmaData">
    <input type="hidden" name="nip" value="<?= $nip ?>">

    <!-- SEC 1: CLIENTE -->
    <div class="section">
      <div class="section-header">
        <div class="section-num">1</div>
        <div class="section-title"><i class="fas fa-user" style="margin-right:6px;color:var(--acento)"></i>Datos del Cliente</div>
      </div>
      <div class="section-body">
        <div class="form-grid col2">
          <div class="form-group">
            <label>Nombre del Cliente <span class="req">*</span></label>
            <div style="display:flex;gap:8px">
              <select name="nombre_cliente" id="selCliente" required onchange="cargarCliente();mostrarSecciones()" style="flex:1">
                <option value="">— Seleccionar cliente —</option>
                <?php foreach($clientes as $cli): ?>
                <option value="<?= htmlspecialchars($cli['nombre_cliente_completo']) ?>"
                        data-email="<?= htmlspecialchars($cli['email_cliente'] ?? '') ?>"
                        data-empresa="<?= htmlspecialchars($cli['empresa_ref_cliente'] ?? '') ?>"
                        data-tel="<?= htmlspecialchars($cli['telefono'] ?? '') ?>">
                  <?= htmlspecialchars($cli['nombre_cliente_completo']) ?>
                </option>
                <?php endforeach; ?>
              </select>
              <a href="nuevo_cliente.php?ret=nueva_orden.php" title="Nuevo cliente" style="display:flex;align-items:center;padding:0 11px;background:linear-gradient(135deg,var(--azul),var(--acento));border-radius:8px;color:#fff;text-decoration:none;font-size:15px;flex-shrink:0"><i class="fas fa-plus"></i></a>
            </div>
          </div>
          <div class="form-group">
            <label>Email</label>
            <div class="field-readonly" id="dispEmail"><i class="fas fa-envelope" style="margin-right:8px;color:var(--acento);opacity:.5"></i><span>—</span></div>
            <input type="hidden" name="email_cliente_tec" id="hidEmail">
          </div>
        </div>
        <div class="form-grid col2" style="margin-top:12px">
          <div class="form-group">
            <label>Empresa / Referencia</label>
            <div class="field-readonly" id="dispEmpresa"><i class="fas fa-building" style="margin-right:8px;color:var(--acento);opacity:.5"></i><span>—</span></div>
            <input type="hidden" name="empresa_referencia" id="hidEmpresa">
          </div>
          <div class="form-group">
            <label>Teléfono</label>
            <div class="field-readonly" id="dispTel"><i class="fas fa-phone" style="margin-right:8px;color:var(--acento);opacity:.5"></i><span>—</span></div>
            <input type="hidden" name="telefono_cliente" id="hidTel">
          </div>
        </div>
      </div>
    </div>

    <div id="alertaCliente" class="alert-seleccione">
      <i class="fas fa-hand-pointer"></i>
      <p>Selecciona primero al cliente</p>
      <small>El resto del formulario se habilitará una vez seleccionado</small>
    </div>

    <!-- SEC 2: IDENTIFICACIÓN -->
    <div class="section hidden-section" id="sec2">
      <div class="section-header"><div class="section-num">2</div><div class="section-title"><i class="fas fa-hashtag" style="margin-right:6px;color:var(--acento)"></i>Identificación de la Orden</div></div>
      <div class="section-body">
        <div class="form-grid col3">
          <div class="form-group">
            <label>Folio</label>
            <div class="badge-folio"><i class="fas fa-barcode"></i> OS-<?= htmlspecialchars($folio) ?></div>
          </div>
          <div class="form-group">
            <label>Fecha <?= $rol==='ADMINISTRADOR'?'✎':'' ?></label>
            <?php if($rol==='ADMINISTRADOR'): ?>
              <input type="datetime-local" name="fecha_creacion" value="<?= date('Y-m-d\TH:i') ?>">
            <?php else: ?>
              <div class="field-readonly"><i class="fas fa-clock" style="margin-right:8px;color:var(--acento)"></i><?= date('d/m/Y H:i') ?></div>
              <input type="hidden" name="fecha_creacion" value="<?= date('Y-m-d H:i:s') ?>">
            <?php endif; ?>
          </div>
          <div class="form-group">
            <label>NIP Cliente</label>
            <div class="badge-nip"><i class="fas fa-shield-alt"></i> <?= $nip ?></div>
          </div>
        </div>
      </div>
    </div>

    <!-- SEC 3: ASESOR -->
    <div class="section hidden-section" id="sec3">
      <div class="section-header"><div class="section-num">3</div><div class="section-title"><i class="fas fa-user-tie" style="margin-right:6px;color:var(--acento)"></i>Asesor y Responsable</div></div>
      <div class="section-body">
        <div class="form-grid col2">
          <div class="form-group">
            <label>Asesor que atiende <span class="req">*</span></label>
            <select name="asesor_que_atiende" required>
              <option value="">— Seleccionar —</option>
              <?php foreach($empleados as $emp): ?>
              <option value="<?= htmlspecialchars($emp['nombre']) ?>"><?= htmlspecialchars($emp['nombre']) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label>Creado por</label>
            <div class="field-readonly"><i class="fas fa-user" style="margin-right:8px;color:var(--acento)"></i><?= htmlspecialchars($usuario) ?></div>
            <input type="hidden" name="creado_por" value="<?= htmlspecialchars($usuario) ?>">
          </div>
        </div>
        <div class="form-grid col2" style="margin-top:12px">
          <div class="form-group">
            <label>Estado inicial</label>
            <div class="field-readonly" style="color:#1B5E20;background:#E8F5E9;border-color:#A5D6A7"><i class="fas fa-circle" style="font-size:8px;margin-right:8px"></i>EN REVISION</div>
            <input type="hidden" name="estado" value="EN REVISION">
          </div>
        </div>
      </div>
    </div>

    <!-- SEC 4: EQUIPO -->
    <div class="section hidden-section" id="sec4">
      <div class="section-header"><div class="section-num">4</div><div class="section-title"><i class="fas fa-laptop" style="margin-right:6px;color:var(--acento)"></i>Equipo Recibido</div></div>
      <div class="section-body">
        <div class="form-grid col3">
          <div class="form-group">
            <label>Tipo de Equipo <span class="req">*</span></label>
            <select name="tipo_de_equipo" required>
              <option value="">— Seleccionar —</option>
              <?php foreach($tipos as $t): ?><option value="<?= htmlspecialchars($t['nombre_de_equipos']) ?>"><?= htmlspecialchars($t['nombre_de_equipos']) ?></option><?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label>Marca <span class="req">*</span></label>
            <select name="marca_de_equipo" required>
              <option value="">— Seleccionar —</option>
              <?php foreach($marcas as $m): ?><option value="<?= htmlspecialchars($m['nombre_marcas']) ?>"><?= htmlspecialchars($m['nombre_marcas']) ?></option><?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label>Modelo</label>
            <input type="text" name="modelo_del_equipo" placeholder="Ej. Inspiron 15">
          </div>
        </div>
        <div class="form-grid col3" style="margin-top:12px">
          <div class="form-group"><label>Número de Serie</label><input type="text" name="numero_de_serie_del_equipo" placeholder="S/N del equipo"></div>
          <div class="form-group"><label>Estado Físico</label><input type="text" name="estado_fisico_de_recepcion" placeholder="Ej. Rayado leve"></div>
          <div class="form-group">
            <label>¿Prende completamente?</label>
            <select name="prende_completamente"><option value="SI">SÍ</option><option value="NO">NO</option><option value="PARCIAL">PARCIAL</option></select>
          </div>
        </div>
        <div class="form-grid col2" style="margin-top:12px">
          <div class="form-group"><label>Password / Contraseña</label><input type="text" name="password" placeholder="Patrón o contraseña"></div>
          <div class="form-group">
            <label>¿Solicita respaldo?</label>
            <select name="solicita_respaldo"><option value="NO">NO</option><option value="SI">SÍ</option></select>
          </div>
        </div>
        <div class="form-group full" style="margin-top:12px">
          <label>Argumento de la Falla <span class="req">*</span></label>
          <textarea name="argumento_de_la_falla" placeholder="Describa el problema reportado..." required></textarea>
        </div>
        <div style="margin-top:16px">
          <div style="font-family:'Exo 2',sans-serif;font-size:10px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:var(--muted);margin-bottom:10px"><i class="fas fa-camera" style="margin-right:6px;color:var(--acento)"></i>Evidencia Fotográfica</div>
          <div class="foto-grid">
            <?php for($f=1;$f<=4;$f++): ?>
            <div class="foto-item" id="fotoItem<?= $f ?>">
              <label class="foto-label">
                <i class="fas fa-camera"></i>
                <span>Foto <?= $f ?></span>
                <small>Toca para capturar</small>
                <input type="file" name="evidencia_recibido_<?= $f ?>" accept="image/*" capture="environment" onchange="previewFoto(this,<?= $f ?>)">
              </label>
              <img class="foto-preview" id="fotoPreview<?= $f ?>" src="" alt="Evidencia <?= $f ?>">
              <button type="button" class="foto-remove" onclick="quitarFoto(<?= $f ?>)"><i class="fas fa-times"></i></button>
            </div>
            <?php endfor; ?>
          </div>
        </div>
      </div>
    </div>

    <!-- SEC 5: INSTRUCCIONES Y ACCESORIOS -->
    <div class="section hidden-section" id="sec5">
      <div class="section-header"><div class="section-num">5</div><div class="section-title"><i class="fas fa-clipboard-list" style="margin-right:6px;color:var(--acento)"></i>Instrucciones y Accesorios</div></div>
      <div class="section-body">
        <div class="form-group" style="margin-bottom:14px">
          <label>Instrucciones del Cliente</label>
          <textarea name="instrucciones_cliente" placeholder="Instrucciones especiales..."></textarea>
        </div>
        <div class="form-group" style="margin-bottom:10px">
          <label>¿Equipo trae accesorios?</label>
          <div class="toggle-group">
            <div class="toggle-opt" id="togSI" onclick="toggleAccesorios('SI')"><i class="fas fa-check-circle" style="margin-right:5px"></i>SÍ</div>
            <div class="toggle-opt selected-no" id="togNO" onclick="toggleAccesorios('NO')"><i class="fas fa-times-circle" style="margin-right:5px"></i>NO</div>
          </div>
          <input type="hidden" name="equipo_con_accesorios" id="hidEquipoAcc" value="NO">
        </div>
        <div id="seccionAccesorios">
          <div style="background:#F0F8FF;border:1px solid var(--borde);border-radius:10px;padding:14px;margin-top:8px">
            <div style="font-family:'Exo 2',sans-serif;font-size:11px;font-weight:700;color:var(--azul);margin-bottom:10px"><i class="fas fa-boxes" style="margin-right:6px;color:var(--acento)"></i>ACCESORIOS RECIBIDOS</div>
            <div id="listaAccesorios"></div>
            <button type="button" class="btn-add-acc" onclick="agregarAccesorio()"><i class="fas fa-plus-circle"></i> Agregar accesorio</button>
          </div>
        </div>
      </div>
    </div>

    <!-- SEC 6: SUCURSAL -->
    <div class="section hidden-section" id="sec6">
      <div class="section-header"><div class="section-num">6</div><div class="section-title"><i class="fas fa-store" style="margin-right:6px;color:var(--acento)"></i>Sucursal y Referencias</div></div>
      <div class="section-body">
        <div class="form-grid col3">
          <div class="form-group">
            <label>Sucursal</label>
            <div class="field-readonly"><i class="fas fa-store" style="margin-right:8px;color:var(--acento)"></i><?= htmlspecialchars($sucursal) ?></div>
            <input type="hidden" name="sucursal" value="<?= htmlspecialchars($sucursal) ?>">
          </div>
          <div class="form-group">
            <label>Referenciado</label>
            <select name="referenciado">
              <option value="">— Seleccionar —</option>
              <?php foreach($sucursalesAll as $s): ?><option value="<?= htmlspecialchars($s['nombre']) ?>"><?= htmlspecialchars($s['nombre']) ?></option><?php endforeach; ?>
            </select>
          </div>
          <div class="form-group">
            <label>Ticket Anticipo</label>
            <div class="field-readonly"><i class="fas fa-ticket-alt" style="margin-right:8px;color:var(--acento)"></i>#<?= htmlspecialchars($ticketInput) ?></div>
            <input type="hidden" name="ticket_anticipo" value="<?= htmlspecialchars($ticketInput) ?>">
          </div>
        </div>
        <div class="form-grid col2" style="margin-top:12px">
          <div class="form-group">
            <label>Dirección Sucursal</label>
            <div class="field-readonly"><i class="fas fa-map-marker-alt" style="margin-right:8px;color:var(--acento)"></i><?= htmlspecialchars($dataSuc['direccion']) ?></div>
            <input type="hidden" name="direccionsucursal" value="<?= htmlspecialchars($dataSuc['direccion']) ?>">
          </div>
          <div class="form-group">
            <label>Teléfono Sucursal</label>
            <div class="field-readonly"><i class="fas fa-phone" style="margin-right:8px;color:var(--acento)"></i><?= htmlspecialchars($dataSuc['telefono']) ?></div>
            <input type="hidden" name="telefonosucursal" value="<?= htmlspecialchars($dataSuc['telefono']) ?>">
          </div>
        </div>
        <div class="form-group full" style="margin-top:12px">
          <label>Fecha Límite de Recojo</label>
          <div class="fecha-limite-display"><i class="fas fa-calendar-alt" style="margin-right:10px;color:var(--azul2)"></i><?= htmlspecialchars($fecLimite) ?></div>
          <input type="hidden" name="feclimiterecoje" value="<?= htmlspecialchars($fecLimiteMySQL) ?>">
        </div>
      </div>
    </div>

    <!-- SEC 7: FIRMA -->
    <div class="section hidden-section" id="sec7">
      <div class="section-header"><div class="section-num">7</div><div class="section-title"><i class="fas fa-signature" style="margin-right:6px;color:var(--acento)"></i>Firma de Aceptación</div></div>
      <div class="section-body">
        <p style="font-size:13px;color:var(--muted);margin-bottom:12px">El cliente firma confirmando la entrega del equipo y aceptación de términos.</p>
        <div class="canvas-wrap">
          <canvas id="firmaCanvas" height="200"></canvas>
          <div class="canvas-toolbar">
            <button type="button" class="btn-canvas" onclick="cambiarColor('#0057B8')"><i class="fas fa-pen" style="color:#0057B8"></i> Azul</button>
            <button type="button" class="btn-canvas" onclick="cambiarColor('#000000')"><i class="fas fa-pen"></i> Negro</button>
            <button type="button" class="btn-canvas danger" onclick="limpiarFirma()"><i class="fas fa-eraser"></i> Limpiar</button>
          </div>
        </div>
      </div>
    </div>

    <div class="submit-bar hidden-section" id="secSubmit">
      <button type="submit" class="btn-submit"><i class="fas fa-save"></i> Registrar Orden de Servicio</button>
      <a href="dashboard.php?vista=ordenes" class="btn-cancel"><i class="fas fa-times"></i> Cancelar</a>
    </div>
    </form>

    <?php else: ?>
    <!-- Sin ticket válido — bloquear todo -->
    <div style="background:#fff;border-radius:14px;border:2px dashed var(--borde);padding:40px;text-align:center;color:var(--muted)">
      <i class="fas fa-lock" style="font-size:48px;color:#D6ECFF;display:block;margin-bottom:14px"></i>
      <p style="font-family:'Exo 2',sans-serif;font-size:16px;font-weight:700;color:var(--azul)">Formulario bloqueado</p>
      <p style="font-size:13px;margin-top:6px">Valide un ticket de pago para habilitar el registro de la orden.</p>
    </div>
    <?php endif; ?>
  </div>
</div>

<script>
function toggleSidebar(){document.getElementById("sidebar").classList.toggle("open");document.getElementById("overlay").classList.toggle("open")}
function closeSidebar(){document.getElementById("sidebar").classList.remove("open");document.getElementById("overlay").classList.remove("open")}
function toggleMenu(btn){btn.classList.toggle("open");btn.nextElementSibling.classList.toggle("open")}

function validarTicket(){
  const val = document.getElementById("ticketField").value.trim();
  if(!val){alert("Ingrese el número de ticket.");return;}

  // Mostrar animación de búsqueda
  const overlay = document.createElement("div");
  overlay.id = "tkSearchOverlay";
  overlay.style.cssText = "position:fixed;inset:0;background:rgba(21,101,192,.08);backdrop-filter:blur(2px);z-index:9999;display:flex;align-items:center;justify-content:center";

  overlay.innerHTML = `
    <div style="background:#fff;border-radius:20px;padding:32px 40px;text-align:center;box-shadow:0 20px 60px rgba(21,101,192,.2);border:1px solid #C5DDF9;min-width:300px">
      <svg id="srBarbon" viewBox="0 0 160 180" width="130" style="margin-bottom:12px">
        <!-- Pelo negro voluminoso -->
        <ellipse cx="80" cy="45" rx="46" ry="34" fill="#1a1a1a"/>
        <ellipse cx="80" cy="36" rx="42" ry="24" fill="#111"/>
        <!-- Cachetes gorditos -->
        <ellipse cx="80" cy="82" rx="44" ry="46" fill="#FDDBB4"/>
        <!-- Papada gorda -->
        <ellipse cx="80" cy="118" rx="36" ry="16" fill="#F5C89A"/>
        <!-- Orejas grandes -->
        <ellipse cx="36" cy="80" rx="10" ry="14" fill="#FDDBB4"/>
        <ellipse cx="124" cy="80" rx="10" ry="14" fill="#FDDBB4"/>
        <ellipse cx="36" cy="80" rx="6" ry="9" fill="#F0B080"/>
        <ellipse cx="124" cy="80" rx="6" ry="9" fill="#F0B080"/>
        <!-- Lentes gruesos -->
        <rect x="30" y="68" width="38" height="24" rx="8" fill="none" stroke="#1a1a1a" stroke-width="4"/>
        <rect x="92" y="68" width="38" height="24" rx="8" fill="none" stroke="#1a1a1a" stroke-width="4"/>
        <line x1="68" y1="80" x2="92" y2="80" stroke="#1a1a1a" stroke-width="3"/>
        <line x1="20" y1="76" x2="30" y2="78" stroke="#1a1a1a" stroke-width="3"/>
        <line x1="140" y1="76" x2="130" y2="78" stroke="#1a1a1a" stroke-width="3"/>
        <!-- Ojos -->
        <circle cx="49" cy="80" r="9" fill="white"/>
        <circle cx="111" cy="80" r="9" fill="white"/>
        <circle id="ojoIzq" cx="49" cy="80" r="4.5" fill="#1a1a1a"/>
        <circle id="ojoDer" cx="111" cy="80" r="4.5" fill="#1a1a1a"/>
        <circle id="brilloIzq" cx="51" cy="78" r="1.5" fill="white"/>
        <circle id="brilloDer" cx="113" cy="78" r="1.5" fill="white"/>
        <!-- Cejas pobladas -->
        <path d="M31 64 Q49 58 67 64" fill="none" stroke="#1a1a1a" stroke-width="4" stroke-linecap="round"/>
        <path d="M93 64 Q111 58 129 64" fill="none" stroke="#1a1a1a" stroke-width="4" stroke-linecap="round"/>
        <!-- Nariz grande y redonda -->
        <ellipse cx="80" cy="96" rx="9" ry="7" fill="#F0A870"/>
        <circle cx="75" cy="99" r="3" fill="#E8956A" opacity="0.5"/>
        <circle cx="85" cy="99" r="3" fill="#E8956A" opacity="0.5"/>
        <!-- Boca / sonrisa gordita -->
        <path d="M60 112 Q80 122 100 112" fill="none" stroke="#c07040" stroke-width="3" stroke-linecap="round"/>
        <!-- Barba espesa -->
        <path d="M36 100 Q32 122 44 140 Q58 155 80 158 Q102 155 116 140 Q128 122 124 100 Q105 110 80 112 Q55 110 36 100Z" fill="#1a1a1a"/>
        <path d="M46 106 Q63 116 80 117 Q97 116 114 106" fill="none" stroke="#333" stroke-width="1.5" opacity="0.5"/>
        <path d="M40 116 Q58 124 80 125 Q102 124 120 116" fill="none" stroke="#333" stroke-width="1" opacity="0.4"/>
        <!-- Bigote tupido -->
        <path d="M60 104 Q70 110 80 107 Q90 110 100 104" fill="#111" stroke="#111" stroke-width="1.5"/>
        <!-- Cuerpo gordo con camisa -->
        <ellipse cx="80" cy="170" rx="55" ry="28" fill="#1565C0"/>
        <rect x="58" y="155" width="44" height="20" rx="8" fill="#FDDBB4"/>
        <!-- Corbata -->
        <polygon points="80,160 73,168 80,178 87,168" fill="#29B6F6"/>
        <!-- Botones camisa -->
        <circle cx="80" cy="162" r="2.5" fill="#0D47A1"/>
        <circle cx="80" cy="170" r="2.5" fill="#0D47A1"/>
      </svg>
      <div style="font-family:'Exo 2',sans-serif;font-size:16px;font-weight:800;color:#1565C0;margin-bottom:4px">Verificando ticket</div>
      <div style="font-family:'Exo 2',sans-serif;font-size:24px;font-weight:800;color:#29B6F6;letter-spacing:4px;margin-bottom:8px">#${val}</div>
      <div id="tkSteps" style="font-size:12px;color:#5A7FA8;min-height:18px"></div>
      <div style="display:flex;justify-content:center;gap:6px;margin-top:12px">
        <div style="width:8px;height:8px;border-radius:50%;background:#29B6F6;animation:tkBounce .8s ease-in-out infinite"></div>
        <div style="width:8px;height:8px;border-radius:50%;background:#1E88E5;animation:tkBounce .8s ease-in-out .15s infinite"></div>
        <div style="width:8px;height:8px;border-radius:50%;background:#1565C0;animation:tkBounce .8s ease-in-out .3s infinite"></div>
      </div>
    </div>
    <style>
    @keyframes tkBounce{0%,100%{transform:translateY(0)}50%{transform:translateY(-8px)}}
    @keyframes mirarLados{
      0%,100%{transform:translateX(0)}
      20%{transform:translateX(-3px)}
      40%{transform:translateX(3px)}
      60%{transform:translateX(-2px)}
      80%{transform:translateX(2px)}
    }
    #ojoIzq,#brilloIzq{animation:mirarLados 1.8s ease-in-out infinite}
    #ojoDer,#brilloDer{animation:mirarLados 1.8s ease-in-out infinite}
    </style>`;
  document.body.appendChild(overlay);

  // Simular pasos visuales
  const steps = ["Buscando en base de datos...", "Verificando disponibilidad...", "Confirmando..."];
  let si = 0;
  const stepEl = document.getElementById("tkSteps");
  const stepInterval = setInterval(()=>{
    if(stepEl) stepEl.textContent = steps[si % steps.length];
    si++;
  }, 600);

  // Enviar tras 900ms de animación
  setTimeout(()=>{
    clearInterval(stepInterval);
    document.getElementById("hidTicketBuscar").value = val;
    document.getElementById("formTicket").submit();
  }, 900);
}
function cambiarTicket(){
  window.location.href = "nueva_orden.php";
}
document.getElementById("ticketField") && document.getElementById("ticketField").addEventListener("keydown",function(e){
  if(e.key==="Enter"){e.preventDefault();validarTicket();}
});

function mostrarSecciones(){
  const sel = document.getElementById("selCliente") ? document.getElementById("selCliente").value : "";
  const ids = ["sec2","sec3","sec4","sec5","sec6","sec7","secSubmit"];
  if(sel){
    document.getElementById("alertaCliente").style.display="none";
    ids.forEach(id=>{const el=document.getElementById(id);if(el){el.classList.remove("hidden-section");}});
    setTimeout(iniciarFirma, 80);
  } else {
    document.getElementById("alertaCliente").style.display="block";
    ids.forEach(id=>{const el=document.getElementById(id);if(el)el.classList.add("hidden-section");});
  }
}

function cargarCliente(){
  const sel = document.getElementById("selCliente");
  const opt = sel.options[sel.selectedIndex];
  const email=opt.dataset.email||"", empresa=opt.dataset.empresa||"", tel=opt.dataset.tel||"";
  document.querySelector("#dispEmail span").textContent   = email   || "—";
  document.querySelector("#dispEmpresa span").textContent = empresa || "—";
  document.querySelector("#dispTel span").textContent     = tel     || "—";
  document.getElementById("hidEmail").value   = email;
  document.getElementById("hidEmpresa").value = empresa;
  document.getElementById("hidTel").value     = tel;
}

const accesoriosCat = <?= json_encode(array_column($accesorios,'name')) ?>;
function toggleAccesorios(val){
  const show=val==="SI";
  document.getElementById("hidEquipoAcc").value=val;
  document.getElementById("seccionAccesorios").style.display=show?"block":"none";
  document.getElementById("togSI").className="toggle-opt"+(show?" selected-si":"");
  document.getElementById("togNO").className="toggle-opt"+(!show?" selected-no":"");
  if(show && document.getElementById("listaAccesorios").children.length===0) agregarAccesorio();
}
function agregarAccesorio(){
  const lista=document.getElementById("listaAccesorios");
  const div=document.createElement("div");div.className="acc-row";
  const opts=accesoriosCat.map(a=>`<option value="${a}">${a}</option>`).join("");
  div.innerHTML=`<div><label style="font-size:9px;color:var(--muted);font-weight:700;letter-spacing:1px;text-transform:uppercase;font-family:'Exo 2',sans-serif;margin-bottom:4px;display:block">Accesorio</label><select name="acc_nombre[]" style="width:100%"><option value="">— Seleccionar —</option>${opts}</select></div><div><label style="font-size:9px;color:var(--muted);font-weight:700;letter-spacing:1px;text-transform:uppercase;font-family:'Exo 2',sans-serif;margin-bottom:4px;display:block">No. Serie</label><input type="text" name="acc_serie[]" placeholder="S/N o descripción"></div><button type="button" class="btn-del" onclick="this.parentElement.remove()"><i class="fas fa-trash"></i></button>`;
  lista.appendChild(div);
}

function previewFoto(input,n){
  if(!input.files||!input.files[0])return;
  const reader=new FileReader();
  reader.onload=e=>{document.getElementById("fotoPreview"+n).src=e.target.result;document.getElementById("fotoItem"+n).classList.add("has-photo");};
  reader.readAsDataURL(input.files[0]);
}
function quitarFoto(n){
  document.getElementById("fotoItem"+n).classList.remove("has-photo");
  document.getElementById("fotoPreview"+n).src="";
  const inp=document.querySelector("#fotoItem"+n+" input[type=file]");
  if(inp){try{inp.value="";const dt=new DataTransfer();inp.files=dt.files;}catch(e){}}
}

// ===== FIRMA CANVAS =====
let firmaColor = "#0057B8";
let firmaDraw  = false;
let firmaLX    = 0, firmaLY = 0;
let firmaIniciada = false;

function iniciarFirma(){
  const canvas = document.getElementById("firmaCanvas");
  if(!canvas || firmaIniciada) return;
  firmaIniciada = true;
  const ctx = canvas.getContext("2d");

  function resizeFirma(){
    const w = canvas.parentElement.clientWidth || 300;
    if(canvas.width === w) return;
    canvas.width  = w;
    canvas.height = 200;
    ctx.fillStyle = "#F5FAFF";
    ctx.fillRect(0,0,canvas.width,canvas.height);
  }
  resizeFirma();
  window.addEventListener("resize", resizeFirma);

  function getPos(e){
    const r = canvas.getBoundingClientRect();
    const src = e.touches ? e.touches[0] : e;
    return {
      x:(src.clientX - r.left)*(canvas.width/r.width),
      y:(src.clientY - r.top)*(canvas.height/r.height)
    };
  }
  function down(e){ e.stopPropagation(); e.preventDefault(); firmaDraw=true; const p=getPos(e); firmaLX=p.x; firmaLY=p.y; }
  function move(e){
    e.stopPropagation(); e.preventDefault();
    if(!firmaDraw) return;
    const p=getPos(e);
    ctx.beginPath(); ctx.moveTo(firmaLX,firmaLY); ctx.lineTo(p.x,p.y);
    ctx.strokeStyle=firmaColor; ctx.lineWidth=2.5; ctx.lineCap="round"; ctx.stroke();
    firmaLX=p.x; firmaLY=p.y;
  }
  function up(e){
    e.stopPropagation();
    if(!firmaDraw) return; firmaDraw=false;
    document.getElementById("firmaData").value = canvas.toDataURL("image/png");
  }
  canvas.addEventListener("mousedown",  down, {passive:false});
  canvas.addEventListener("mousemove",  move, {passive:false});
  canvas.addEventListener("mouseup",    up,   {passive:false});
  canvas.addEventListener("mouseleave", up,   {passive:false});
  canvas.addEventListener("touchstart", down, {passive:false});
  canvas.addEventListener("touchmove",  move, {passive:false});
  canvas.addEventListener("touchend",   up,   {passive:false});
}

function cambiarColor(c){ firmaColor = c; }
function limpiarFirma(){
  const c = document.getElementById("firmaCanvas");
  if(!c) return;
  c.getContext("2d").clearRect(0,0,c.width,c.height);
  document.getElementById("firmaData").value="";
}
</script>
<?php include __DIR__."/theme.php"; ?>
</body>
</html>