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

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

// ── ANTICIPO AJAX: validar ticket ─────────────────────────
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 correctamente.";
        }catch(PDOException $e){ $msgErr='Error: '.$e->getMessage(); }
    }
}

// Tabla activa
$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 ordenes_de_servicio ORDER BY id_orden_serv 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;--acento2:#00E5FF;
  --fondo:#EBF5FF;--sidebar:#0D1B30;--sidebar2:#152338;
  --texto:#0D2A4A;--muted:#5A7FA8;--borde:#90CAF9;
  --blanco:#FFFFFF;--hover:#1A2F4A;
  --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 cubic-bezier(.16,1,.3,1);}
.sidebar-logo{padding:22px 20px 18px;border-bottom:1px solid rgba(41,182,246,.1);display:flex;align-items:center;gap:12px;}
.sidebar-logo img{height:38px;width:auto;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:14px 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-info-sb{flex:1;min-width: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:16px 0;overflow-y:auto}
.nav-label{font-family:"Exo 2",sans-serif;font-size:9px;font-weight:700;letter-spacing:2.5px;text-transform:uppercase;color:rgba(144,202,249,.35);padding:12px 20px 6px;}
.menu-item{position:relative}
.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:var(--hover);color:#fff}
.menu-btn.active{background:rgba(41,182,246,.12);color:var(--acento)}
.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;transition:background .15s;}
.menu-btn:hover .icon,.menu-btn.active .icon{background:rgba(41,182,246,.2)}
.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)}
.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);}
.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;font-weight:500;text-decoration:none;transition:background .15s,color .15s;font-family:"Inter",sans-serif;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:14px 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;letter-spacing:1px;}
.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 span{color:var(--acento)}
.topbar-breadcrumb{font-size:12px;color:var(--muted);margin-left:auto;display:flex;align-items:center;gap:6px}
.topbar-breadcrumb i{font-size:10px;color:var(--acento)}
.hamburger{display:none;background:none;border:none;cursor:pointer;color:var(--azul);font-size:20px;margin-right:8px}
.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;}
.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;letter-spacing:.5px}
.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:18px 24px;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;}
.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}
.overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);z-index:99}

/* ── ANTICIPO STYLES ── */
.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:10px 20px;border-radius:10px;background:var(--azul);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{background:var(--azul2);box-shadow:0 5px 18px rgba(21,101,192,.35);}
.ant-btn-add i{font-size:13px;}
.ant-thumb{width:42px;height:42px;object-fit:cover;border-radius:6px;border:1px solid #D6ECFF;cursor:pointer;}
/* Modal */
.ant-overlay{display:none;position:fixed;inset:0;background:rgba(0,0,0,.5);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:560px;max-width:100%;max-height:92vh;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;}
.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;}
/* Upload zone */
.ant-uz{border:3px dashed var(--borde);border-radius:14px;padding:34px 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:40px;color:var(--muted);margin-bottom:10px;display:block;}
.ant-uz:hover i,.ant-uz.has i{color:var(--azul);}
.ant-uz input[type=file]{position:absolute;inset:0;opacity:0;cursor:pointer;width:100%;height:100%;}
.ant-prev-box{display:none;margin-top:13px;border-radius:10px;overflow:hidden;border:2px solid #D6ECFF;}
.ant-prev-box img{width:100%;max-height:230px;object-fit:contain;background:#F0F8FF;display:block;}
.ant-prev-ctrl{display:flex;gap:7px;padding:9px;border-top:1px solid #E3F0FF;background:#F8FBFF;}
/* OCR */
.ant-ocr-p{display:none;margin-top:11px;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-top:11px;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-modal-grid{display:grid;grid-template-columns:1fr 1fr;gap:18px;align-items:start;}
@media(max-width:600px){.ant-modal-grid{grid-template-columns:1fr;}.ant-modal{width:100%!important;}}
/* Ticket status */
.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;}
/* Lightbox */
.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;}
.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;}
@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;}
}
</style>
</head>
<body>

<div class="overlay" id="overlay" onclick="closeSidebar()"></div>

<!-- SIDEBAR -->
<aside class="sidebar" id="sidebar">
  <div class="sidebar-logo">
    <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAABGdBTUEAALGPC/xhBQAAACBjSFJNAAB6JgAAgIQAAPoAAACA6AAAdTAAAOpgAAA6mAAAF3CculE8AAAABmJLR0QA/wD/AP+gvaeTAAAAB3RJTUUH6AQQCgYXUMaSegAAABl0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAAAVSURBVGje7cEBDQAAAMKg909tDjdhAAMBAAAAAAAAAgB/AAFAAAAAAElFTkSuQmCC" alt="V" style="height:32px;width:32px;border-radius:6px;background:var(--azul);display:flex;align-items:center;justify-content:center;">
    <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 class="user-info-sb">
      <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 class="menu-item">
      <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>

