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

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

// ── AJAX: validar ticket anticipo ──────────────────────────
if(isset($_GET['action']) && ($_GET['vista']??'')==='anticipo'){
    header('Content-Type: application/json');
    if($_GET['action']==='validar_ticket'){
        $folio=trim($_GET['folio']??'');
        if(!$folio){echo json_encode(['status'=>'vacio']);exit;}
        $r=$pdo->prepare("SELECT total_pagado,creado_por,fecha_creacion FROM anticipo_revision WHERE folio_de_ticket=? LIMIT 1");
        $r->execute([$folio]);$ant=$r->fetch();
        if($ant){echo json_encode(['status'=>'duplicado','msg'=>"Ticket #$folio ya registrado por {$ant['creado_por']} el {$ant['fecha_creacion']}",'total'=>$ant['total_pagado']]);}
        else{echo json_encode(['status'=>'disponible']);}
    }
    exit;
}

// ── ANTICIPO: GUARDAR ──────────────────────────────────────
$msgOk='';$msgErr='';
if($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['_action']??'')==='guardar_anticipo'){
    $folio =trim($_POST['folio_de_ticket']??'');
    $total =trim($_POST['total_pagado']??'');
    $imgB64=$_POST['imagen_ticket']??'';
    if(!$folio||!$total){ $msgErr='Folio y total son requeridos.'; }
    else {
        $dup=$pdo->prepare("SELECT id_anticipo FROM anticipo_revision WHERE folio_de_ticket=? LIMIT 1");
        $dup->execute([$folio]);
        if($dup->fetch()){ $msgErr="El ticket #$folio ya está registrado."; }
        else {
            try {
                $imgG='';
                if($imgB64&&strpos($imgB64,'base64,')!==false){
                    [,$b64]=explode('base64,',$imgB64,2);
                    $bin=base64_decode($b64);$img=@imagecreatefromstring($bin);
                    if($img){$w=imagesx($img);$h=imagesy($img);$mw=600;
                        if($w>$mw){$nh=(int)($h*$mw/$w);$r2=imagecreatetruecolor($mw,$nh);imagecopyresampled($r2,$img,0,0,0,0,$mw,$nh,$w,$h);imagedestroy($img);$img=$r2;}
                        ob_start();imagejpeg($img,null,60);$jpg=ob_get_clean();imagedestroy($img);
                        $imgG='data:image/jpeg;base64,'.base64_encode($jpg);}
                    else{$imgG=$imgB64;}
                }
                $dbcols=$pdo->query("SHOW COLUMNS FROM anticipo_revision")->fetchAll(PDO::FETCH_COLUMN);
                $data=['folio_de_ticket'=>$folio,'total_pagado'=>$total,'imagen_ticket'=>$imgG,
                       'creado_por'=>$usuario,'sucursal'=>$sucursal,'fecha_creacion'=>date('Y-m-d H:i:s'),
                       'estatus'=>'DISPONIBLE','id_orden_serv_aplicado'=>''];
                $data=array_filter($data,fn($k)=>in_array($k,$dbcols),ARRAY_FILTER_USE_KEY);
                $flds=implode(',',array_map(fn($k)=>"`$k`",array_keys($data)));
                $hlds=implode(',',array_fill(0,count($data),'?'));
                $pdo->prepare("INSERT INTO anticipo_revision ($flds) VALUES ($hlds)")->execute(array_values($data));
                $msgOk="Ticket <strong>#$folio</strong> registrado — Total: <strong>$$total</strong>";
            } catch(PDOException $e){ $msgErr='Error: '.$e->getMessage(); }
        }
    }
}

// ── ANTICIPO: EDITAR ───────────────────────────────────────
if($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['_action']??'')==='editar_anticipo' && $rol==='ADMINISTRADOR'){
    $id=( int)($_POST['id_anticipo']??0);
    $folio=trim($_POST['folio_de_ticket']??'');
    $total=trim($_POST['total_pagado']??'');
    $est=trim($_POST['estatus']??'DISPONIBLE');
    if($id&&$folio&&$total){
        try{$pdo->prepare("UPDATE anticipo_revision SET folio_de_ticket=?,total_pagado=?,estatus=? WHERE id_anticipo=?")->execute([$folio,$total,$est,$id]);$msgOk="Anticipo <strong>#$folio</strong> actualizado.";}
        catch(PDOException $e){$msgErr='Error: '.$e->getMessage();}
    }
}

// ── ANTICIPO: BORRAR ───────────────────────────────────────
if($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['_action']??'')==='borrar_anticipo' && $rol==='ADMINISTRADOR'){
    $id=(int)($_POST['id_anticipo']??0);
    if($id){try{$pdo->prepare("DELETE FROM anticipo_revision WHERE id_anticipo=?")->execute([$id]);$msgOk="Anticipo eliminado.";}catch(PDOException $e){$msgErr='Error: '.$e->getMessage();}}
}

// ── CLIENTES: GUARDAR ─────────────────────────────────────
if($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['_action']??'')==='guardar_cliente' && $rol==='ADMINISTRADOR'){
    $nom=trim($_POST['nombre_cliente_completo']??'');
    $tel=trim($_POST['telefono']??'');
    $eml=trim($_POST['email_cliente']??'');
    $emp=trim($_POST['empresa_ref_cliente']??'');
    if($nom){
        try{
            $pdo->prepare("INSERT INTO clientes_tec (nombre_cliente_completo,telefono,email_cliente,empresa_ref_cliente,sucursal,creado_por,fecha_alta_cliente) VALUES (?,?,?,?,?,?,NOW())")
                ->execute([$nom,$tel,$eml,$emp,$sucursal,$usuario]);
            $msgOk="Cliente <strong>$nom</strong> registrado.";
        }catch(PDOException $e){$msgErr='Error: '.$e->getMessage();}
    }else{$msgErr='El nombre es obligatorio.';}
}
// ── CLIENTES: EDITAR ──────────────────────────────────────
if($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['_action']??'')==='editar_cliente' && $rol==='ADMINISTRADOR'){
    $id=(int)($_POST['id_cliente']??0);
    $nom=trim($_POST['nombre_cliente_completo']??'');
    $tel=trim($_POST['telefono']??'');
    $eml=trim($_POST['email_cliente']??'');
    $emp=trim($_POST['empresa_ref_cliente']??'');
    if($id&&$nom){
        try{
            $pdo->prepare("UPDATE clientes_tec SET nombre_cliente_completo=?,telefono=?,email_cliente=?,empresa_ref_cliente=? WHERE id_cliente=?")
                ->execute([$nom,$tel,$eml,$emp,$id]);
            $msgOk="Cliente actualizado.";
        }catch(PDOException $e){$msgErr='Error: '.$e->getMessage();}
    }
}
// ── CLIENTES: BORRAR ──────────────────────────────────────
if($_SERVER['REQUEST_METHOD']==='POST' && ($_POST['_action']??'')==='borrar_cliente' && $rol==='ADMINISTRADOR'){
    $id=(int)($_POST['id_cliente']??0);
    if($id){
        try{$pdo->prepare("DELETE FROM clientes_tec WHERE id_cliente=?")->execute([$id]);$msgOk="Cliente eliminado.";}
        catch(PDOException $e){$msgErr='Error: '.$e->getMessage();}
    }
}

// ── DATOS TABLA ────────────────────────────────────────────
$vista=$_GET["vista"]??'';
$datos=[];$cols=[];$titulo='';

