<?php
session_start();
require 'config.php';
if(!isset($_SESSION["usuario"])){header("Location: login.php");exit;}
$usuario=$_SESSION["usuario"];$rol=$_SESSION["rol"];$sucursal=$_SESSION["sucursal"];
$id=(int)($_GET['id']??0);
if(!$id){header("Location: dashboard.php?vista=ordenes");exit;}
$stmt=$pdo->prepare("SELECT * FROM ordenes_de_servicio WHERE id_orden_serv=? LIMIT 1");
$stmt->execute([$id]);$orden=$stmt->fetch();
if(!$orden){header("Location: dashboard.php?vista=ordenes");exit;}
$eq=$pdo->prepare("SELECT * FROM refequipo WHERE id_orden_serv=? LIMIT 1");
$eq->execute([$id]);$equipo=$eq->fetch()?:[];
$accs=$pdo->prepare("SELECT * FROM refaccesorios WHERE id_orden_serv=?");
$accs->execute([$id]);$accesorios=$accs->fetchAll();
$yr=date('Y',strtotime($orden['fecha_creacion']??'now'));
$folio=$yr.'-'.str_pad($id,4,'0',STR_PAD_LEFT);

// Colores estado
$colores=['EN REVISION'=>['#FFF8E1','#F57F17'],'SERVICIO COTIZADO'=>['#E3F2FD','#1565C0'],
          'CONFIRMADO'=>['#EDE7F6','#4527A0'],'EN PROCESO'=>['#E8EAF6','#283593'],
          'PAGADO'=>['#E0F2F1','#00695C'],'TERMINADO'=>['#E8F5E9','#2E7D32'],
          'ENTREGADO FINAL'=>['#F9FBE7','#558B2F'],'CANCELADO'=>['#FFEBEE','#C62828']];
$est=strtoupper($orden['estado']??'---');
$ep=isset($colores[$est])?$colores[$est]:['#F5FAFF','#5A7FA8'];

// Helper: muestra campo solo si tiene valor
function campo($lbl,$val,$full=false){
    if($val===null||$val===''||strtolower(trim($val))==='null') return '';
    $cls=$full?'field-card full':'field-card';
    $v=htmlspecialchars($val);
    return "<div class=\"$cls\"><div class=\"field-lbl\">$lbl</div><div class=\"field-val\">$v</div></div>";
}