<!-- MAIN -->
<div class="main">
  <div class="topbar">
    <button class="hamburger" onclick="toggleSidebar()"><i class="fas fa-bars"></i></button>
    <div class="topbar-title">PROCEIN <span>2026</span> 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): ?>
    <!-- BIENVENIDA -->
    <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" style="text-decoration:none"><div 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></div></a>
      <a href="?vista=clientes" style="text-decoration:none"><div 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></div></a>
      <a href="?vista=anticipo" style="text-decoration:none"><div 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></div></a>
    </div>

    <?php elseif($vista==="anticipo"): ?>
    <!-- ═══════════════════════════════════ -->
    <!-- VISTA ANTICIPO REVISIÓN (COMPLETA)  -->
    <!-- ═══════════════════════════════════ -->
    <?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)">
        <!-- BOTÓN AGREGAR -->
        <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 Pagado</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='.2'"><?php else:?>🎫<?php endif;?></td>
            <td><span style="font-size:17px;font-weight:800;color:var(--azul);letter-spacing:2px">#<?=htmlspecialchars($a['folio_de_ticket']??'—')?></span></td>
            <td><span style="font-size:15px;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 style="font-size:12px"><?=!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)">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 else: ?>
    <!-- OTRAS VISTAS (genérica) -->
    <div class="table-panel">
      <div class="table-header">
        <i class="fas <?=$vista==="clientes"?"fa-users":"fa-file-alt"?>" style="color:var(--acento);font-size:18px"></i>
        <span class="table-title"><?=htmlspecialchars($titulo)?></span>
        <span class="table-badge"><?=count($datos)?> registros</span>
        <input type="text" class="table-search" placeholder="🔍  Buscar..." onkeyup="filtrar(this)">
      </div>
      <div class="table-wrap">
        <?php if($datos): ?>
        <table id="miTabla">
          <thead><tr><?php foreach($cols as $c): ?><th><?=htmlspecialchars(str_replace("_"," ",$c))?></th><?php endforeach;?></tr></thead>
          <tbody>
          <?php foreach($datos as $row): ?>
          <tr><?php foreach($cols as $c): ?><td title="<?=htmlspecialchars($row[$c]??"")?>"><?=htmlspecialchars(mb_strimwidth($row[$c]??'—',0,30,'…'))?></td><?php endforeach;?></tr>
          <?php endforeach; ?>
          </tbody>
        </table>
        <?php else: ?>
        <div class="empty-state"><i class="fas fa-inbox"></i><p>Sin registros en esta tabla.</p></div>
        <?php endif; ?>
      </div>
    </div>
    <?php endif; ?>
  </div>
</div>

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

<!-- MODAL EDITAR ANTICIPO (solo ADMIN) -->
<?php if($rol==='ADMINISTRADOR'): ?>
<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" id="antFormEdit">
    <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" style="font-size:14px">
        <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 CONFIRMAR 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">¿Está seguro de 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 AGREGAR ANTICIPO -->
<div class="ant-overlay" id="antModal">
<div class="ant-modal" style="width:780px">
  <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">

    <!-- LAYOUT 2 COLUMNAS: imagen izq | datos der -->
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:18px;align-items:start">

      <!-- COL IZQ: imagen -->
      <div>
        <label class="ant-lbl">Imagen del Ticket <span style="color:#dc2626">*</span></label>
        <!-- Zona upload (se oculta cuando hay imagen) -->
        <div class="ant-uz" id="antUz" ondragover="antEv(event)" ondragleave="antUnev()" ondrop="antDrop(event)" style="padding:24px 16px">
          <i class="fas fa-camera" style="font-size:32px"></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>
        <!-- Preview -->
        <div id="antPrevBox" style="display:none;border-radius:10px;overflow:hidden;border:2px solid #D6ECFF;">
          <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> OCR</button>
          </div>
        </div>
        <!-- OCR progress -->
        <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 class="ant-ocr-w" id="antOcrW" style="margin-top:8px">⚠️ <span id="antOcrWM"></span></div>
      </div>

      <!-- COL DER: datos detectados + campos -->
      <div>
        <!-- OCR resultado -->
        <div class="ant-ocr-r" id="antOcrR" style="margin-bottom:14px">
          <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>

        <!-- Folio -->
        <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">✓ El ticket es nuevo, continuar</button>
        </div>

        <!-- Total -->
        <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>

        <!-- Info usuario -->
        <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><!-- /grid -->

    <div class="ant-modal-foot" style="margin-top:16px">
      <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>