if($vista==="anticipo"){
    $titulo="Anticipo Revisión";
    $res=$pdo->query("SELECT * FROM anticipo_revision ORDER BY id_anticipo DESC");
    $datos=$res->fetchAll();$cols=$datos?array_keys($datos[0]):[];
}elseif($vista==="clientes"){
    $titulo="Clientes TEC";
    $res=$pdo->query("SELECT * FROM clientes_tec ORDER BY id_cliente DESC");
    $datos=$res->fetchAll();$cols=$datos?array_keys($datos[0]):[];
}elseif($vista==="ordenes"){
    $titulo="Órdenes de Servicio";
    $res=$pdo->query("SELECT * FROM ordenes_de_servicio ORDER BY id_orden_serv DESC");
    $datos=$res->fetchAll();$cols=$datos?array_keys($datos[0]):[];
}
?><!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>PROCEIN 2026 PRO — Dashboard</title>
<link href="https://fonts.googleapis.com/css2?family=Exo+2:wght@300;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;--sidebar:#0D1B30;--texto:#0D2A4A;--muted:#5A7FA8;--borde:#90CAF9;--blanco:#FFFFFF;--sidebar-w:260px;}
html,body{height:100%;width:100%}
body{font-family:"Inter",sans-serif;background:var(--fondo);color:var(--texto);display:flex;min-height:100vh}
.sidebar{width:var(--sidebar-w);min-height:100vh;background:var(--sidebar);display:flex;flex-direction:column;position:fixed;left:0;top:0;bottom:0;z-index:100;box-shadow:4px 0 24px rgba(0,0,0,.25);transition:transform .3s}
.sidebar-logo{padding:20px 18px 16px;border-bottom:1px solid rgba(41,182,246,.1);display:flex;align-items:center;gap:12px}
.sidebar-logo img{height:70px;filter:drop-shadow(0 0 8px rgba(41,182,246,.3))}
.sidebar-logo-text{font-family:"Exo 2",sans-serif;font-size:13px;font-weight:800;color:#fff;line-height:1.2}
.sidebar-logo-text span{color:var(--acento);display:block;font-size:10px;letter-spacing:2px;font-weight:600}
.sidebar-user{padding:13px 18px;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:36px;height:36px;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:14px;font-weight:800;color:#fff;flex-shrink:0}
.user-name{font-size:12px;font-weight:600;color:#E8F2FF;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.user-role{font-size:10px;color:var(--acento);letter-spacing:1px;text-transform:uppercase;font-weight:600}
.nav{flex:1;padding:14px 0;overflow-y:auto}
.nav-label{font-family:"Exo 2",sans-serif;font-size:12px;font-weight:700;letter-spacing:2.5px;text-transform:uppercase;color:rgba(144,202,249,.35);padding:10px 20px 5px}
.menu-btn{width:100%;display:flex;align-items:center;gap:12px;padding:12px 20px;background:none;border:none;cursor:pointer;color:#90CAF9;font-family:"Exo 2",sans-serif;font-size:13px;font-weight:600;text-align:left;transition:background .15s,color .15s;position:relative}
.menu-btn:hover{background:#1A2F4A;color:#fff}
.menu-btn.active{background:rgba(41,182,246,.12);color:var(--acento)}
.menu-btn.active::before{content:"";position:absolute;left:0;top:20%;bottom:20%;width:3px;border-radius:0 3px 3px 0;background:var(--acento);box-shadow:0 0 8px rgba(0,229,255,.6)}
.menu-btn .icon{width:32px;height:32px;border-radius:8px;background:rgba(41,182,246,.1);display:flex;align-items:center;justify-content:center;font-size:14px;flex-shrink:0}
.menu-btn .arrow{margin-left:auto;font-size:11px;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 .35s cubic-bezier(.16,1,.3,1);background:rgba(0,0,0,.15)}
.submenu.open{max-height:300px}
.sub-item{display:flex;align-items:center;gap:10px;padding:10px 20px 10px 52px;color:#6A8BAE;font-size:12px;text-decoration:none;transition:background .15s,color .15s;border-left:2px solid transparent;margin-left:18px}
.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:11px;width:16px;text-align:center;color:var(--acento);opacity:.7}
.sidebar-footer{padding:13px 16px;border-top:1px solid rgba(41,182,246,.08)}
.logout-btn{width:100%;display:flex;align-items:center;gap:10px;padding:10px 14px;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:12px;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:var(--blanco);border-bottom:1px solid #D6ECFF;padding:14px 28px;display:flex;align-items:center;gap:16px;box-shadow:0 2px 12px rgba(21,101,192,.07);position:sticky;top:0;z-index:50}
.topbar-title{font-family:"Exo 2",sans-serif;font-size:18px;font-weight:800;color:var(--azul)}
.topbar-title em{color:var(--acento);font-style:normal}
.topbar-breadcrumb{font-size:12px;color:var(--muted);margin-left:auto;display:flex;align-items:center;gap:6px}
.hamburger{display:none;background:none;border:none;cursor:pointer;color:var(--azul);font-size:20px}
.content{flex:1;padding:clamp(16px,3vw,32px)}
.welcome-card{background:linear-gradient(135deg,var(--azul) 0%,var(--azul2) 60%,var(--acento) 100%);border-radius:14px;padding:28px 32px;color:#fff;margin-bottom:28px;display:flex;align-items:center;justify-content:space-between;box-shadow:0 8px 30px rgba(21,101,192,.3);position:relative;overflow:hidden}
.welcome-card::before{content:"";position:absolute;right:-40px;top:-40px;width:200px;height:200px;border-radius:50%;background:rgba(255,255,255,.06)}
.welcome-title{font-family:"Exo 2",sans-serif;font-size:clamp(16px,3vw,22px);font-weight:800;margin-bottom:4px}
.welcome-sub{font-size:13px;opacity:.8}
.welcome-icon{font-size:clamp(36px,6vw,56px);opacity:.7}
.stats-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:16px;margin-bottom:28px}
.stat-card{background:var(--blanco);border-radius:12px;padding:20px;border:1px solid #D6ECFF;box-shadow:0 2px 12px rgba(21,101,192,.06);display:flex;align-items:center;gap:16px;transition:transform .2s,box-shadow .2s;text-decoration:none;color:inherit}
.stat-card:hover{transform:translateY(-3px);box-shadow:0 8px 24px rgba(21,101,192,.12)}
.stat-icon{width:48px;height:48px;border-radius:12px;display:flex;align-items:center;justify-content:center;font-size:20px;flex-shrink:0}
.stat-icon.blue{background:linear-gradient(135deg,#E3F2FD,#BBDEFB)}
.stat-icon.cyan{background:linear-gradient(135deg,#E0F7FA,#B2EBF2)}
.stat-icon.green{background:linear-gradient(135deg,#E8F5E9,#C8E6C9)}
.stat-num{font-family:"Exo 2",sans-serif;font-size:24px;font-weight:800;color:var(--azul)}
.stat-label{font-size:11px;color:var(--muted);font-weight:500}
.table-panel{background:var(--blanco);border-radius:14px;border:1px solid #D6ECFF;box-shadow:0 2px 16px rgba(21,101,192,.07);overflow:hidden}
.table-header{padding:16px 22px;border-bottom:1px solid #E3F0FF;display:flex;align-items:center;gap:12px;flex-wrap:wrap}
.table-title{font-family:"Exo 2",sans-serif;font-size:16px;font-weight:700;color:var(--azul)}
.table-badge{background:linear-gradient(135deg,var(--azul),var(--acento));color:#fff;border-radius:20px;padding:3px 12px;font-size:11px;font-weight:700;font-family:"Exo 2",sans-serif}
.btn-nueva-orden{display:inline-flex;align-items:center;gap:7px;padding:8px 16px;background:linear-gradient(135deg,#1565C0,#1E88E5);border-radius:8px;color:#fff;text-decoration:none;font-size:12px;font-weight:700;font-family:"Exo 2",sans-serif;letter-spacing:1px;box-shadow:0 3px 10px rgba(21,101,192,.25);transition:transform .15s,box-shadow .2s;border:none;cursor:pointer}
.btn-nueva-orden:hover{transform:translateY(-1px);box-shadow:0 6px 18px rgba(21,101,192,.35)}
.table-search{margin-left:auto;padding:8px 14px;background:#F0F8FF;border:1.5px solid var(--borde);border-radius:8px;font-size:13px;color:var(--texto);outline:none;width:200px;transition:border-color .2s}
.table-search:focus{border-color:var(--azul2)}
.table-wrap{overflow-x:auto}
table{width:100%;border-collapse:collapse;font-size:13px}
thead{background:linear-gradient(90deg,#E8F2FF,#EBF5FF)}
th{padding:11px 16px;text-align:left;font-family:"Exo 2",sans-serif;font-size:10px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:var(--muted);border-bottom:2px solid #D6ECFF;white-space:nowrap}
td{padding:11px 16px;border-bottom:1px solid #F0F6FF;color:var(--texto);max-width:180px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
tr:hover td{background:#F5FAFF}
tr:last-child td{border-bottom:none}
.empty-state{text-align:center;padding:48px;color:var(--muted)}
.empty-state i{font-size:40px;margin-bottom:12px;color:#D6ECFF;display:block}
.empty-state p{font-size:14px}
.badge-disp{background:#d1fae5;color:#065f46;border:1px solid #a7f3d0;padding:2px 8px;border-radius:20px;font-size:11px;font-weight:700}
.badge-used{background:#f1f5f9;color:#475569;border:1px solid #e2e8f0;padding:2px 8px;border-radius:20px;font-size:11px;font-weight:700}
.ant-thumb{width:42px;height:42px;object-fit:cover;border-radius:6px;border:1px solid #D6ECFF;cursor:pointer}
/* ANTICIPO MODAL */
.ant-alert-ok{display:flex;align-items:flex-start;gap:9px;padding:12px 16px;border-radius:10px;margin-bottom:14px;font-size:13px;font-weight:500;background:#d1fae5;border:1px solid #a7f3d0;color:#065f46}
.ant-alert-err{display:flex;align-items:flex-start;gap:9px;padding:12px 16px;border-radius:10px;margin-bottom:14px;font-size:13px;font-weight:500;background:#fee2e2;border:1px solid #fecaca;color:#991b1b}
.ant-btn-add{display:inline-flex;align-items:center;gap:7px;padding:9px 18px;border-radius:9px;background:linear-gradient(135deg,var(--azul),var(--azul2));color:#fff;font-family:"Exo 2",sans-serif;font-size:13px;font-weight:700;cursor:pointer;border:none;box-shadow:0 3px 12px rgba(21,101,192,.25);transition:all .15s;letter-spacing:.5px}
.ant-btn-add:hover{transform:translateY(-1px);box-shadow:0 6px 18px rgba(21,101,192,.35)}
.ant-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.55);backdrop-filter:blur(4px);z-index:9999;align-items:center;justify-content:center;padding:14px}
.ant-overlay.open{display:flex}
.ant-modal{background:#fff;border-radius:16px;padding:26px;width:720px;max-width:100%;max-height:94vh;overflow-y:auto;box-shadow:0 20px 60px rgba(0,0,0,.2);animation:mIn .18s ease}
@keyframes mIn{from{opacity:0;transform:scale(.95)}to{opacity:1;transform:scale(1)}}
.ant-modal-title{font-family:"Exo 2",sans-serif;font-size:17px;font-weight:800;color:var(--azul);margin-bottom:18px;display:flex;align-items:center;gap:9px}
.ant-modal-foot{display:flex;gap:9px;justify-content:flex-end;margin-top:16px;padding-top:14px;border-top:1px solid #E3F0FF}
.ant-fg{margin-bottom:14px}
.ant-lbl{display:block;font-size:10px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:1px;margin-bottom:5px}
.ant-inp{width:100%;padding:10px 13px;background:#F0F8FF;border:1.5px solid var(--borde);border-radius:10px;color:var(--texto);font-family:"Inter",sans-serif;font-size:14px;outline:none;transition:all .2s;-webkit-appearance:none}
.ant-inp:focus{border-color:var(--azul);background:#fff;box-shadow:0 0 0 3px rgba(21,101,192,.1)}
.ant-inp.ok{border-color:#059669}.ant-inp.err{border-color:#dc2626}
.ant-inp-xl{font-size:26px!important;font-weight:800!important;text-align:center!important;letter-spacing:4px!important;color:var(--azul)!important}
.ant-btn-pri{display:inline-flex;align-items:center;gap:7px;padding:10px 18px;border-radius:10px;background:var(--azul);color:#fff;font-family:"Exo 2",sans-serif;font-size:13px;font-weight:700;cursor:pointer;border:none;transition:all .15s}
.ant-btn-pri:hover{background:var(--azul2)}.ant-btn-pri:disabled{opacity:.4;cursor:not-allowed}
.ant-btn-sec{display:inline-flex;align-items:center;gap:7px;padding:9px 16px;border-radius:9px;background:#F0F8FF;color:var(--muted);font-family:"Exo 2",sans-serif;font-size:13px;font-weight:600;cursor:pointer;border:1px solid var(--borde);transition:all .15s}
.ant-btn-sec:hover{background:#E3F0FF}
.ant-btn-sm{padding:5px 10px!important;font-size:11px!important}
.ant-btn-danger{background:#fff0f0!important;color:#dc2626!important;border:1px solid #fecaca!important}
.ant-uz{border:3px dashed var(--borde);border-radius:14px;padding:32px 20px;text-align:center;cursor:pointer;transition:all .22s;background:#F0F8FF;position:relative}
.ant-uz:hover,.ant-uz.over{border-color:var(--azul);background:#E3F0FF}
.ant-uz.has{border-color:#059669;background:#f0fdf4}
.ant-uz i{font-size:38px;color:var(--muted);margin-bottom:10px;display:block}
.ant-uz input[type=file]{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%}
.ant-ocr-p{display:none;margin-top:10px;background:#fffbeb;border:1px solid #fde68a;border-radius:9px;padding:11px 14px}
.ant-ocr-track{height:5px;background:#fde68a;border-radius:3px;overflow:hidden;margin-bottom:6px}
.ant-ocr-fill{height:100%;background:#f59e0b;border-radius:3px;width:0%;transition:width .3s}
.ant-ocr-step{font-size:12px;color:#92400e;font-weight:600}
.ant-ocr-r{display:none;margin-bottom:12px;background:linear-gradient(135deg,#f0fdf4,#ecfdf5);border:2px solid #a7f3d0;border-radius:11px;padding:13px}
.ant-ocr-2c{display:grid;grid-template-columns:1fr 1fr;gap:9px;margin-bottom:7px}
.ant-ocr-d{text-align:center;padding:11px;background:#fff;border-radius:8px;border:1px solid #D6ECFF}
.ant-ocr-d-l{font-size:9px;font-weight:700;color:var(--muted);text-transform:uppercase;letter-spacing:1px}
.ant-ocr-d-v{font-size:24px;font-weight:800;letter-spacing:3px;margin-top:2px}
.ant-tk{display:none;margin-top:7px;padding:8px 13px;border-radius:9px;font-size:13px;align-items:center;gap:7px}
.ant-tk.show{display:flex}
.ant-tk-ok{background:#d1fae5;border:1px solid #a7f3d0;color:#065f46}
.ant-tk-err{background:#fee2e2;border:1px solid #fecaca;color:#991b1b}
.ant-tk-chk{background:#fffbeb;border:1px solid #fde68a;color:#92400e}
.ant-lb{display:none;position:fixed;inset:0;background:rgba(0,0,0,.86);z-index:99999;align-items:center;justify-content:center}
.ant-lb.open{display:flex}
.ant-lb img{max-width:92vw;max-height:90vh;border-radius:8px;object-fit:contain}
.ant-lb-x{position:absolute;top:14px;right:18px;color:#fff;font-size:28px;cursor:pointer;background:none;border:none}
@keyframes spin{to{transform:rotate(360deg)}}
.ant-spin{animation:spin 1s linear infinite}
.overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:99}
@media(max-width:768px){
  .sidebar{transform:translateX(-100%)}.sidebar.open{transform:translateX(0)}
  .main{margin-left:0}.hamburger{display:block}
  .overlay{display:block;opacity:0;pointer-events:none;transition:opacity .3s}.overlay.open{opacity:1;pointer-events:all}
  .stats-grid{grid-template-columns:1fr 1fr}.table-search{width:100%;margin-left:0;margin-top:8px}
  .welcome-icon{display:none}.ant-ocr-2c{grid-template-columns:1fr}
  .ant-modal-grid{grid-template-columns:1fr!important}
}
</style>
</head>
<body>
<div class="overlay" id="overlay" onclick="closeSidebar()"></div>

<aside class="sidebar" id="sidebar">
  <div class="sidebar-logo">
    <img src="https://lh3.googleusercontent.com/d/18I4DcekLRsd0Lfsg8cpqxU7Vh6b1IC4O" alt="VANTECC">
      </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">Menu</div>
    <div>
      <button class="menu-btn <?= in_array($vista,["anticipo","clientes","ordenes"])?"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 <?= in_array($vista,["anticipo","clientes","ordenes"])?"open":"" ?>">
        <a href="?vista=ordenes" class="sub-item <?= $vista==="ordenes"?"active":"" ?>"><i class="fas fa-file-alt"></i> Órdenes de Servicio</a>
        <a href="?vista=anticipo" class="sub-item <?= $vista==="anticipo"?"active":"" ?>"><i class="fas fa-dollar-sign"></i> Registrar Anticipo</a>
        <a href="?vista=clientes" class="sub-item <?= $vista==="clientes"?"active":"" ?>"><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">PROCEIN <em>2026</em> PRO</div>
    <div class="topbar-breadcrumb">
      <i class="fas fa-home"></i>
      <?php if($titulo): ?><span style="color:#bbb">·</span> Servicios Técnicos <span style="color:#bbb">·</span> <?= htmlspecialchars($titulo) ?>
      <?php else: ?><span>Dashboard</span><?php endif; ?>
    </div>
  </div>

  <div class="content">

  <?php if(!$vista): ?>
    <div class="welcome-card">
      <div>
        <div class="welcome-title">Bienvenido, <?= htmlspecialchars($usuario) ?></div>
        <div class="welcome-sub">Sucursal: <?= htmlspecialchars($sucursal) ?> &nbsp;·&nbsp; Rol: <?= htmlspecialchars($rol) ?></div>
      </div>
      <div class="welcome-icon"><i class="fas fa-laptop-code"></i></div>
    </div>
    <?php
    $nOrdenes  = $pdo->query("SELECT COUNT(*) FROM ordenes_de_servicio")->fetchColumn();
    $nClientes = $pdo->query("SELECT COUNT(*) FROM clientes_tec")->fetchColumn();
    $nAnticipos= $pdo->query("SELECT COUNT(*) FROM anticipo_revision")->fetchColumn();
    ?>
    <div class="stats-grid">
      <a href="?vista=ordenes" class="stat-card"><div class="stat-icon blue"><i class="fas fa-file-alt" style="color:#1565C0"></i></div><div><div class="stat-num"><?=$nOrdenes?></div><div class="stat-label">Órdenes</div></div></a>
      <a href="?vista=clientes" class="stat-card"><div class="stat-icon cyan"><i class="fas fa-users" style="color:#0097A7"></i></div><div><div class="stat-num"><?=$nClientes?></div><div class="stat-label">Clientes</div></div></a>
      <a href="?vista=anticipo" class="stat-card"><div class="stat-icon green"><i class="fas fa-dollar-sign" style="color:#2E7D32"></i></div><div><div class="stat-num"><?=$nAnticipos?></div><div class="stat-label">Anticipos</div></div></a>
    </div>

  <?php elseif($vista==="anticipo"): ?>
    <?php if($msgOk): ?><div class="ant-alert-ok">✅ <?=$msgOk?> <button onclick="abrirModal()" style="margin-left:10px;background:none;border:1px solid #059669;border-radius:6px;padding:2px 9px;font-size:11px;color:#059669;cursor:pointer;font-weight:700">+ Otro</button></div><?php endif; ?>
    <?php if($msgErr): ?><div class="ant-alert-err">❌ <?=htmlspecialchars($msgErr)?></div><?php endif; ?>
    <div class="table-panel">
      <div class="table-header">
        <i class="fas fa-dollar-sign" style="color:var(--acento);font-size:18px"></i>
        <span class="table-title">Anticipo Revisión</span>
        <span class="table-badge"><?=count($datos)?> registros</span>
        <input type="text" class="table-search" placeholder="🔍  Buscar..." onkeyup="filtrar(this)">
        <button onclick="abrirModal()" class="ant-btn-add"><i class="fas fa-plus"></i> Agregar Anticipo</button>
      </div>
      <div class="table-wrap">
        <?php if($datos): ?>
        <table id="miTabla">
          <thead><tr>
            <th></th><th>Folio Ticket</th><th>Total</th><th>Estado</th>
            <th>Orden Aplicada</th><th>Registrado por</th><th>Sucursal</th><th>Fecha</th>
            <?php if($rol==='ADMINISTRADOR'): ?><th>Acciones</th><?php endif; ?>
          </tr></thead>
          <tbody>
          <?php foreach($datos as $a):
            $st=strtoupper($a['estatus']??'');$img=$a['imagen_ticket']??'';
          ?>
          <tr>
            <td><?php if($img):?><img src="<?=htmlspecialchars($img)?>" class="ant-thumb" onclick="verLb('<?=htmlspecialchars($img)?>')" onerror="this.style.opacity='.15'"><?php else:?>🎫<?php endif;?></td>
            <td><span style="font-size:16px;font-weight:800;color:var(--azul);letter-spacing:2px">#<?=htmlspecialchars($a['folio_de_ticket']??'—')?></span></td>
            <td><span style="font-size:14px;font-weight:700;color:#059669">$<?=number_format((float)($a['total_pagado']??0))?></span></td>
            <td><span class="<?=$st==='DISPONIBLE'?'badge-disp':'badge-used'?>"><?=htmlspecialchars($st?:'—')?></span></td>
            <td><?=!empty($a['id_orden_serv_aplicado'])?'<span style="color:var(--azul);font-weight:700">'.htmlspecialchars($a['id_orden_serv_aplicado']).'</span>':'<span style="color:var(--muted);font-size:11px">Sin orden</span>'?></td>
            <td style="font-size:12px;color:var(--muted)"><?=htmlspecialchars($a['creado_por']??'—')?></td>
            <td style="font-size:12px;color:var(--muted)"><?=htmlspecialchars($a['sucursal']??'—')?></td>
            <td style="font-size:11px;color:var(--muted);white-space:nowrap"><?=htmlspecialchars(substr($a['fecha_creacion']??'',0,16))?></td>
            <?php if($rol==='ADMINISTRADOR'): ?>
            <td style="white-space:nowrap">
              <button onclick="antEditar(<?=$a['id_anticipo']?>,'<?=htmlspecialchars(addslashes($a['folio_de_ticket']??''))?>',' <?=htmlspecialchars(addslashes($a['total_pagado']??''))?>',' <?=htmlspecialchars(addslashes($a['estatus']??'DISPONIBLE'))?>')" class="ant-btn-sec ant-btn-sm" style="margin-right:4px"><i class="fas fa-edit"></i> Editar</button>
              <button onclick="antBorrar(<?=$a['id_anticipo']?>,'<?=htmlspecialchars(addslashes($a['folio_de_ticket']??''))?>')" class="ant-btn-sec ant-btn-sm ant-btn-danger"><i class="fas fa-trash"></i></button>
            </td>
            <?php endif; ?>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
        <?php else: ?>
        <div class="empty-state"><i class="fas fa-dollar-sign"></i><p>Sin anticipos registrados.</p>
          <button onclick="abrirModal()" class="ant-btn-add" style="margin-top:14px"><i class="fas fa-plus"></i> Registrar primero</button></div>
        <?php endif; ?>
      </div>
    </div>

  <?php elseif($vista==="ordenes"): ?>
    <div class="table-panel">
      <div class="table-header">
        <i class="fas fa-file-alt" style="color:var(--acento);font-size:18px"></i>
        <span class="table-title">Órdenes de Servicio</span>
        <span class="table-badge"><?=count($datos)?> registros</span>
        <a href="nueva_orden.php" class="btn-nueva-orden"><i class="fas fa-plus-circle"></i> Nueva Orden</a>
        <input type="text" class="table-search" placeholder="🔍  Buscar..." onkeyup="filtrar(this)">
      </div>
      <div class="table-wrap">
        <?php if($datos): ?>
        <table id="miTabla">
          <thead><tr>
            <th>Folio</th><th>Fecha</th><th>Cliente</th><th>Teléfono</th>
            <th>Estado</th><th>Asesor</th><th>Sucursal</th>
            <?php if($rol==='ADMINISTRADOR'): ?><th style="text-align:center">Acc.</th><?php endif; ?>
          </tr></thead>
          <tbody>
          <?php foreach($datos as $row):
            $yr  = date('Y', strtotime($row['fecha_creacion'] ?? date('Y-m-d')));
            $fol = $yr.'-'.str_pad($row['id_orden_serv'],4,'0',STR_PAD_LEFT);
            $est = strtoupper($row['estado'] ?? '—');
            $ec  = ['EN REVISION'=>'#FFF8E1|#F57F17','EN PROCESO'=>'#E3F2FD|#1565C0','TERMINADO'=>'#E8F5E9|#2E7D32','ENTREGADO'=>'#E8F5E9|#1B5E20','CANCELADO'=>'#FFEBEE|#C62828'];
            $ep  = isset($ec[$est]) ? explode('|',$ec[$est]) : ['#F5FAFF','#5A7FA8'];
          ?>
          <tr>
            <td><a href="ver_orden.php?id=<?=$row['id_orden_serv']?>" style="font-family:'Exo 2',sans-serif;font-size:13px;font-weight:800;color:#1565C0;text-decoration:none;background:#EBF5FF;padding:4px 10px;border-radius:6px;border:1px solid #90CAF9;white-space:nowrap"><?=htmlspecialchars($fol)?> <i class="fas fa-external-link-alt" style="font-size:9px;opacity:.5"></i></a></td>
            <td style="font-size:12px;color:var(--muted);white-space:nowrap"><?=htmlspecialchars(substr($row['fecha_creacion']??'—',0,16))?></td>
            <td style="font-weight:600;max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap" title="<?=htmlspecialchars($row['nombre_cliente']??'')?>"><?=htmlspecialchars(mb_strimwidth($row['nombre_cliente']??'—',0,20,'…'))?></td>
            <td style="font-size:13px"><?=htmlspecialchars($row['telefono_cliente']??'—')?></td>
            <td><?php
              $iconos=['EN REVISION'=>'fa-search','SERVICIO COTIZADO'=>'fa-file-invoice-dollar',
                       'CONFIRMADO'=>'fa-thumbs-up','PAGADO'=>'fa-money-bill-wave',
                       'ENTREGADO FINAL'=>'fa-box-open','CANCELADO'=>'fa-times-circle'];
              $ico=$iconos[$est]??'fa-circle';
            ?><span style="background:<?=$ep[0]?>;color:<?=$ep[1]?>;border:1.5px solid <?=$ep[1]?>;border-radius:20px;padding:4px 12px;font-size:11px;font-weight:800;font-family:'Exo 2',sans-serif;white-space:nowrap;display:inline-flex;align-items:center;gap:5px;letter-spacing:.5px"><i class="fas <?=$ico?>"></i><?=htmlspecialchars($est)?></span></td>
            <td style="font-size:12px;color:var(--muted)"><?=htmlspecialchars(mb_strimwidth($row['asesor_que_atiende']??'—',0,16,'…'))?></td>
            <td style="font-size:12px;color:var(--muted)"><?=htmlspecialchars($row['sucursal']??'—')?></td>
            <?php if($rol==='ADMINISTRADOR'): ?>
            <td style="white-space:nowrap;text-align:center">
              <a href="editar_orden.php?id=<?=$row['id_orden_serv']?>" style="display:inline-flex;align-items:center;padding:6px 8px;background:#EBF5FF;border:1px solid #90CAF9;border-radius:6px;color:#1565C0;font-size:12px;text-decoration:none;margin-right:3px" title="Editar"><i class="fas fa-edit"></i></a>
              <button onclick="borrarOrden(<?=$row['id_orden_serv']?>)" style="display:inline-flex;align-items:center;padding:6px 8px;background:#FFEBEE;border:1px solid #FFCDD2;border-radius:6px;color:#C62828;font-size:12px;cursor:pointer" title="Eliminar"><i class="fas fa-trash"></i></button>
            </td>
            <?php endif; ?>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
        <?php else: ?>
        <div class="empty-state"><i class="fas fa-inbox"></i><p>Sin órdenes registradas.</p></div>
        <?php endif; ?>
      </div>
    </div>
  <?php elseif($vista==="clientes"): ?>
    <div class="table-panel">
      <div class="table-header">
        <i class="fas fa-users" style="color:var(--acento);font-size:18px"></i>
        <span class="table-title">Clientes TEC</span>
        <span class="table-badge"><?=count($datos)?> registros</span>
        <input type="text" class="table-search" placeholder="🔍  Buscar..." onkeyup="filtrar(this)">
        <?php if($rol==='ADMINISTRADOR'): ?>
        <button onclick="cliAbrirModal()" class="ant-btn-add" style="background:linear-gradient(135deg,#1565C0,#29B6F6)">
          <i class="fas fa-plus"></i> Nuevo Cliente
        </button>
        <?php endif; ?>
      </div>
      <div class="table-wrap">
        <?php if($datos): ?>
        <table id="miTabla">
          <thead><tr>
            <th>ID</th><th>Nombre</th><th>Teléfono</th><th>Email</th><th>Empresa</th><th>Sucursal</th><th>Alta</th>
            <?php if($rol==='ADMINISTRADOR'): ?><th>Acciones</th><?php endif; ?>
          </tr></thead>
          <tbody>
          <?php foreach($datos as $r): ?>
          <tr>
            <td style="font-weight:700;color:var(--azul)"><?=$r['id_cliente']?></td>
            <td style="font-weight:600"><?=htmlspecialchars(mb_strimwidth($r['nombre_cliente_completo']??'—',0,28,'…'))?></td>
            <td><?=htmlspecialchars($r['telefono']??'—')?></td>
            <td><?=htmlspecialchars(mb_strimwidth($r['email_cliente']??'—',0,24,'…'))?></td>
            <td><?=htmlspecialchars(mb_strimwidth($r['empresa_ref_cliente']??'—',0,20,'…'))?></td>
            <td style="font-size:12px;color:var(--muted)"><?=htmlspecialchars($r['sucursal']??'—')?></td>
            <td style="font-size:11px;color:var(--muted)"><?=htmlspecialchars(substr($r['fecha_alta_cliente']??'',0,10))?></td>
            <?php if($rol==='ADMINISTRADOR'): ?>
            <td style="white-space:nowrap">
              <button onclick="cliEditar(<?=$r['id_cliente']?>,'<?=addslashes($r['nombre_cliente_completo']??'')?>', '<?=addslashes($r['telefono']??'')?>', '<?=addslashes($r['email_cliente']??'')?>', '<?=addslashes($r['empresa_ref_cliente']??'')?>')"
                class="ant-btn-sec ant-btn-sm" style="margin-right:4px"><i class="fas fa-edit"></i> Editar</button>
              <button onclick="cliBorrar(<?=$r['id_cliente']?>,'<?=addslashes($r['nombre_cliente_completo']??'')?>')"
                class="ant-btn-sec ant-btn-sm ant-btn-danger"><i class="fas fa-trash"></i></button>
            </td>
            <?php endif; ?>
          </tr>
          <?php endforeach; ?>
          </tbody>
        </table>
        <?php else: ?>
        <div class="empty-state"><i class="fas fa-users"></i><p>Sin clientes registrados.</p>
          <?php if($rol==='ADMINISTRADOR'): ?>
          <button onclick="cliAbrirModal()" class="ant-btn-add" style="margin-top:14px"><i class="fas fa-plus"></i> Agregar primero</button>
          <?php endif; ?>
        </div>
        <?php endif; ?>
      </div>
    </div>

  <?php else: ?>
    <div class="empty-state"><i class="fas fa-inbox"></i><p>Sin registros.</p></div>
  <?php endif; ?>

  </div><!-- /content -->
</div><!-- /main -->

<!-- LIGHTBOX -->
<div class="ant-lb" id="antLb" onclick="this.classList.remove('open')">
  <button class="ant-lb-x">✕</button>
  <img id="antLbImg" src="" alt="">
</div>

<!-- MODAL AGREGAR ANTICIPO -->
<div class="ant-overlay" id="antModal">
<div class="ant-modal" style="width:760px">
  <div class="ant-modal-title"><i class="fas fa-dollar-sign"></i> Registrar Anticipo de Revisión</div>
  <form method="POST" action="?vista=anticipo" id="antForm">
    <input type="hidden" name="_action" value="guardar_anticipo">
    <input type="hidden" name="imagen_ticket" id="antHImg">
    <input type="hidden" name="folio_de_ticket" id="antHFolio">
    <input type="hidden" name="total_pagado" id="antHTotal">
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:18px;align-items:start" class="ant-modal-grid">
      <!-- IZQ: imagen -->
      <div>
        <label class="ant-lbl">Imagen del Ticket <span style="color:#dc2626">*</span></label>
        <div class="ant-uz" id="antUz" ondragover="antEv(event)" ondragleave="antUnev()" ondrop="antDrop(event)">
          <i class="fas fa-camera" style="font-size:34px"></i>
          <p id="antUzTxt" style="font-size:13px;font-weight:600;color:var(--muted);margin-top:6px">📷 Toque para <b style="color:var(--azul)">tomar foto</b></p>
          <p style="font-size:10px;color:var(--muted);margin-top:3px">JPG · PNG · WEBP</p>
          <input type="file" id="antFilInp" accept="image/*" capture="environment" onchange="antCargar(this)">
        </div>
        <div id="antPrevBox" style="display:none;border-radius:10px;overflow:hidden;border:2px solid #D6ECFF;margin-top:10px">
          <img id="antPrevImg" src="" alt="" style="width:100%;max-height:220px;object-fit:contain;background:#F0F8FF;display:block">
          <div style="display:flex;gap:6px;padding:8px;border-top:1px solid #E3F0FF;background:#F8FBFF;flex-wrap:wrap">
            <button type="button" onclick="document.getElementById('antFilInp').click()" class="ant-btn-sec ant-btn-sm"><i class="fas fa-camera"></i> Cambiar</button>
            <button type="button" onclick="antQuitar()" class="ant-btn-sec ant-btn-sm ant-btn-danger"><i class="fas fa-trash"></i></button>
            <button type="button" onclick="antReOCR()" class="ant-btn-sec ant-btn-sm" id="antBtnR" style="display:none"><i class="fas fa-redo"></i> Re-OCR</button>
          </div>
        </div>
        <div class="ant-ocr-p" id="antOcrP" style="margin-top:8px">
          <div class="ant-ocr-track"><div class="ant-ocr-fill" id="antOcrF"></div></div>
          <div class="ant-ocr-step" id="antOcrS">Iniciando...</div>
        </div>
      </div>
      <!-- DER: datos + campos -->
      <div>
        <div class="ant-ocr-r" id="antOcrR">
          <div style="font-size:10px;font-weight:800;color:var(--muted);text-transform:uppercase;letter-spacing:1px;margin-bottom:9px">🤖 Detectado automáticamente</div>
          <div class="ant-ocr-2c">
            <div class="ant-ocr-d" style="border-color:#a7f3d0"><div class="ant-ocr-d-l">🎫 Folio</div><div class="ant-ocr-d-v" style="color:#059669" id="antOFol">—</div></div>
            <div class="ant-ocr-d" style="border-color:#90CAF9"><div class="ant-ocr-d-l">💰 Total</div><div class="ant-ocr-d-v" style="color:var(--azul)" id="antOTot">—</div></div>
          </div>
        </div>
        <div class="ant-fg">
          <label class="ant-lbl" style="display:flex;align-items:center;justify-content:space-between">
            Folio del Ticket <span style="color:#dc2626">*</span>
            <?php if($rol==='ADMINISTRADOR'): ?><span style="font-size:9px;color:var(--acento);font-weight:700">✎ ADMIN: editable</span><?php endif; ?>
          </label>
          <input type="text" id="antInF" class="ant-inp ant-inp-xl" placeholder="000000" maxlength="10"
                 oninput="antValidarTk(this.value)" autocomplete="off"
                 <?php if($rol!=='ADMINISTRADOR'): ?>readonly style="font-size:26px;font-weight:800;text-align:center;letter-spacing:4px;color:var(--azul);background:#F0F8FF;cursor:not-allowed"<?php endif; ?>>
          <div class="ant-tk" id="antTkS"><i id="antTkI" style="flex-shrink:0;font-size:15px"></i><span id="antTkM"></span></div>
          <button type="button" id="antBtnManual" onclick="antForzarValido()" style="display:none;margin-top:6px;font-size:11px;color:var(--azul);background:none;border:1px solid var(--borde);border-radius:6px;padding:4px 10px;cursor:pointer">✓ Es ticket nuevo, continuar</button>
        </div>
        <div class="ant-fg">
          <label class="ant-lbl" style="display:flex;align-items:center;justify-content:space-between">
            Total Pagado ($) <span style="color:#dc2626">*</span>
            <?php if($rol==='ADMINISTRADOR'): ?><span style="font-size:9px;color:var(--acento);font-weight:700">✎ ADMIN: editable</span><?php endif; ?>
          </label>
          <input type="number" id="antInT" class="ant-inp" placeholder="0" min="0" step="1"
                 style="font-size:24px;font-weight:800;text-align:center;color:#059669<?php if($rol!=='ADMINISTRADOR'):?>;background:#F0F8FF;cursor:not-allowed<?php endif;?>"
                 oninput="document.getElementById('antHTotal').value=this.value;antActBtn()"
                 <?php if($rol!=='ADMINISTRADOR'):?>readonly<?php endif;?>>
          <?php if($rol!=='ADMINISTRADOR'): ?>
          <p style="font-size:10px;color:var(--muted);margin-top:4px;text-align:center">🔒 Solo el OCR puede modificar estos campos</p>
          <?php endif; ?>
        </div>
        <div style="background:#F0F8FF;border:1px solid var(--borde);border-radius:8px;padding:10px 14px;font-size:12px;color:var(--muted)">
          <div><i class="fas fa-user" style="color:var(--acento);margin-right:6px"></i><b><?=htmlspecialchars($usuario)?></b> · <?=htmlspecialchars($sucursal)?></div>
          <div style="margin-top:4px"><i class="fas fa-clock" style="color:var(--acento);margin-right:6px"></i><?=date('d/m/Y H:i')?></div>
        </div>
      </div>
    </div>
    <div class="ant-modal-foot">
      <button type="button" class="ant-btn-sec" onclick="antCerrar()"><i class="fas fa-times"></i> Cancelar</button>
      <button type="submit" class="ant-btn-pri" id="antBtnG" disabled><i class="fas fa-save"></i> Guardar Anticipo</button>
    </div>
  </form>
</div>
</div>

<?php if($rol==='ADMINISTRADOR'): ?>
<!-- MODAL EDITAR -->
<div class="ant-overlay" id="antModalEdit">
<div class="ant-modal" style="max-width:440px">
  <div class="ant-modal-title"><i class="fas fa-edit"></i> Editar Anticipo</div>
  <form method="POST" action="?vista=anticipo">
    <input type="hidden" name="_action" value="editar_anticipo">
    <input type="hidden" name="id_anticipo" id="editId">
    <div class="ant-fg"><label class="ant-lbl">Folio del Ticket</label><input type="text" name="folio_de_ticket" id="editFolio" class="ant-inp ant-inp-xl" maxlength="10"></div>
    <div class="ant-fg"><label class="ant-lbl">Total Pagado ($)</label><input type="number" name="total_pagado" id="editTotal" class="ant-inp" min="0" step="1" style="font-size:22px;font-weight:800;text-align:center;color:#059669"></div>
    <div class="ant-fg"><label class="ant-lbl">Estatus</label><select name="estatus" id="editEstatus" class="ant-inp"><option value="DISPONIBLE">DISPONIBLE</option><option value="USADO">USADO</option></select></div>
    <div class="ant-modal-foot">
      <button type="button" class="ant-btn-sec" onclick="document.getElementById('antModalEdit').classList.remove('open')"><i class="fas fa-times"></i> Cancelar</button>
      <button type="submit" class="ant-btn-pri"><i class="fas fa-save"></i> Guardar Cambios</button>
    </div>
  </form>
</div>
</div>
<!-- MODAL BORRAR -->
<div class="ant-overlay" id="antModalDel">
<div class="ant-modal" style="max-width:400px">
  <div class="ant-modal-title" style="color:#dc2626"><i class="fas fa-exclamation-triangle"></i> Confirmar Eliminación</div>
  <p style="color:var(--muted);font-size:14px;margin-bottom:20px">¿Eliminar el anticipo <strong id="delFolioTxt"></strong>? Esta acción no se puede deshacer.</p>
  <form method="POST" action="?vista=anticipo">
    <input type="hidden" name="_action" value="borrar_anticipo">
    <input type="hidden" name="id_anticipo" id="delId">
    <div class="ant-modal-foot">
      <button type="button" class="ant-btn-sec" onclick="document.getElementById('antModalDel').classList.remove('open')"><i class="fas fa-times"></i> Cancelar</button>
      <button type="submit" class="ant-btn-pri" style="background:#dc2626"><i class="fas fa-trash"></i> Sí, eliminar</button>
    </div>
  </form>
</div>
</div>
<?php endif; ?>

<!-- MODAL NUEVO/EDITAR CLIENTE -->
<?php if($rol==='ADMINISTRADOR'): ?>
<div class="ant-overlay" id="cliModal">
<div class="ant-modal" style="max-width:480px">
  <div class="ant-modal-title" id="cliModalTitle"><i class="fas fa-user-plus"></i> Nuevo Cliente</div>
  <form method="POST" action="?vista=clientes" id="cliForm">
    <input type="hidden" name="_action" id="cliAction" value="guardar_cliente">
    <input type="hidden" name="id_cliente" id="cliId">
    <div class="ant-fg"><label class="ant-lbl">Nombre Completo <span style="color:#dc2626">*</span></label>
      <input type="text" name="nombre_cliente_completo" id="cliNom" class="ant-inp" placeholder="Nombre y apellidos" required></div>
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:14px">
      <div class="ant-fg"><label class="ant-lbl">Teléfono</label>
        <input type="text" name="telefono" id="cliTel" class="ant-inp" placeholder="614-000-0000"></div>
      <div class="ant-fg"><label class="ant-lbl">Email</label>
        <input type="text" name="email_cliente" id="cliEml" class="ant-inp" placeholder="correo@ejemplo.com"></div>
    </div>
    <div class="ant-fg"><label class="ant-lbl">Empresa / Referencia</label>
      <input type="text" name="empresa_ref_cliente" id="cliEmp" class="ant-inp" placeholder="Empresa o cómo nos conoció"></div>
    <div class="ant-modal-foot">
      <button type="button" class="ant-btn-sec" onclick="document.getElementById('cliModal').classList.remove('open')"><i class="fas fa-times"></i> Cancelar</button>
      <button type="submit" class="ant-btn-pri"><i class="fas fa-save"></i> Guardar Cliente</button>
    </div>
  </form>
</div>
</div>
<!-- MODAL BORRAR CLIENTE -->
<div class="ant-overlay" id="cliModalDel">
<div class="ant-modal" style="max-width:400px">
  <div class="ant-modal-title" style="color:#dc2626"><i class="fas fa-exclamation-triangle"></i> Eliminar Cliente</div>
  <p style="color:var(--muted);font-size:14px;margin-bottom:20px">¿Eliminar al cliente <strong id="cliDelNom"></strong>? Esta acción no se puede deshacer.</p>
  <form method="POST" action="?vista=clientes">
    <input type="hidden" name="_action" value="borrar_cliente">
    <input type="hidden" name="id_cliente" id="cliDelId">
    <div class="ant-modal-foot">
      <button type="button" class="ant-btn-sec" onclick="document.getElementById('cliModalDel').classList.remove('open')"><i class="fas fa-times"></i> Cancelar</button>
      <button type="submit" class="ant-btn-pri" style="background:#dc2626"><i class="fas fa-trash"></i> Sí, eliminar</button>
    </div>
  </form>
</div>
</div>
<?php endif; ?>

<script src="https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js"></script>
<script>
function toggleMenu(btn){btn.classList.toggle("open");btn.classList.toggle("active");btn.nextElementSibling.classList.toggle("open")}
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 filtrar(input){const q=input.value.toLowerCase();document.querySelectorAll("#miTabla tbody tr").forEach(tr=>{tr.style.display=tr.textContent.toLowerCase().includes(q)?"":"none"})}
function borrarOrden(id){if(!confirm('¿Eliminar la orden OS-'+String(id).padStart(6,'0')+'? No se puede deshacer.'))return;const f=document.createElement('form');f.method='POST';f.action='borrar_orden.php';const inp=document.createElement('input');inp.type='hidden';inp.name='id';inp.value=id;f.appendChild(inp);document.body.appendChild(f);f.submit()}
function verLb(src){document.getElementById('antLbImg').src=src;document.getElementById('antLb').classList.add('open')}

let antTkV=false,antImgL=false,antDeb,antUFile=null,antManualTimer;
function abrirModal(){document.getElementById('antModal').classList.add('open');antReset()}
function antCerrar(){document.getElementById('antModal').classList.remove('open')}
document.getElementById('antModal').addEventListener('click',function(e){if(e.target===this)antCerrar()})
function antReset(){
  antTkV=false;antImgL=false;antUFile=null;
  ['antFilInp','antInF','antInT'].forEach(id=>{const el=document.getElementById(id);if(el)el.value=''});
  ['antHImg','antHFolio','antHTotal'].forEach(id=>{const el=document.getElementById(id);if(el)el.value=''});
  document.getElementById('antUz').className='ant-uz';
  document.getElementById('antUzTxt').innerHTML='📷 Toque para <b style="color:var(--azul)">tomar foto</b>';
  document.getElementById('antPrevBox').style.display='none';
  document.getElementById('antOcrP').style.display='none';
  document.getElementById('antOcrR').style.display='none';
  document.getElementById('antTkS').className='ant-tk';
  document.getElementById('antInF').className='ant-inp ant-inp-xl';
  document.getElementById('antBtnG').disabled=true;
  document.getElementById('antBtnR').style.display='none';
  document.getElementById('antBtnManual').style.display='none';
}
function antEv(e){e.preventDefault();document.getElementById('antUz').classList.add('over')}
function antUnev(){document.getElementById('antUz').classList.remove('over')}
function antDrop(e){e.preventDefault();antUnev();const f=e.dataTransfer.files[0];if(f){const dt=new DataTransfer();dt.items.add(f);document.getElementById('antFilInp').files=dt.files;antCargar({files:[f]})}}
function antCargar(input){
  const file=input.files?.[0];if(!file)return;antUFile=file;
  const reader=new FileReader();
  reader.onload=e=>{
    document.getElementById('antPrevImg').src=e.target.result;
    document.getElementById('antHImg').value=e.target.result;
    document.getElementById('antPrevBox').style.display='block';
    document.getElementById('antUz').className='ant-uz has';
    document.getElementById('antUzTxt').textContent='✅ Imagen cargada — analizando...';
    document.getElementById('antOcrR').style.display='none';
    antImgL=true;antLanzarOCR(file);
  };reader.readAsDataURL(file);
}
function antQuitar(){
  antImgL=false;antTkV=false;antUFile=null;
  ['antFilInp','antInF','antInT','antHImg','antHFolio','antHTotal'].forEach(id=>{const el=document.getElementById(id);if(el)el.value=''});
  document.getElementById('antPrevBox').style.display='none';
  document.getElementById('antUz').className='ant-uz';
  document.getElementById('antUzTxt').innerHTML='📷 Toque para <b style="color:var(--azul)">tomar foto</b>';
  document.getElementById('antOcrP').style.display='none';
  document.getElementById('antOcrR').style.display='none';
  document.getElementById('antTkS').className='ant-tk';
  document.getElementById('antBtnR').style.display='none';
  antActBtn();
}
function antReOCR(){if(antUFile)antLanzarOCR(antUFile)}
function antLanzarOCR(file){
  document.getElementById('antOcrP').style.display='block';
  document.getElementById('antOcrR').style.display='none';
  antSetB(5);antSetS('Cargando OCR...');
  Tesseract.recognize(file,'spa+eng',{logger:m=>{
    if(m.status==='loading tesseract core'){antSetB(10);antSetS('Cargando Tesseract...')}
    if(m.status==='loading language traineddata'){antSetB(30);antSetS('Cargando idioma...')}
    if(m.status==='recognizing text'){antSetB(30+Math.round(m.progress*65));antSetS('Reconociendo... '+Math.round(m.progress*100)+'%')}
  }}).then(({data:{text}})=>{document.getElementById('antOcrP').style.display='none';antProcesarOCR(text)})
  .catch(()=>{document.getElementById('antOcrP').style.display='none';document.getElementById('antBtnR').style.display='inline-flex'});
}
function antSetB(p){document.getElementById('antOcrF').style.width=p+'%'}
function antSetS(t){document.getElementById('antOcrS').textContent=t}
function antProcesarOCR(texto){
  let folio='',total='';
  let m=texto.match(/[Tt]icket\s*[:#]\s*#?\s*(\d{4,9})/);
  if(m){const n=m[1];folio=n.length>6?n.slice(-6):n}
  if(!folio){m=texto.match(/#\s*(\d{6})\b/);if(m)folio=m[1]}
  if(!folio){m=texto.match(/\b(\d{6})\b/);if(m)folio=m[1]}
  let mT=texto.match(/PAGADO\s*[:\s]*\$?\s*([\d,]+(?:\.\d{0,2})?)\s*(?:MXN)?/i);
  if(mT)total=Math.floor(parseFloat(mT[1].replace(/,/g,''))).toString();
  if(!total){mT=texto.match(/TOTAL\s*[:\s]*\$?\s*([\d,]+(?:\.\d{0,2})?)/i);if(mT)total=Math.floor(parseFloat(mT[1].replace(/,/g,''))).toString()}
  if(folio||total){
    document.getElementById('antOcrR').style.display='block';
    document.getElementById('antOFol').textContent=folio||'No detectado';
    document.getElementById('antOTot').textContent=total?'$'+total:'No detectado';
    if(folio){document.getElementById('antInF').value=folio;antValidarTk(folio)}
    if(total){document.getElementById('antInT').value=total;document.getElementById('antHTotal').value=total}
    document.getElementById('antBtnR').style.display='inline-flex';
  }else{document.getElementById('antBtnR').style.display='inline-flex'}
}
function antValidarTk(val){
  clearTimeout(antDeb);clearTimeout(antManualTimer);val=val.trim();
  const ts=document.getElementById('antTkS'),ico=document.getElementById('antTkI'),msg=document.getElementById('antTkM'),inp=document.getElementById('antInF');
  document.getElementById('antBtnManual').style.display='none';
  if(!val){ts.className='ant-tk';inp.className='ant-inp ant-inp-xl';antTkV=false;antActBtn();return}
  ts.className='ant-tk show ant-tk-chk';ico.className='fas fa-spinner ant-spin';msg.textContent='Verificando...';antTkV=false;antActBtn();
  antManualTimer=setTimeout(()=>{if(!antTkV)document.getElementById('antBtnManual').style.display='block'},3000);
  document.getElementById('antHFolio').value=val;
  antDeb=setTimeout(()=>{
    fetch('?vista=anticipo&action=validar_ticket&folio='+encodeURIComponent(val))
      .then(r=>r.text()).then(txt=>{
        let d;try{d=JSON.parse(txt)}catch(e){antForzarValido();return}
        if(d.status==='disponible'){ts.className='ant-tk show ant-tk-ok';ico.className='fas fa-check-circle';msg.textContent='✓ Ticket disponible';inp.className='ant-inp ant-inp-xl ok';antTkV=true}
        else if(d.status==='duplicado'){ts.className='ant-tk show ant-tk-err';ico.className='fas fa-times-circle';msg.innerHTML='⛔ '+d.msg;inp.className='ant-inp ant-inp-xl err';antTkV=false}
        antActBtn();
      }).catch(()=>{antTkV=true;antActBtn()});
  },450);
}
function antForzarValido(){
  antTkV=true;
  document.getElementById('antTkS').className='ant-tk show ant-tk-ok';
  document.getElementById('antTkI').className='fas fa-check-circle';
  document.getElementById('antTkM').textContent='✓ Ticket marcado como disponible';
  document.getElementById('antInF').className='ant-inp ant-inp-xl ok';
  document.getElementById('antBtnManual').style.display='none';
  antActBtn();
}
function antActBtn(){
  const f=document.getElementById('antInF').value.trim();
  const t=document.getElementById('antInT').value.trim();
  const i=document.getElementById('antHImg').value;
  document.getElementById('antBtnG').disabled=!(antTkV&&f&&t&&i);
}
function antEditar(id,folio,total,estatus){
  document.getElementById('editId').value=id;
  document.getElementById('editFolio').value=folio.trim();
  document.getElementById('editTotal').value=total.trim();
  const sel=document.getElementById('editEstatus');
  if(sel)[...sel.options].forEach(o=>{o.selected=o.value===estatus.trim()});
  document.getElementById('antModalEdit').classList.add('open');
}
function antBorrar(id,folio){
  document.getElementById('delId').value=id;
  document.getElementById('delFolioTxt').textContent='#'+folio;
  document.getElementById('antModalDel').classList.add('open');
}
document.getElementById('antForm').addEventListener('submit',function(e){
  if(!document.getElementById('antHImg').value){e.preventDefault();alert('Suba la imagen del ticket.');return}
  if(!antTkV){e.preventDefault();alert('Folio no válido o ya registrado.');return}
  if(!document.getElementById('antInT').value){e.preventDefault();alert('Ingrese el total.');return}
});

function cliAbrirModal(){
  document.getElementById('cliModalTitle').innerHTML='<i class="fas fa-user-plus"></i> Nuevo Cliente';
  document.getElementById('cliAction').value='guardar_cliente';
  document.getElementById('cliId').value='';
  ['cliNom','cliTel','cliEml','cliEmp'].forEach(id=>{const el=document.getElementById(id);if(el)el.value='';});
  document.getElementById('cliModal').classList.add('open');
}
function cliEditar(id,nom,tel,eml,emp){
  document.getElementById('cliModalTitle').innerHTML='<i class="fas fa-edit"></i> Editar Cliente';
  document.getElementById('cliAction').value='editar_cliente';
  document.getElementById('cliId').value=id;
  document.getElementById('cliNom').value=nom;
  document.getElementById('cliTel').value=tel;
  document.getElementById('cliEml').value=eml;
  document.getElementById('cliEmp').value=emp;
  document.getElementById('cliModal').classList.add('open');
}
function cliBorrar(id,nom){
  document.getElementById('cliDelId').value=id;
  document.getElementById('cliDelNom').textContent=nom;
  document.getElementById('cliModalDel').classList.add('open');
}
</script>
<?php include __DIR__."/theme.php"; ?>
</body>
</html>