// Fotos
$fotos=[];
for($f=1;$f<=4;$f++){
    $col='evidencia_recibido_'.$f;
    if(!empty($equipo[$col])) $fotos[]=$equipo[$col];
}
?><!DOCTYPE html>
<html lang="es"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Orden <?=htmlspecialchars($folio)?></title>
<link href="https://fonts.googleapis.com/css2?family=Exo+2:wght@400;600;700;800&family=Inter:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css" rel="stylesheet">
<style>
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0}
:root{--azul:#1565C0;--azul2:#1E88E5;--acento:#29B6F6;--fondo:#EBF5FF;--texto:#0D2A4A;--muted:#5A7FA8;--borde:#C5DDF9;--sidebar-w:230px}
html,body{min-height:100vh;background:var(--fondo);font-family:"Inter",sans-serif;color:var(--texto)}
body{display:flex}
.sidebar{width:var(--sidebar-w);min-height:100vh;background:#0D1B30;position:fixed;left:0;top:0;bottom:0;z-index:100;display:flex;flex-direction:column;box-shadow:4px 0 24px rgba(0,0,0,.25);transition:transform .3s}
.sidebar-logo{padding:18px 16px 14px;border-bottom:1px solid rgba(41,182,246,.1);display:flex;align-items:center;gap:10px}
.sidebar-logo img{height:60px;filter:drop-shadow(0 0 6px rgba(41,182,246,.3))}
.sidebar-logo-text{font-family:"Exo 2",sans-serif;font-size:11px;font-weight:800;color:#fff;line-height:1.3}
.sidebar-logo-text span{color:var(--acento);font-size:9px;letter-spacing:2px;font-weight:600;display:block}
.sidebar-user{padding:10px 14px;background:rgba(41,182,246,.06);border-bottom:1px solid rgba(41,182,246,.08);display:flex;align-items:center;gap:10px}
.user-avatar{width:32px;height:32px;border-radius:50%;background:linear-gradient(135deg,var(--azul),var(--acento));display:flex;align-items:center;justify-content:center;font-family:"Exo 2",sans-serif;font-size:13px;font-weight:800;color:#fff;flex-shrink:0}
.user-name{font-size:11px;font-weight:600;color:#E8F2FF;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.user-role{font-size:9px;color:var(--acento);letter-spacing:1px;text-transform:uppercase;font-weight:600}
.nav{flex:1;padding:10px 0;overflow-y:auto}
.nav-label{font-family:"Exo 2",sans-serif;font-size:9px;font-weight:700;letter-spacing:2px;text-transform:uppercase;color:rgba(144,202,249,.35);padding:8px 14px 4px}
.menu-btn{width:100%;display:flex;align-items:center;gap:9px;padding:10px 14px;background:rgba(41,182,246,.1);border:none;cursor:pointer;color:#fff;font-family:"Exo 2",sans-serif;font-size:12px;font-weight:600;text-align:left}
.menu-btn .icon{width:28px;height:28px;border-radius:7px;background:rgba(41,182,246,.2);display:flex;align-items:center;justify-content:center;font-size:12px;flex-shrink:0}
.submenu{background:rgba(0,0,0,.15)}
.sub-item{display:flex;align-items:center;gap:8px;padding:8px 14px 8px 42px;color:#6A8BAE;font-size:12px;text-decoration:none;border-left:2px solid transparent;margin-left:12px;transition:background .15s}
.sub-item:hover{background:rgba(41,182,246,.07);color:#C5E3FF}
.sub-item.active{color:var(--acento);border-left-color:var(--acento);background:rgba(41,182,246,.08)}
.sub-item i{font-size:10px;width:13px;color:var(--acento);opacity:.7}
.sidebar-footer{padding:10px 12px;border-top:1px solid rgba(41,182,246,.08)}
.logout-btn{width:100%;display:flex;align-items:center;gap:9px;padding:8px 11px;border-radius:8px;background:rgba(220,50,50,.08);border:1px solid rgba(220,50,50,.15);color:#FF7777;font-family:"Exo 2",sans-serif;font-size:11px;font-weight:600;cursor:pointer;text-decoration:none}
.main{margin-left:var(--sidebar-w);flex:1;display:flex;flex-direction:column;min-height:100vh}
.topbar{background:#fff;border-bottom:1px solid #D6ECFF;padding:11px 20px;display:flex;align-items:center;gap:10px;box-shadow:0 2px 10px rgba(21,101,192,.07);position:sticky;top:0;z-index:50;flex-wrap:wrap}
.topbar-title{font-family:"Exo 2",sans-serif;font-size:15px;font-weight:800;color:var(--azul)}
.topbar-title em{color:var(--acento);font-style:normal}
.btn-volver{display:inline-flex;align-items:center;gap:6px;padding:7px 13px;border-radius:8px;background:#EBF5FF;border:1px solid var(--borde);color:var(--azul);font-size:12px;font-weight:600;text-decoration:none;font-family:"Exo 2",sans-serif;margin-left:auto}
.btn-editar{display:inline-flex;align-items:center;gap:6px;padding:7px 14px;border-radius:8px;background:linear-gradient(135deg,var(--azul),var(--azul2));color:#fff;font-size:12px;font-weight:700;text-decoration:none;font-family:"Exo 2",sans-serif;box-shadow:0 3px 10px rgba(21,101,192,.25);border:none}
.hamburger{display:none;background:none;border:none;cursor:pointer;color:var(--azul);font-size:20px}
.content{padding:20px;flex:1}
.folio-row{display:flex;align-items:center;gap:12px;margin-bottom:20px;flex-wrap:wrap}
.folio-badge{display:inline-flex;align-items:center;gap:8px;background:linear-gradient(135deg,var(--azul),var(--azul2));color:#fff;border-radius:10px;padding:10px 16px;font-family:"Exo 2",sans-serif;font-size:18px;font-weight:800;letter-spacing:2px;box-shadow:0 4px 14px rgba(21,101,192,.3)}
.estado-badge{display:inline-block;padding:5px 14px;border-radius:20px;font-family:"Exo 2",sans-serif;font-size:11px;font-weight:700;letter-spacing:1px}
.fecha-badge{font-size:12px;color:var(--muted);margin-left:auto;display:flex;align-items:center;gap:5px}
.folio-row{display:flex;align-items:center;gap:12px;margin-bottom:14px;flex-wrap:wrap}
.section{background:#fff;border-radius:14px;border:1px solid var(--borde);margin-bottom:16px;overflow:hidden;box-shadow:0 2px 10px rgba(21,101,192,.06)}
.section-header{padding:12px 18px;background:linear-gradient(90deg,#EBF5FF,#F5FAFF);border-bottom:1px solid var(--borde);display:flex;align-items:center;gap:10px}
.section-title{font-family:"Exo 2",sans-serif;font-size:13px;font-weight:700;color:var(--azul)}
.section-body{padding:16px 18px}
.fields-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(190px,1fr));gap:10px}
.field-card{background:#F5FAFF;border:1px solid var(--borde);border-radius:9px;padding:10px 14px}
.field-card.full{grid-column:1/-1}
.field-lbl{font-family:"Exo 2",sans-serif;font-size:9px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:var(--muted);margin-bottom:4px}
.field-val{font-size:14px;font-weight:500;color:var(--texto);word-break:break-word}
.nip-box{display:inline-flex;align-items:center;gap:8px;background:linear-gradient(135deg,#1B5E20,#2E7D32);color:#fff;border-radius:7px;padding:6px 12px;font-family:"Exo 2",sans-serif;font-size:16px;font-weight:800;letter-spacing:3px}
.foto-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(140px,1fr));gap:10px;margin-top:12px}
.foto-thumb{width:100%;height:130px;object-fit:cover;border-radius:10px;border:2px solid var(--borde);cursor:pointer;transition:transform .2s}
.foto-thumb:hover{transform:scale(1.04)}
.acc-table{width:100%;border-collapse:collapse;font-size:13px}
.acc-table th{padding:8px 12px;background:#EBF5FF;font-family:"Exo 2",sans-serif;font-size:10px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--muted);text-align:left;border-bottom:2px solid var(--borde)}
.acc-table td{padding:9px 12px;border-bottom:1px solid #F0F6FF}
.acc-table tr:last-child td{border-bottom:none}
.firma-wrap{background:#F5FAFF;border:1.5px solid var(--borde);border-radius:10px;padding:12px;display:inline-block}
.firma-img{max-width:100%;max-height:180px;display:block;border-radius:6px}
.lb{display:none;position:fixed;inset:0;background:rgba(0,0,0,.88);z-index:9999;align-items:center;justify-content:center}
.lb.open{display:flex}
.lb img{max-width:92vw;max-height:90vh;border-radius:8px;object-fit:contain}
.lb-x{position:absolute;top:14px;right:18px;color:#fff;font-size:28px;cursor:pointer;background:none;border:none}
.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}.fields-grid{grid-template-columns:1fr 1fr}.foto-grid{grid-template-columns:1fr 1fr}}
@media(max-width:480px){.fields-grid{grid-template-columns:1fr}}
</style></head>
<body>
<div class="overlay" id="overlay" onclick="closeSb()"></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"><?php echo strtoupper(substr($usuario,0,1)); ?></div>
    <div style="min-width:0">
      <div class="user-name"><?php echo htmlspecialchars($usuario); ?></div>
      <div class="user-role"><?php echo htmlspecialchars($rol); ?></div>
    </div>
  </div>
  <nav class="nav">
    <div class="nav-label">Módulos</div>
    <div>
      <button class="menu-btn" onclick="this.nextElementSibling.style.display=this.nextElementSibling.style.display==='block'?'none':'block'">
        <span class="icon"><i class="fas fa-laptop-code"></i></span>Servicios Técnicos
      </button>
      <div class="submenu" style="display:block">
        <a href="dashboard.php?vista=ordenes" class="sub-item active"><i class="fas fa-file-alt"></i> Órdenes de Servicio</a>
        <a href="dashboard.php?vista=anticipo" class="sub-item"><i class="fas fa-dollar-sign"></i> Registrar Anticipo</a>
        <a href="dashboard.php?vista=clientes" class="sub-item"><i class="fas fa-users"></i> Clientes</a>
      </div>
    </div>
  </nav>
  <div class="sidebar-footer"><a href="logout.php" class="logout-btn"><i class="fas fa-sign-out-alt"></i> Cerrar Sesión</a></div>
</aside>

<div class="main">
  <div class="topbar">
    <button class="hamburger" onclick="toggleSb()"><i class="fas fa-bars"></i></button>
    <div class="topbar-title">Orden <em><?php echo htmlspecialchars($folio); ?></em></div>
    <?php
    $nipEnc = urlencode($orden['nip']??'');
    $folEnc = urlencode($folio);
    ?>
    <a href="OrdenServ.php?os=<?php echo $folEnc; ?>&v=<?php echo $nipEnc; ?>"
       target="_blank"
       style="display:inline-flex;align-items:center;gap:8px;padding:8px 18px;
               background:linear-gradient(135deg,#E65100,#FF6D00);color:#fff;
               border-radius:9px;font-family:'Exo 2',sans-serif;font-size:13px;
               font-weight:700;text-decoration:none;letter-spacing:.5px;
               box-shadow:0 4px 14px rgba(230,81,0,.35);border:none;
               transition:transform .15s,box-shadow .2s"
       onmouseover="this.style.transform='translateY(-2px)';this.style.boxShadow='0 6px 20px rgba(230,81,0,.45)'"
       onmouseout="this.style.transform='';this.style.boxShadow='0 4px 14px rgba(230,81,0,.35)'">
      <i class="fas fa-print" style="font-size:16px"></i> Imprimir Orden
    </a>
    <?php if($rol==='ADMINISTRADOR'): ?>
    <a href="editar_orden.php?id=<?php echo $id; ?>" class="btn-editar"><i class="fas fa-edit"></i> Editar</a>
    <?php endif; ?>
    <a href="dashboard.php?vista=ordenes" class="btn-volver"><i class="fas fa-arrow-left"></i> Volver</a>
  </div>

  <div class="content">

    <?php if(isset($_GET['cotizado'])): ?>
    <div style="background:linear-gradient(135deg,#EDE7F6,#F3E5F5);border:1.5px solid #CE93D8;border-left:5px solid #6A1B9A;border-radius:10px;padding:14px 20px;margin-bottom:18px;display:flex;align-items:center;gap:14px;animation:fadeIn .4s ease">
      <div style="font-size:28px">📋</div>
      <div>
        <div style="font-family:'Exo 2',sans-serif;font-size:14px;font-weight:800;color:#4A148C">¡Cotización guardada exitosamente!</div>
        <div style="font-size:12px;color:#7B1FA2;margin-top:3px">La orden pasó a estado SERVICIO COTIZADO.</div>
      </div>
    </div>
    <?php endif; ?>
    <?php if(isset($_GET['nuevo'])): ?>
    <div style="background:linear-gradient(135deg,#E8F5E9,#F1F8E9);border:1.5px solid #A5D6A7;border-left:5px solid #2E7D32;border-radius:10px;padding:14px 20px;margin-bottom:18px;display:flex;align-items:center;gap:14px;animation:fadeIn .4s ease">
      <div style="font-size:28px">✅</div>
      <div>
        <div style="font-family:'Exo 2',sans-serif;font-size:14px;font-weight:800;color:#1B5E20">¡Orden <?php echo htmlspecialchars($folio); ?> registrada exitosamente!</div>
        <div style="font-size:12px;color:#388E3C;margin-top:3px">Ya puedes imprimir la orden o enviar el link al cliente.</div>
      </div>
      <div style="margin-left:auto;display:flex;gap:8px;flex-wrap:wrap">
        <a href="OrdenServ.php?os=<?php echo urlencode($folio); ?>&v=<?php echo urlencode($orden['nip']??''); ?>"
           target="_blank"
           style="display:inline-flex;align-items:center;gap:6px;padding:8px 16px;background:#2E7D32;color:#fff;border-radius:8px;font-family:'Exo 2',sans-serif;font-size:12px;font-weight:700;text-decoration:none">
          <i class="fas fa-print"></i> Imprimir ahora
        </a>
        <a href="nueva_orden.php" style="display:inline-flex;align-items:center;gap:6px;padding:8px 14px;background:#fff;color:#2E7D32;border:1.5px solid #A5D6A7;border-radius:8px;font-family:'Exo 2',sans-serif;font-size:12px;font-weight:700;text-decoration:none">
          + Nueva Orden
        </a>
      </div>
    </div>
    <style>@keyframes fadeIn{from{opacity:0;transform:translateY(-8px)}to{opacity:1;transform:none}}</style>
    <?php endif; ?>

    <div class="folio-row">
      <div class="folio-badge"><i class="fas fa-file-alt"></i> <?php echo htmlspecialchars($folio); ?></div>
      <span style="background:<?php echo $ep[0]; ?>;color:<?php echo $ep[1]; ?>;border:2px solid <?php echo $ep[1]; ?>;border-radius:20px;padding:7px 18px;font-family:'Exo 2',sans-serif;font-size:14px;font-weight:800;letter-spacing:1.5px;display:inline-flex;align-items:center;gap:7px">
        <?php
        $iconEst=['EN REVISION'=>'fa-search','SERVICIO COTIZADO'=>'fa-file-invoice-dollar',
                  'CONFIRMADO'=>'fa-thumbs-up','PAGADO'=>'fa-money-bill-wave',
                  'ENTREGADO FINAL'=>'fa-box-check'];
        echo '<i class="fas '.($iconEst[$est]??'fa-circle').'"></i>';
        echo htmlspecialchars($est);
        ?>
      </span>
      <div class="fecha-badge"><i class="fas fa-clock"></i><?php echo htmlspecialchars(substr($orden['fecha_creacion']??'---',0,16)); ?></div>
    </div>

    <?php $tiene_cotizacion = !empty($orden['fecha_cotitec']); ?>
    <div style="margin-bottom:18px;display:flex;gap:10px;flex-wrap:wrap;align-items:center">

    <?php if($est==='EN REVISION'): ?>
      <a href="cotizar.php?id=<?php echo $id; ?>"
         style="display:inline-flex;align-items:center;gap:9px;padding:12px 22px;background:linear-gradient(135deg,#6A1B9A,#8E24AA);color:#fff;border-radius:10px;font-family:'Exo 2',sans-serif;font-size:14px;font-weight:700;text-decoration:none;letter-spacing:.5px;box-shadow:0 4px 16px rgba(106,27,154,.35);transition:transform .15s"
         onmouseover="this.style.transform='translateY(-2px)'" onmouseout="this.style.transform=''">
        <i class="fas fa-file-invoice-dollar" style="font-size:16px"></i> Cotizar Servicio
      </a>

    <?php elseif($est==='SERVICIO COTIZADO'): ?>
      <button onclick="cambiarEstado('CONFIRMADO')"
         style="display:inline-flex;align-items:center;gap:9px;padding:12px 22px;background:linear-gradient(135deg,#1565C0,#1E88E5);color:#fff;border-radius:10px;font-family:'Exo 2',sans-serif;font-size:14px;font-weight:700;border:none;cursor:pointer;letter-spacing:.5px;box-shadow:0 4px 16px rgba(21,101,192,.35)">
        <i class="fas fa-thumbs-up" style="font-size:16px"></i> Confirmar Servicio
      </button>
      <a href="cotizar.php?id=<?php echo $id; ?>"
         style="display:inline-flex;align-items:center;gap:7px;padding:11px 18px;background:#fff;border:1.5px solid #8E24AA;color:#8E24AA;border-radius:10px;font-family:'Exo 2',sans-serif;font-size:13px;font-weight:700;text-decoration:none">
        <i class="fas fa-edit"></i> Editar Cotización
      </a>

    <?php elseif($est==='CONFIRMADO'): ?>
      <button onclick="cambiarEstado('PAGADO')"
         style="display:inline-flex;align-items:center;gap:9px;padding:12px 22px;background:linear-gradient(135deg,#00695C,#00897B);color:#fff;border-radius:10px;font-family:'Exo 2',sans-serif;font-size:14px;font-weight:700;border:none;cursor:pointer;letter-spacing:.5px;box-shadow:0 4px 16px rgba(0,105,92,.35)">
        <i class="fas fa-money-bill-wave" style="font-size:16px"></i> Registrar Pago
      </button>

    <?php elseif($est==='PAGADO'): ?>
      <button onclick="cambiarEstado('ENTREGADO FINAL')"
         style="display:inline-flex;align-items:center;gap:9px;padding:12px 22px;background:linear-gradient(135deg,#2E7D32,#43A047);color:#fff;border-radius:10px;font-family:'Exo 2',sans-serif;font-size:14px;font-weight:700;border:none;cursor:pointer;letter-spacing:.5px;box-shadow:0 4px 16px rgba(46,125,50,.35)">
        <i class="fas fa-box-open" style="font-size:16px"></i> Registrar Entrega Final
      </button>

    <?php elseif($est==='ENTREGADO FINAL'): ?>
      <div style="display:inline-flex;align-items:center;gap:8px;padding:10px 18px;background:#E8F5E9;border:1.5px solid #A5D6A7;border-radius:10px;font-family:'Exo 2',sans-serif;font-size:13px;font-weight:700;color:#2E7D32">
        <i class="fas fa-check-double"></i> Proceso Completado
      </div>
    <?php endif; ?>
    </div>

    <!-- Modal confirmación estado -->
    <div id="modalEstado" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.6);z-index:9999;align-items:center;justify-content:center">
      <div style="background:#fff;border-radius:16px;padding:28px 32px;max-width:380px;width:90%;text-align:center;box-shadow:0 20px 60px rgba(0,0,0,.2)">
        <div id="modalIcon" style="font-size:48px;margin-bottom:14px"></div>
        <div id="modalTitle" style="font-family:'Exo 2',sans-serif;font-size:16px;font-weight:800;color:#0D2A4A;margin-bottom:8px"></div>
        <div id="modalSub" style="font-size:13px;color:#5A7FA8;margin-bottom:22px"></div>
        <form method="POST" action="cambiar_estado.php">
          <input type="hidden" name="id_orden_serv" value="<?php echo $id; ?>">
          <input type="hidden" name="nuevo_estado" id="modalEstadoVal">
          <div style="display:flex;gap:10px;justify-content:center">
            <button type="submit" id="modalBtn" style="padding:11px 24px;border:none;border-radius:8px;color:#fff;font-family:'Exo 2',sans-serif;font-size:13px;font-weight:700;cursor:pointer">Confirmar</button>
            <button type="button" onclick="document.getElementById('modalEstado').style.display='none'"
                    style="padding:11px 18px;border:1.5px solid #C5DDF9;border-radius:8px;background:#fff;color:#5A7FA8;font-family:'Exo 2',sans-serif;font-size:13px;font-weight:600;cursor:pointer">Cancelar</button>
          </div>
        </form>
      </div>
    </div>

    <!-- CLIENTE -->
    <?php
    $nc=$orden['nombre_cliente']??'';$ec2=$orden['email_cliente_tec']??'';
    $tc=$orden['telefono_cliente']??'';$emp=$orden['empresa_referencia']??'';
    if($nc||$ec2||$tc||$emp):
    ?>
    <div class="section">
      <div class="section-header"><i class="fas fa-user" style="color:var(--acento)"></i><span class="section-title">Datos del Cliente</span></div>
      <div class="section-body"><div class="fields-grid">
        <?php echo campo('Nombre',$nc); ?>
        <?php echo campo('Email',$ec2); ?>
        <?php echo campo('Teléfono',$tc); ?>
        <?php echo campo('Empresa / Referencia',$emp); ?>
      </div></div>
    </div>
    <?php endif; ?>

    <!-- DATOS DE LA ORDEN -->
    <div class="section">
      <div class="section-header"><i class="fas fa-hashtag" style="color:var(--acento)"></i><span class="section-title">Datos de la Orden</span></div>
      <div class="section-body"><div class="fields-grid">
        <?php echo campo('Fecha de Creación',$orden['fecha_creacion']??''); ?>
        <?php echo campo('Asesor que Atiende',$orden['asesor_que_atiende']??''); ?>
        <?php echo campo('Creado por',$orden['creado_por']??''); ?>
        <?php echo campo('Sucursal',$orden['sucursal']??''); ?>
        <?php echo campo('Referenciado',$orden['referenciado']??''); ?>
        <?php echo campo('Ticket Anticipo',$orden['ticket_anticipo']??''); ?>
        <?php echo campo('Estado',$orden['estado']??''); ?>
        <?php echo campo('Fecha Límite de Recojo',$orden['feclimiterecoje']??''); ?>
        <?php echo campo('Trae Accesorios',$orden['equipo_con_accesorios']??''); ?>
        <?php if(!empty($orden['nip'])): ?>
        <div class="field-card">
          <div class="field-lbl">NIP Cliente</div>
          <div class="field-val"><div class="nip-box"><i class="fas fa-shield-alt"></i> <?php echo htmlspecialchars($orden['nip']); ?></div></div>
        </div>
        <?php endif; ?>
        <?php echo campo('Instrucciones del Cliente',$orden['instrucciones_cliente']??'',true); ?>
      </div></div>
    </div>

    <!-- EQUIPO -->
    <?php
    $camposEq=['tipo_de_equipo'=>'Tipo de Equipo','marca_de_equipo'=>'Marca',
               'modelo_del_equipo'=>'Modelo','estado_fisico_de_recepcion'=>'Estado Físico',
               'numero_de_serie_del_equipo'=>'No. Serie','prende_completamente'=>'Prende',
               'password'=>'Contraseña/Patrón','solicita_respaldo'=>'Solicita Respaldo',
               'argumento_de_la_falla'=>'Argumento de la Falla'];
    $hayEq=false;
    foreach($camposEq as $k=>$l){ if(!empty($equipo[$k])){ $hayEq=true; break; }}
    if($hayEq||$fotos):
    ?>
    <div class="section">
      <div class="section-header"><i class="fas fa-laptop" style="color:var(--acento)"></i><span class="section-title">Equipo Recibido</span></div>
      <div class="section-body">
        <?php if($hayEq): ?>
        <div class="fields-grid">
          <?php foreach($camposEq as $k=>$lbl):
            $full=($k==='argumento_de_la_falla');
            echo campo($lbl,$equipo[$k]??'',$full);
          endforeach; ?>
        </div>
        <?php endif; ?>
        <?php if($fotos || (!empty($orden['firma_cliente']) && strlen($orden['firma_cliente'])>10) || $accesorios): ?>
        <div style="margin-top:14px;display:flex;gap:20px;align-items:flex-start;flex-wrap:wrap">

          <!-- FOTOS + FIRMA izquierda -->
          <?php if($fotos || (!empty($orden['firma_cliente']) && strlen($orden['firma_cliente'])>10)): ?>
          <div style="flex:1;min-width:280px">
            <div style="font-family:'Exo 2',sans-serif;font-size:9px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:var(--muted);margin-bottom:8px">
              <i class="fas fa-camera" style="margin-right:6px;color:var(--acento)"></i>Evidencia Fotográfica
            </div>
            <div style="display:flex;gap:8px;flex-wrap:wrap;align-items:flex-end">
              <?php foreach($fotos as $fv): ?>
              <img src="<?php echo htmlspecialchars($fv); ?>"
                   style="width:120px;height:100px;object-fit:cover;border-radius:10px;border:2px solid var(--borde);cursor:pointer;transition:transform .2s"
                   onclick="abrirLb(this.src)"
                   onerror="this.style.display='none'"
                   alt="Evidencia"
                   onmouseover="this.style.transform='scale(1.04)'" onmouseout="this.style.transform=''">
              <?php endforeach; ?>
              <?php if(!empty($orden['firma_cliente']) && strlen($orden['firma_cliente'])>10): ?>
              <div style="display:flex;flex-direction:column;align-items:center;gap:3px">
                <div style="background:#F5FAFF;border:1.5px solid var(--borde);border-radius:10px;padding:5px;cursor:pointer" onclick="abrirLb(this.querySelector('img').src)">
                  <img src="<?php echo htmlspecialchars($orden['firma_cliente']); ?>"
                       style="width:120px;height:82px;object-fit:contain;display:block;border-radius:5px;background:#fff"
                       alt="Firma">
                </div>
                <span style="font-family:'Exo 2',sans-serif;font-size:9px;font-weight:700;color:var(--muted);letter-spacing:1px;text-transform:uppercase"><i class="fas fa-signature" style="margin-right:3px"></i>Firma</span>
              </div>
              <?php endif; ?>
            </div>
          </div>
          <?php endif; ?>

          <!-- ACCESORIOS derecha -->
          <?php if($accesorios): ?>
          <div style="flex:1;min-width:260px">
            <div style="font-family:'Exo 2',sans-serif;font-size:9px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:var(--muted);margin-bottom:8px">
              <i class="fas fa-boxes" style="margin-right:6px;color:var(--acento)"></i>Accesorios Recibidos (<?php echo count($accesorios); ?>)
            </div>
            <div style="background:#F5FAFF;border:1px solid var(--borde);border-radius:10px;overflow:hidden">
              <table class="acc-table" style="margin:0">
                <thead><tr><th>#</th><th>Accesorio</th><th>No. Serie</th></tr></thead>
                <tbody>
                <?php foreach($accesorios as $i=>$acc): ?>
                <tr>
                  <td style="color:var(--muted);font-size:12px"><?php echo ($i+1); ?></td>
                  <td style="font-weight:600"><?php echo htmlspecialchars($acc['accesorio_recibido']??'---'); ?></td>
                  <td style="color:var(--muted)"><?php echo htmlspecialchars($acc['numero_de_serie_de_accesorio']??'---'); ?></td>
                </tr>
                <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          </div>
          <?php endif; ?>

        </div>
        <?php endif; ?>
      </div>
    </div>
    <?php endif; ?>

    <!-- COTIZACIÓN -->
    <?php
    $cots=$pdo->prepare("SELECT * FROM refcotiser WHERE id_orden_serv=?");
    $cots->execute([$id]);$cotizaciones=$cots->fetchAll();
    $total_cot=(float)($orden['total_cotizado']??0);
    $mano_obra=(float)($orden['mano_de_obra']??0);
    if($cotizaciones):
    ?>
    <div class="section">
      <div class="section-header" style="justify-content:space-between">
        <div style="display:flex;align-items:center;gap:10px">
          <i class="fas fa-file-invoice-dollar" style="color:var(--acento)"></i>
          <span class="section-title">Cotización del Servicio</span>
        </div>
        <?php if($rol==='ADMINISTRADOR'): ?>
        <a href="cotizar.php?id=<?php echo $id; ?>"
           style="display:inline-flex;align-items:center;gap:6px;padding:5px 12px;background:#EDE7F6;border:1.5px solid #8E24AA;color:#6A1B9A;border-radius:8px;font-family:'Exo 2',sans-serif;font-size:11px;font-weight:700;text-decoration:none">
          <i class="fas fa-edit"></i> Editar Cotización
        </a>
        <?php endif; ?>
      </div>
      <div class="section-body">
        <table style="width:100%;border-collapse:collapse;font-size:13px">
          <thead><tr>
            <th style="padding:8px 12px;background:#EBF5FF;font-family:'Exo 2',sans-serif;font-size:10px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--muted);text-align:left;border-bottom:2px solid var(--borde)">Diagnóstico</th>
            <th style="padding:8px 12px;background:#EBF5FF;font-family:'Exo 2',sans-serif;font-size:10px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--muted);text-align:left;border-bottom:2px solid var(--borde)">Solución</th>
            <th style="padding:8px 12px;background:#EBF5FF;font-family:'Exo 2',sans-serif;font-size:10px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--muted);text-align:right;border-bottom:2px solid var(--borde)">M.Obra</th>
            <th style="padding:8px 12px;background:#EBF5FF;font-family:'Exo 2',sans-serif;font-size:10px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--muted);text-align:left;border-bottom:2px solid var(--borde)">Refacción</th>
            <th style="padding:8px 12px;background:#EBF5FF;font-family:'Exo 2',sans-serif;font-size:10px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--muted);text-align:center;border-bottom:2px solid var(--borde)">Tipo</th>
            <th style="padding:8px 12px;background:#EBF5FF;font-family:'Exo 2',sans-serif;font-size:10px;font-weight:700;letter-spacing:1px;text-transform:uppercase;color:var(--muted);text-align:right;border-bottom:2px solid var(--borde)">Subtotal</th>
          </tr></thead>
          <tbody>
          <?php foreach($cotizaciones as $ct):
            $lk=$ct['link']??'';
            if(stripos($lk,'mercadolibre')!==false) $entrega='3-6 días';
            elseif(stripos($lk,'ebay')!==false) $entrega='8-20 días';
            elseif(stripos($lk,'compujuarez')!==false) $entrega='1-2 días';
            elseif(stripos($lk,'amazon')!==false) $entrega='8-20 días';
            else $entrega='';
            $t=$ct['tipo_de_compra']??'manoobra';
            $tc=['manoobra'=>['#E8F5E9','#2E7D32'],'LOCAL'=>['#E3F2FD','#1565C0'],'NACIONAL'=>['#F3E5F5','#6A1B9A'],'INTERNACIONAL'=>['#FFF3E0','#E65100']];
            $tc2=$tc[$t]??['#F5FAFF','#5A7FA8'];
          ?>
          <tr style="border-bottom:1px solid #F0F6FF">
            <td style="padding:9px 12px;font-weight:600;font-size:12px"><?php echo htmlspecialchars($ct['diagnostico']??'—'); ?></td>
            <td style="padding:9px 12px;font-size:12px;color:var(--muted)">
              <?php echo htmlspecialchars(mb_strimwidth($ct['solucion']??'—',0,50,'…')); ?>
              <?php if(!empty($ct['detalle_para_solucion'])): ?>
              <div style="font-size:11px;font-style:italic"><?php echo htmlspecialchars(mb_strimwidth($ct['detalle_para_solucion'],0,50,'…')); ?></div>
              <?php endif; ?>
            </td>
            <td style="padding:9px 12px;text-align:right;font-weight:700;color:var(--azul)">$<?php echo number_format((float)($ct['precio']??0),2); ?></td>
            <td style="padding:9px 12px;font-size:11px">
              <?php if(($ct['requiere_reemplazo_partes']??'NO')==='SI'):
                $costo_ref = (float)($ct['subtotal']??0) - (float)($ct['precio']??0);
              ?>
              <strong><?php echo htmlspecialchars($ct['numero_de_parte']??''); ?></strong><br>
              <span style="font-weight:700;color:var(--verde)">$<?php echo number_format($costo_ref,2); ?></span>
              <?php if($entrega): ?><br><span style="color:var(--acento);font-size:10px"><i class="fas fa-clock"></i> <?php echo $entrega; ?></span><?php endif; ?>
              <?php else: ?>—<?php endif; ?>
            </td>
            <td style="padding:9px 12px;text-align:center">
              <span style="background:<?php echo $tc2[0]; ?>;color:<?php echo $tc2[1]; ?>;border-radius:12px;padding:2px 8px;font-size:10px;font-weight:700;font-family:'Exo 2',sans-serif"><?php echo htmlspecialchars($t); ?></span>
            </td>
            <td style="padding:9px 12px;text-align:right;font-weight:800;font-size:14px;color:#1B5E20">$<?php echo number_format((float)($ct['subtotal']??0),2); ?></td>
          </tr>
          <?php endforeach; ?>
          </tbody>
          <tfoot>
            <tr style="background:#F0F8FF">
              <td colspan="2" style="padding:10px 12px;text-align:right;font-family:'Exo 2',sans-serif;font-size:11px;font-weight:700;color:var(--muted)">Mano de Obra Total:</td>
              <td style="padding:10px 12px;text-align:right;font-weight:800;color:var(--azul)">$<?php echo number_format($mano_obra,2); ?></td>
              <td colspan="2" style="padding:10px 12px;text-align:right;font-family:'Exo 2',sans-serif;font-size:12px;font-weight:700">TOTAL COTIZADO:</td>
              <td style="padding:10px 12px;text-align:right;font-weight:800;font-size:18px;color:#1B5E20">$<?php echo number_format($total_cot,2); ?></td>
            </tr>
          </tfoot>
        </table>
        <div style="margin-top:10px;font-size:11px;color:var(--muted)">
          <i class="fas fa-user-cog" style="margin-right:4px"></i>Técnico: <strong><?php echo htmlspecialchars($orden['tecnico_asignado']??'—'); ?></strong>
          &nbsp;·&nbsp;
          <i class="fas fa-calendar" style="margin-right:4px"></i>Cotizado: <strong><?php echo htmlspecialchars(substr($orden['fecha_cotitec']??'—',0,16)); ?></strong>
        </div>
      </div>
    </div>
    <?php endif; ?>



  </div>
</div>

<div class="lb" id="lb" onclick="this.classList.remove('open')">
  <button class="lb-x" onclick="document.getElementById('lb').classList.remove('open')">&#10005;</button>
  <img id="lbImg" src="" alt="Evidencia">
</div>

<script>
function cambiarEstado(nuevoEst){
  const cfgs={
    'CONFIRMADO':   {icon:'👍',title:'Confirmar Servicio',sub:'¿El cliente autorizó la reparación?',color:'#1565C0'},
    'PAGADO':       {icon:'💰',title:'Registrar Pago',sub:'¿El cliente realizó el pago completo?',color:'#00695C'},
    'ENTREGADO FINAL':{icon:'📦',title:'Registrar Entrega Final',sub:'¿El equipo fue entregado al cliente?',color:'#2E7D32'},
  };
  const c=cfgs[nuevoEst]; if(!c) return;
  document.getElementById('modalIcon').textContent=c.icon;
  document.getElementById('modalTitle').textContent=c.title;
  document.getElementById('modalSub').textContent=c.sub;
  document.getElementById('modalEstadoVal').value=nuevoEst;
  document.getElementById('modalBtn').style.background=c.color;
  document.getElementById('modalEstado').style.display='flex';
}
function toggleSb(){document.getElementById('sidebar').classList.toggle('open');document.getElementById('overlay').classList.toggle('open')}
function closeSb(){document.getElementById('sidebar').classList.remove('open');document.getElementById('overlay').classList.remove('open')}
function abrirLb(src){document.getElementById('lbImg').src=src;document.getElementById('lb').classList.add('open')}
</script>
<?php include __DIR__."/theme.php"; ?>
</body></html>