<?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']??$_POST['id_orden_serv']??0);
if(!$id){header("Location: dashboard.php?vista=ordenes");exit;}

$stmtO=$pdo->prepare("SELECT * FROM ordenes_de_servicio WHERE id_orden_serv=? LIMIT 1");
$stmtO->execute([$id]);$orden=$stmtO->fetch();
if(!$orden){header("Location: dashboard.php?vista=ordenes");exit;}

$yr=date('Y',strtotime($orden['fecha_creacion']??'now'));
$folio=$yr.'-'.str_pad($id,4,'0',STR_PAD_LEFT);

$stmtP=$pdo->prepare("SELECT * FROM refcotiser WHERE id_orden_serv=?");
$stmtP->execute([$id]);$partidas=$stmtP->fetchAll();

$actividades=$pdo->query("SELECT * FROM ACTIVIDADES ORDER BY n+0 ASC")->fetchAll();
$actMap=[];
foreach($actividades as $a) $actMap[$a['diag']]=$a;

$msg='';$msgType='';

if($_SERVER['REQUEST_METHOD']==='POST' && isset($_POST['guardar_cotizacion'])){
    try{
        $pdo->beginTransaction();
        $pdo->prepare("DELETE FROM refcotiser WHERE id_orden_serv=?")->execute([$id]);

        $total_mano_obra=0;$total_cotizado=0;
        $diagnosticos=$_POST['diagnostico']??[];
        $soluciones=$_POST['solucion']??[];
        $detalles=$_POST['detalle_para_solucion']??[];
        $precios=$_POST['precio']??[];
        $req_refs=$_POST['requiere_reemplazo_partes']??[];
        $num_partes=$_POST['numero_de_parte']??[];
        $costos_parte=$_POST['costo_de_la_parte']??[];
        $costos_envio=$_POST['costo_de_envio']??[];
        $links=$_POST['link']??[];

        $stmtI=$pdo->prepare("INSERT INTO refcotiser
            (id_orden_serv,diagnostico,solucion,detalle_para_solucion,precio,
             requiere_reemplazo_partes,numero_de_parte,costo_de_la_parte,costo_de_envio,
             link,porciento_link,subtotal,tipo_de_compra)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)");

        foreach($diagnosticos as $i=>$diag){
            if(empty(trim($diag))) continue;
            $precio=(float)($precios[$i]??0);
            $req=$req_refs[$i]??'NO';
            $num_p=$num_partes[$i]??'';
            $costo_p=(float)($costos_parte[$i]??0);
            $costo_e=(float)($costos_envio[$i]??0);
            $link=trim($links[$i]??'');

            if(stripos($link,'mercadolibre')!==false) $pct=1.35;
            elseif(stripos($link,'ebay')!==false) $pct=1.90;
            elseif(stripos($link,'compujuarez')!==false) $pct=1.00;
            elseif(stripos($link,'amazon')!==false) $pct=1.60;
            elseif(stripos($link,'ctonline')!==false) $pct=1.45;
            else $pct=2.50;

            if(empty($link)) $subtotal=$precio;
            elseif(stripos($link,'compujuarez')!==false) $subtotal=$precio+($costo_p+$costo_e)*$pct;
            else $subtotal=$precio+ceil(($costo_p+$costo_e)*$pct/10)*10;

            if(empty($link)) $tipo='manoobra';
            elseif(stripos($link,'mercadolibre')!==false) $tipo='NACIONAL';
            elseif(stripos($link,'ebay')!==false) $tipo='INTERNACIONAL';
            elseif(stripos($link,'compujuarez')!==false) $tipo='LOCAL';
            elseif(stripos($link,'amazon')!==false) $tipo='INTERNACIONAL';
            else $tipo='NACIONAL';

            $stmtI->execute([$id,$diag,$soluciones[$i]??'',$detalles[$i]??'',$precio,
                $req,$num_p,$costo_p,$costo_e,$link,$pct,$subtotal,$tipo]);

            $total_mano_obra+=$precio;
            $total_cotizado+=$subtotal;
        }

        $pdo->prepare("UPDATE ordenes_de_servicio SET
            estado='SERVICIO COTIZADO',fecha_cotitec=NOW(),
            tecnico_asignado=?,total_cotizado=?,mano_de_obra=?
            WHERE id_orden_serv=?")
        ->execute([$usuario,$total_cotizado,$total_mano_obra,$id]);

        $pdo->commit();
        header("Location: ver_orden.php?id=$id&cotizado=1");
        exit;
    }catch(Exception $e){$pdo->rollBack();$msg="Error: ".$e->getMessage();$msgType='error';}
}
$stmtP->execute([$id]);$partidas=$stmtP->fetchAll();

// Equipo
$eq=$pdo->prepare("SELECT tipo_de_equipo,marca_de_equipo,modelo_del_equipo FROM refequipo WHERE id_orden_serv=? LIMIT 1");
$eq->execute([$id]);$equipo=$eq->fetch()?:[];
?><!DOCTYPE html>
<html lang="es"><head>
<meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
<title>Cotizar — <?php echo 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;--verde:#2E7D32;--rojo:#C62828}
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)}
.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}
.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}.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;color:#fff;font-family:"Exo 2",sans-serif;font-size:12px;font-weight:600;text-align:left;cursor:pointer}
.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}
.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:12px;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-top{display:inline-flex;align-items:center;gap:6px;padding:7px 13px;border-radius:8px;font-size:12px;font-weight:600;text-decoration:none;font-family:"Exo 2",sans-serif;border:1px solid var(--borde);background:#EBF5FF;color:var(--azul);cursor:pointer}
.content{padding:20px;flex:1}
.msg{padding:12px 16px;border-radius:10px;margin-bottom:16px;font-size:14px}
.error{background:#FFEBEE;border:1px solid #EF9A9A;color:#C62828}
.orden-info{background:#fff;border-radius:12px;border:1px solid var(--borde);padding:14px 18px;margin-bottom:18px;display:flex;align-items:center;gap:16px;flex-wrap:wrap;box-shadow:0 2px 10px rgba(21,101,192,.06)}
.info-chip{font-size:12px;color:var(--muted);display:flex;align-items:center;gap:5px}
.info-chip strong{color:var(--texto)}
.partida{background:#fff;border:1.5px solid var(--borde);border-radius:14px;margin-bottom:16px;overflow:hidden;box-shadow:0 2px 12px rgba(21,101,192,.07)}
.partida-header{background:linear-gradient(90deg,var(--azul),var(--azul2));color:#fff;padding:10px 18px;display:flex;align-items:center;justify-content:space-between}
.partida-num{font-family:"Exo 2",sans-serif;font-size:13px;font-weight:800;letter-spacing:1px}
.btn-del-partida{background:rgba(255,255,255,.15);border:1px solid rgba(255,255,255,.3);color:#fff;border-radius:7px;padding:5px 10px;cursor:pointer;font-size:12px;font-weight:600;font-family:"Exo 2",sans-serif;display:flex;align-items:center;gap:5px}
.partida-body{padding:16px 18px}
.form-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:14px}
.form-grid.col2{grid-template-columns:1fr 1fr}
.form-grid.col3{grid-template-columns:1fr 1fr 1fr}
.form-group{display:flex;flex-direction:column;gap:5px}
.form-group.full{grid-column:1/-1}
.fg-label{font-family:"Exo 2",sans-serif;font-size:9px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:var(--muted)}
input[type=text],input[type=number],input[type=url],select,textarea{padding:10px 12px;background:#F5FAFF;border:1.5px solid var(--borde);border-radius:8px;color:var(--texto);font-size:14px;font-family:"Inter",sans-serif;outline:none;transition:border-color .2s;width:100%}
input:focus,select:focus,textarea:focus{border-color:var(--azul2);background:#fff;box-shadow:0 0 0 3px rgba(30,136,229,.1)}
select{background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='8'%3E%3Cpath d='M1 1l5 5 5-5' stroke='%235A7FA8' stroke-width='1.5' fill='none' stroke-linecap='round'/%3E%3C/svg%3E");background-repeat:no-repeat;background-position:right 11px center;padding-right:30px;background-color:#F5FAFF}
textarea{resize:vertical;min-height:70px}
.field-ro{padding:10px 12px;background:#EEF4FB;border:1.5px solid #D6ECFF;border-radius:8px;color:var(--muted);font-size:14px;min-height:42px;display:flex;align-items:center;gap:6px}
.ref-box{background:#FFF8E1;border:1.5px solid #FFE082;border-radius:10px;padding:14px;margin-top:12px;display:none}
.ref-box.visible{display:block}
.ref-box-title{font-family:"Exo 2",sans-serif;font-size:11px;font-weight:700;color:#E65100;margin-bottom:12px;display:flex;align-items:center;gap:6px}
.toggle-group{display:flex;gap:8px}
.toggle-opt{flex:1;padding:9px;border:1.5px solid var(--borde);border-radius:8px;text-align:center;cursor:pointer;font-family:"Exo 2",sans-serif;font-size:12px;font-weight:700;color:var(--muted);transition:all .2s;user-select:none}
.toggle-opt.si{border-color:#2E7D32;background:#E8F5E9;color:#2E7D32}
.toggle-opt.no{border-color:#90A4AE;background:#ECEFF1;color:#546E7A}
.subtotal-box{background:linear-gradient(135deg,#E8F5E9,#F1F8E9);border:1.5px solid #A5D6A7;border-radius:10px;padding:12px 16px;margin-top:14px;display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:8px}
.subtotal-label{font-family:"Exo 2",sans-serif;font-size:11px;font-weight:700;color:#2E7D32;text-transform:uppercase;letter-spacing:1px}
.subtotal-val{font-family:"Exo 2",sans-serif;font-size:22px;font-weight:800;color:#1B5E20}
.chip{display:inline-flex;align-items:center;gap:4px;padding:2px 9px;border-radius:12px;font-size:11px;font-weight:700;font-family:"Exo 2",sans-serif;background:rgba(255,255,255,.7);border:1px solid rgba(0,0,0,.08)}
.btn-agregar{display:flex;align-items:center;justify-content:center;gap:10px;width:100%;padding:14px;background:#fff;border:2px dashed var(--acento);border-radius:12px;color:var(--azul2);font-family:"Exo 2",sans-serif;font-size:14px;font-weight:700;cursor:pointer;transition:all .2s;margin-bottom:20px}
.btn-agregar:hover{background:#EBF5FF;border-color:var(--azul2)}
.total-global{background:linear-gradient(135deg,var(--azul),var(--azul2));color:#fff;border-radius:12px;padding:16px 22px;display:flex;justify-content:space-between;align-items:center;margin-bottom:20px;flex-wrap:wrap;gap:10px}
.tg-label{font-family:"Exo 2",sans-serif;font-size:12px;font-weight:700;opacity:.85}
.tg-val{font-family:"Exo 2",sans-serif;font-size:28px;font-weight:800;letter-spacing:1px}
.tg-mo{font-family:"Exo 2",sans-serif;font-size:12px;opacity:.75;margin-top:2px}
.btn-save{display:inline-flex;align-items:center;gap:9px;padding:14px 32px;background:linear-gradient(135deg,#1B5E20,#2E7D32,#43A047);border:none;border-radius:10px;color:#fff;font-family:"Exo 2",sans-serif;font-size:15px;font-weight:700;letter-spacing:1.5px;cursor:pointer;box-shadow:0 4px 20px rgba(46,125,50,.3)}
.btn-cancel{display:inline-flex;align-items:center;gap:8px;padding:13px 20px;border-radius:10px;border:1.5px solid var(--borde);background:#fff;color:var(--muted);font-family:"Exo 2",sans-serif;font-size:13px;font-weight:600;text-decoration:none}
/* Select diagnóstico — truncar opción seleccionada */
select.sel-diag{font-size:13px;font-weight:600}
@media(max-width:900px){.form-grid.col3{grid-template-columns:1fr 1fr}}
@media(max-width:640px){.form-grid.col2,.form-grid.col3{grid-template-columns:1fr}}
</style></head>
<body>
<aside class="sidebar">
  <div class="sidebar-logo">
    <img src="https://lh3.googleusercontent.com/d/18I4DcekLRsd0Lfsg8cpqxU7Vh6b1IC4O" alt="VANTECC">
    <div class="sidebar-logo-text">PROCEIN 2026 PRO<span>CompuJuárez · Vantecc</span></div>
  </div>
  <div class="sidebar-user">
    <div class="user-avatar"><?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"><span class="icon"><i class="fas fa-laptop-code"></i></span>Servicios Técnicos</button>
      <div class="submenu">
        <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">
    <div class="topbar-title"><i class="fas fa-file-invoice-dollar" style="color:var(--acento);margin-right:8px"></i>Cotización — Orden <em><?php echo htmlspecialchars($folio); ?></em></div>
    <a href="ver_orden.php?id=<?php echo $id; ?>" class="btn-top" style="margin-left:auto"><i class="fas fa-eye"></i> Ver Orden</a>
    <a href="dashboard.php?vista=ordenes" class="btn-top"><i class="fas fa-arrow-left"></i> Volver</a>
  </div>
  <div class="content">
    <?php if($msg): ?><div class="msg error"><?php echo $msg; ?></div><?php endif; ?>

    <div class="orden-info">
      <div class="info-chip"><i class="fas fa-user"></i><strong><?php echo htmlspecialchars($orden['nombre_cliente']??'—'); ?></strong></div>
      <div class="info-chip"><i class="fas fa-laptop"></i><strong><?php echo htmlspecialchars(trim(($equipo['tipo_de_equipo']??'').' '.($equipo['marca_de_equipo']??'').' '.($equipo['modelo_del_equipo']??''))); ?></strong></div>
      <div class="info-chip"><i class="fas fa-user-cog"></i>Técnico: <strong><?php echo htmlspecialchars($usuario); ?></strong></div>
    </div>

    <form method="POST" id="formCot">
      <input type="hidden" name="guardar_cotizacion" value="1">
      <input type="hidden" name="id_orden_serv" value="<?php echo $id; ?>">

      <div id="listaPartidas">
      <?php foreach($partidas as $pi=>$pt):
        $req_val=$pt['requiere_reemplazo_partes']??'NO';
      ?>
      <div class="partida">
        <div class="partida-header">
          <div class="partida-num"><i class="fas fa-tools" style="margin-right:6px"></i>Partida <?php echo ($pi+1); ?></div>
          <button type="button" class="btn-del-partida" onclick="eliminarPartida(this)"><i class="fas fa-trash"></i> Quitar</button>
        </div>
        <div class="partida-body">
          <div style="display:grid;grid-template-columns:1fr 180px;gap:14px;margin-bottom:12px">
            <div class="form-group">
              <label class="fg-label">Diagnóstico / Actividad</label>
              <select name="diagnostico[]" class="sel-diag" onchange="autoFill(this)" required>
                <option value="">— Seleccionar —</option>
                <?php foreach($actividades as $act): ?>
                <option value="<?php echo htmlspecialchars($act['diag']); ?>"
                  <?php echo $act['diag']===$pt['diagnostico']?'selected':''; ?>>
                  <?php echo htmlspecialchars($act['diag']); ?>
                </option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="form-group">
              <label class="fg-label">Precio Mano de Obra</label>
              <div class="field-ro"><i class="fas fa-tag" style="color:var(--azul2)"></i>
                <span class="precio-txt">$<?php echo number_format((float)($pt['precio']??0),2); ?></span>
                <input type="hidden" name="precio[]" class="precio-hid" value="<?php echo $pt['precio']??0; ?>">
              </div>
            </div>
          </div>
          <div class="form-group full" style="margin-bottom:12px">
            <label class="fg-label">Solución</label>
            <div class="field-ro"><i class="fas fa-check-circle" style="color:var(--verde)"></i>
              <span class="solucion-txt"><?php echo htmlspecialchars($pt['solucion']??'---'); ?></span>
              <input type="hidden" name="solucion[]" class="solucion-hid" value="<?php echo htmlspecialchars($pt['solucion']??''); ?>">
            </div>
          </div>
          <div class="form-group full" style="margin-bottom:12px">
            <label class="fg-label">Detalle adicional <span style="color:#aaa;font-weight:400">(editable)</span></label>
            <textarea name="detalle_para_solucion[]" placeholder="Notas adicionales..."><?php echo htmlspecialchars($pt['detalle_para_solucion']??''); ?></textarea>
          </div>
          <div class="form-group" style="margin-bottom:4px">
            <label class="fg-label">¿Requiere refacción?</label>
            <div class="toggle-group">
              <div class="toggle-opt <?php echo $req_val==='SI'?'si':''; ?>" onclick="setRef(this,'SI')"><i class="fas fa-cogs" style="margin-right:5px"></i>SÍ</div>
              <div class="toggle-opt <?php echo $req_val!=='SI'?'no':''; ?>" onclick="setRef(this,'NO')"><i class="fas fa-times" style="margin-right:5px"></i>NO</div>
            </div>
            <input type="hidden" name="requiere_reemplazo_partes[]" class="req-hid" value="<?php echo $req_val; ?>">
          </div>
          <div class="ref-box <?php echo $req_val==='SI'?'visible':''; ?>">
            <div class="ref-box-title"><i class="fas fa-box-open"></i>Datos de la Refacción</div>
            <div class="form-grid col2" style="margin-bottom:12px">
              <div class="form-group"><label class="fg-label">Número de Parte</label>
                <input type="text" name="numero_de_parte[]" placeholder="Ej. SR54C" value="<?php echo htmlspecialchars($pt['numero_de_parte']??''); ?>"></div>
              <div class="form-group"><label class="fg-label">Link del Proveedor</label>
                <input type="url" name="link[]" class="link-inp" placeholder="https://ebay.com/..." value="<?php echo htmlspecialchars($pt['link']??''); ?>" oninput="calcSubtotal(this)"></div>
            </div>
            <div class="form-grid col2">
              <div class="form-group"><label class="fg-label">Costo Proveedor $</label>
                <input type="number" name="costo_de_la_parte[]" class="costo-p" min="0" step="0.01" placeholder="0.00" value="<?php echo $pt['costo_de_la_parte']??0; ?>" oninput="calcSubtotal(this)"></div>
              <div class="form-group"><label class="fg-label">Costo de Envío $</label>
                <input type="number" name="costo_de_envio[]" class="costo-e" min="0" step="0.01" placeholder="0.00" value="<?php echo $pt['costo_de_envio']??0; ?>" oninput="calcSubtotal(this)"></div>
            </div>
          </div>
          <!-- Subtotal -->
          <div class="subtotal-box">
            <div style="flex:1">
              <div class="subtotal-label">Total Partida</div>
              <div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:5px">
                <span class="chip subtotal-pct" style="color:#1565C0"><i class="fas fa-percentage" style="font-size:9px"></i> x<?php echo number_format((float)($pt['porciento_link']??1),2); ?></span>
                <span class="chip subtotal-tipo"><?php echo htmlspecialchars($pt['tipo_de_compra']??'manoobra'); ?></span>
                <?php if(!empty($pt['link'])): ?>
                <span class="chip subtotal-entrega" style="color:var(--muted);font-style:italic"><i class="fas fa-clock" style="font-size:9px"></i>
                  <?php $lk=$pt['link'];
                    if(stripos($lk,'mercadolibre')!==false) echo 'DE 3 A 6 DÍAS';
                    elseif(stripos($lk,'ebay')!==false) echo 'DE 8 A 20 DÍAS';
                    elseif(stripos($lk,'compujuarez')!==false) echo 'DE 1 A 2 DÍAS';
                    elseif(stripos($lk,'amazon')!==false) echo 'DE 8 A 20 DÍAS';
                    else echo 'DE 8 A 20 DÍAS'; ?>
                </span>
                <?php endif; ?>
              </div>
            </div>
            <div class="subtotal-val">$<span class="subtotal-num"><?php echo number_format((float)($pt['subtotal']??0),2); ?></span></div>
          </div>
        </div>
      </div>
      <?php endforeach; ?>
      </div>

      <button type="button" class="btn-agregar" onclick="agregarPartida()">
        <i class="fas fa-plus-circle" style="font-size:18px"></i> Agregar Partida
      </button>

      <div class="total-global">
        <div>
          <div class="tg-label">TOTAL COTIZACIÓN</div>
          <div class="tg-val">$<span id="totalVal">0.00</span></div>
          <div class="tg-mo">Mano de obra: $<span id="totalMO">0.00</span></div>
        </div>
        <i class="fas fa-calculator" style="font-size:36px;opacity:.4"></i>
      </div>

      <div style="display:flex;gap:12px;flex-wrap:wrap;padding-top:4px">
        <button type="submit" class="btn-save"><i class="fas fa-check-circle"></i> Guardar Cotización</button>
        <a href="ver_orden.php?id=<?php echo $id; ?>" class="btn-cancel"><i class="fas fa-times"></i> Cancelar</a>
      </div>
    </form>
  </div>
</div>

<script>
const ACTIVIDADES = <?php echo json_encode(array_values($actividades), JSON_UNESCAPED_UNICODE); ?>;
const actMap = {};
ACTIVIDADES.forEach(a => actMap[a.diag] = a);
let partidaCount = <?php echo max(count($partidas),0); ?>;

function getPct(link){
  if(!link) return 1;
  link=link.toLowerCase();
  if(link.includes('mercadolibre')) return 1.35;
  if(link.includes('ebay')) return 1.90;
  if(link.includes('compujuarez')) return 1.00;
  if(link.includes('amazon')) return 1.60;
  if(link.includes('ctonline')) return 1.45;
  return 2.50;
}
function getTipo(link){
  if(!link) return 'manoobra';
  link=link.toLowerCase();
  if(link.includes('mercadolibre')) return 'NACIONAL';
  if(link.includes('ebay')) return 'INTERNACIONAL';
  if(link.includes('compujuarez')) return 'LOCAL';
  if(link.includes('amazon')) return 'INTERNACIONAL';
  return 'NACIONAL';
}
function getEntrega(link){
  if(!link) return '';
  link=link.toLowerCase();
  if(link.includes('mercadolibre')) return 'DE 3 A 6 DÍAS';
  if(link.includes('ebay')) return 'DE 8 A 20 DÍAS';
  if(link.includes('compujuarez')) return 'DE 1 A 2 DÍAS';
  if(link.includes('amazon')) return 'DE 8 A 20 DÍAS';
  return 'DE 8 A 20 DÍAS';
}

function calcSubtotal(el){
  const p=el.closest('.partida-body');
  const precio=parseFloat(p.querySelector('.precio-hid').value)||0;
  const costoP=parseFloat(p.querySelector('.costo-p')?.value)||0;
  const costoE=parseFloat(p.querySelector('.costo-e')?.value)||0;
  const link=p.querySelector('.link-inp')?.value||'';
  const pct=getPct(link);
  let sub=precio;
  if(link){
    if(link.toLowerCase().includes('compujuarez')) sub+=((costoP+costoE)*pct);
    else sub+=Math.ceil((costoP+costoE)*pct/10)*10;
  }
  p.querySelector('.subtotal-num').textContent=sub.toFixed(2);
  p.querySelector('.subtotal-pct').innerHTML='<i class="fas fa-percentage" style="font-size:9px"></i> x'+pct.toFixed(2);
  p.querySelector('.subtotal-tipo').textContent=getTipo(link);
  const entEl=p.querySelector('.subtotal-entrega');
  if(entEl){ const e=getEntrega(link); entEl.textContent=e?('⏱ '+e):''; entEl.style.display=link?'inline-flex':'none'; }
  recalcTotal();
}

function autoFill(sel){
  const p=sel.closest('.partida-body');
  const a=actMap[sel.value];
  if(a){
    p.querySelector('.precio-txt').textContent='$'+(parseFloat(a.price||0).toFixed(2));
    p.querySelector('.precio-hid').value=a.price||0;
    p.querySelector('.solucion-txt').textContent=a.soluc||'---';
    p.querySelector('.solucion-hid').value=a.soluc||'';
  } else {
    p.querySelector('.precio-txt').textContent='$0.00';
    p.querySelector('.precio-hid').value=0;
    p.querySelector('.solucion-txt').textContent='---';
    p.querySelector('.solucion-hid').value='';
  }
  calcSubtotal(sel);
}

function setRef(btn,val){
  const p=btn.closest('.partida-body');
  p.querySelector('.req-hid').value=val;
  const btns=btn.parentElement.querySelectorAll('.toggle-opt');
  btns[0].className='toggle-opt'+(val==='SI'?' si':'');
  btns[1].className='toggle-opt'+(val==='NO'?' no':'');
  const box=p.querySelector('.ref-box');
  box.classList.toggle('visible',val==='SI');
  if(val==='NO'){
    p.querySelector('.costo-p').value=0;
    p.querySelector('.costo-e').value=0;
    p.querySelector('.link-inp').value='';
    calcSubtotal(btn);
  }
}

function recalcTotal(){
  let total=0,mo=0;
  document.querySelectorAll('.partida-body').forEach(p=>{
    total+=parseFloat(p.querySelector('.subtotal-num').textContent)||0;
    mo+=parseFloat(p.querySelector('.precio-hid').value)||0;
  });
  document.getElementById('totalVal').textContent=total.toFixed(2);
  document.getElementById('totalMO').textContent=mo.toFixed(2);
}

function plantillaPartida(n){
  const opts=ACTIVIDADES.map(a=>`<option value="${a.diag}">${a.diag}</option>`).join('');
  return `<div class="partida">
    <div class="partida-header">
      <div class="partida-num"><i class="fas fa-tools" style="margin-right:6px"></i>Partida ${n+1}</div>
      <button type="button" class="btn-del-partida" onclick="eliminarPartida(this)"><i class="fas fa-trash"></i> Quitar</button>
    </div>
    <div class="partida-body">
      <div style="display:grid;grid-template-columns:1fr 180px;gap:14px;margin-bottom:12px">
        <div class="form-group">
          <label class="fg-label">Diagnóstico / Actividad</label>
          <select name="diagnostico[]" class="sel-diag" onchange="autoFill(this)" required>
            <option value="">— Seleccionar —</option>${opts}
          </select>
        </div>
        <div class="form-group">
          <label class="fg-label">Precio Mano de Obra</label>
          <div class="field-ro"><i class="fas fa-tag" style="color:var(--azul2)"></i>
            <span class="precio-txt">$0.00</span>
            <input type="hidden" name="precio[]" class="precio-hid" value="0">
          </div>
        </div>
      </div>
      <div class="form-group full" style="margin-bottom:12px">
        <label class="fg-label">Solución</label>
        <div class="field-ro"><i class="fas fa-check-circle" style="color:var(--verde)"></i>
          <span class="solucion-txt">---</span>
          <input type="hidden" name="solucion[]" class="solucion-hid" value="">
        </div>
      </div>
      <div class="form-group full" style="margin-bottom:12px">
        <label class="fg-label">Detalle adicional <span style="color:#aaa;font-weight:400">(editable)</span></label>
        <textarea name="detalle_para_solucion[]" placeholder="Notas adicionales..."></textarea>
      </div>
      <div class="form-group" style="margin-bottom:4px">
        <label class="fg-label">¿Requiere refacción?</label>
        <div class="toggle-group">
          <div class="toggle-opt" onclick="setRef(this,'SI')"><i class="fas fa-cogs" style="margin-right:5px"></i>SÍ</div>
          <div class="toggle-opt no" onclick="setRef(this,'NO')"><i class="fas fa-times" style="margin-right:5px"></i>NO</div>
        </div>
        <input type="hidden" name="requiere_reemplazo_partes[]" class="req-hid" value="NO">
      </div>
      <div class="ref-box">
        <div class="ref-box-title"><i class="fas fa-box-open"></i>Datos de la Refacción</div>
        <div class="form-grid col2" style="margin-bottom:12px">
          <div class="form-group"><label class="fg-label">Número de Parte</label>
            <input type="text" name="numero_de_parte[]" placeholder="Ej. SR54C"></div>
          <div class="form-group"><label class="fg-label">Link del Proveedor</label>
            <input type="url" name="link[]" class="link-inp" placeholder="https://ebay.com/..." oninput="calcSubtotal(this)"></div>
        </div>
        <div class="form-grid col2">
          <div class="form-group"><label class="fg-label">Costo Proveedor $</label>
            <input type="number" name="costo_de_la_parte[]" class="costo-p" min="0" step="0.01" placeholder="0.00" oninput="calcSubtotal(this)"></div>
          <div class="form-group"><label class="fg-label">Costo de Envío $</label>
            <input type="number" name="costo_de_envio[]" class="costo-e" min="0" step="0.01" placeholder="0.00" oninput="calcSubtotal(this)"></div>
        </div>
      </div>
      <div class="subtotal-box">
        <div style="flex:1">
          <div class="subtotal-label">Total Partida</div>
          <div style="display:flex;gap:6px;flex-wrap:wrap;margin-top:5px">
            <span class="chip subtotal-pct" style="color:#1565C0"><i class="fas fa-percentage" style="font-size:9px"></i> x1.00</span>
            <span class="chip subtotal-tipo">manoobra</span>
            <span class="chip subtotal-entrega" style="display:none;color:var(--muted);font-style:italic"></span>
          </div>
        </div>
        <div class="subtotal-val">$<span class="subtotal-num">0.00</span></div>
      </div>
    </div>
  </div>`;
}

function agregarPartida(){
  document.getElementById('listaPartidas').insertAdjacentHTML('beforeend',plantillaPartida(partidaCount++));
  recalcTotal();
}
function eliminarPartida(btn){
  btn.closest('.partida').remove();
  document.querySelectorAll('.partida-num').forEach((el,i)=>{
    el.innerHTML=`<i class="fas fa-tools" style="margin-right:6px"></i>Partida ${i+1}`;
  });
  recalcTotal();
}

window.addEventListener('DOMContentLoaded',()=>{
  if(document.querySelectorAll('.partida').length===0) agregarPartida();
  recalcTotal();
});
</script>
<?php include __DIR__."/theme.php"; ?>
</body></html>