<script src="https://cdn.jsdelivr.net/npm/tesseract.js@5/dist/tesseract.min.js"></script>
<script>
// ── Sidebar ──────────────────────────────────────────────
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 verLb(src){document.getElementById('antLbImg').src=src;document.getElementById('antLb').classList.add('open');}

// ── Modal anticipo ────────────────────────────────────────
let antTkV=false,antImgL=false,antDeb,antUFile=null;
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 o seleccionar</b>';
    document.getElementById('antPrevBox').style.display='none';
    document.getElementById('antOcrP').style.display='none';
    document.getElementById('antOcrR').style.display='none';
    document.getElementById('antOcrW').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';
}

// Drag & Drop
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]});}}

// Cargar imagen
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 con OCR...';
        document.getElementById('antOcrR').style.display='none';
        document.getElementById('antOcrW').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 o seleccionar</b>';
    document.getElementById('antOcrP').style.display='none';
    document.getElementById('antOcrR').style.display='none';
    document.getElementById('antOcrW').style.display='none';
    document.getElementById('antTkS').className='ant-tk';
    document.getElementById('antInF').className='ant-inp ant-inp-xl';
    document.getElementById('antBtnR').style.display='none';
    antActBtn();
}
function antReOCR(){if(antUFile)antLanzarOCR(antUFile);}

// OCR
function antLanzarOCR(file){
    document.getElementById('antOcrP').style.display='block';
    document.getElementById('antOcrR').style.display='none';
    document.getElementById('antOcrW').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 español...');}
            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';
        console.log('📄 OCR:\n',text);
        antProcesarOCR(text);
    }).catch(err=>{
        document.getElementById('antOcrP').style.display='none';
        antMostWarn('Error OCR. Ingrese datos manualmente.');
        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='';
    // Folio: "Ticket: #238302"
    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];}
    // Total: "PAGADO: $80.00 MXN"
    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;}
        if(!folio||!total)antMostWarn('Algunos datos no detectados. Corrija si es necesario.');
        document.getElementById('antBtnR').style.display='inline-flex';
    }else{antMostWarn('No se detectaron datos. Ingrese manualmente.');document.getElementById('antBtnR').style.display='inline-flex';}
}
function antMostWarn(msg){document.getElementById('antOcrW').style.display='block';document.getElementById('antOcrWM').textContent=msg;}

// Validar ticket
function antValidarTk(val){
    clearTimeout(antDeb);val=val.trim();
    const ts=document.getElementById('antTkS'),ico=document.getElementById('antTkI'),msg=document.getElementById('antTkM'),inp=document.getElementById('antInF');
    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();
    // Mostrar botón manual si tarda más de 3s
    clearTimeout(antManualTimer);
    antManualTimer=setTimeout(()=>{
        if(!antTkV) document.getElementById('antBtnManual').style.display='block';
    },3000);
    document.getElementById('antHFolio').value=val;
    antDeb=setTimeout(()=>{
        fetch('dashboard.php?vista=anticipo&action=validar_ticket&folio='+encodeURIComponent(val))
            .then(r=>{
                if(!r.ok) throw new Error('HTTP '+r.status);
                return r.text();
            })
            .then(txt=>{
                let d;
                try{ d=JSON.parse(txt); }
                catch(e){
                    // Respuesta no es JSON — posiblemente redirect o error PHP
                    console.error('Respuesta no JSON:', txt.substring(0,200));
                    // Asumir disponible para no bloquear
                    ts.className='ant-tk show ant-tk-ok';
                    ico.className='fas fa-check-circle';
                    msg.textContent='✓ Ticket listo (verificación manual)';
                    inp.className='ant-inp ant-inp-xl ok';antTkV=true;
                    antActBtn(); return;
                }
                ico.className='';ico.style.animation='';
                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;
                }else{
                    ts.className='ant-tk show ant-tk-err';
                    ico.className='fas fa-exclamation-circle';msg.textContent='Error al verificar';antTkV=false;
                }
                antActBtn();
            }).catch(err=>{
                console.error('Fetch error:',err);
                ico.className='fas fa-exclamation-triangle';
                ts.className='ant-tk show ant-tk-chk';
                msg.textContent='No se pudo verificar — revise consola';
                // Habilitar de todas formas si tiene imagen y total
                antTkV=true; antActBtn();
            });
    },450);
}
document.getElementById('antInF').addEventListener('input',function(){document.getElementById('antHFolio').value=this.value;});
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();
}
// Mostrar botón manual si verificación tarda más de 3s
let antManualTimer;
const _origValidarTk = antValidarTk;

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;}
});
</script>
</body>
</html>
