<?php
session_start();
include("../includes/auth.php");
include("../config/db.php");

if(!isset($_SESSION['user_id'])){
    header("Location: /login.php");
    exit;
}

$user_id  = intval($_SESSION['user_id']);
$is_admin = intval($_SESSION['can_manage_users'] ?? 0) === 1;
$preselect_product = intval($_GET['product_id'] ?? 0);

$camp_ids = [];
$cq = $conn->query("SELECT campaign_id FROM user_campaigns WHERE user_id='$user_id'");
while($c = $cq->fetch_assoc()) $camp_ids[] = $c['campaign_id'];

$wcamps = "";
if(!$is_admin && !empty($camp_ids)){
    $cids = implode(',', $camp_ids);
    $wcamps = "AND (p.campaign_id IS NULL OR p.campaign_id IN ($cids))";
}

$products_arr = [];
$pq = $conn->query("
SELECT p.*, cl.logo_path AS logo, cl.color_hex
FROM products p
LEFT JOIN company_logos cl ON cl.company_name = p.company_name
WHERE p.is_active = 1
AND p.product_type IN ('luz','gas','luz_gas')
$wcamps
ORDER BY p.company_name, p.product_name
");
if($pq) while($p = $pq->fetch_assoc()) $products_arr[] = $p;

$prods_json = json_encode($products_arr, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP);
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Comparativa de Factura</title>
<link rel="stylesheet" href="/assets/css/style.css">
<style>
.content-area{margin-left:260px;padding:32px 40px;background:#f8fafc;min-height:100vh;}
.page-title{font-size:32px;font-weight:800;color:#02122c;margin-bottom:6px;}
.page-subtitle{color:#64748b;margin-bottom:28px;}
.layout{display:grid;grid-template-columns:360px 1fr;gap:24px;align-items:start;}
.panel{background:#fff;border-radius:20px;padding:24px;box-shadow:0 4px 20px rgba(0,0,0,.06);margin-bottom:20px;}
.panel-title{font-size:18px;font-weight:800;color:#02122c;margin-bottom:16px;}
.upload-zone{border:2px dashed #e2e8f0;border-radius:16px;padding:28px 20px;text-align:center;cursor:pointer;transition:.2s;background:#f8fafc;margin-bottom:14px;}
.upload-zone:hover{border-color:#5b4bff;background:#f5f3ff;}
.upload-zone.done{border-color:#10b981;background:#dcfce7;}
.upload-icon{font-size:36px;margin-bottom:8px;}
.upload-text{font-size:14px;color:#64748b;}
.product-list{display:flex;flex-direction:column;gap:8px;max-height:280px;overflow-y:auto;margin-bottom:14px;}
.product-opt{display:flex;align-items:center;gap:10px;padding:10px 12px;border-radius:12px;border:1.5px solid #e2e8f0;cursor:pointer;transition:.2s;background:#f8fafc;}
.product-opt:hover{border-color:#5b4bff;background:#f5f3ff;}
.product-opt.sel{border-color:#5b4bff;background:#ede9fe;}
.product-opt input{accent-color:#5b4bff;}
.opt-name{font-size:13px;font-weight:700;color:#02122c;flex:1;}
.opt-price{font-size:12px;color:#5b4bff;font-weight:700;}
.btn-go{width:100%;height:50px;background:linear-gradient(90deg,#5b4bff,#7b61ff);color:#fff;border:none;border-radius:14px;font-size:15px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;}
.btn-go:disabled{opacity:.5;cursor:not-allowed;}
.spinner{display:inline-block;width:18px;height:18px;border:3px solid rgba(255,255,255,.3);border-top-color:#fff;border-radius:50%;animation:spin .8s linear infinite;}
@keyframes spin{to{transform:rotate(360deg);}}
.ahorro-box{border-radius:16px;padding:20px 24px;color:#fff;text-align:center;margin-bottom:20px;background:linear-gradient(135deg,#10b981,#059669);}
.ahorro-box.neg{background:linear-gradient(135deg,#ef4444,#dc2626);}
.ahorro-num{font-size:38px;font-weight:900;}
.ahorro-lbl{font-size:14px;opacity:.85;}
.ahorro-yr{font-size:15px;font-weight:700;margin-top:4px;}
.ia-box{background:#f8fafc;border-left:4px solid #5b4bff;border-radius:0 12px 12px 0;padding:16px;font-size:14px;line-height:1.7;}
.cmp-table{width:100%;border-collapse:collapse;font-size:14px;margin-bottom:16px;}
.cmp-table th{background:#f8fafc;padding:10px 12px;text-align:left;font-size:11px;font-weight:700;color:#94a3b8;text-transform:uppercase;}
.cmp-table td{padding:10px 12px;border-bottom:1px solid #f1f5f9;}
.green{color:#10b981;font-weight:800;}
.red{color:#ef4444;}
.factura{background:#fff;border-radius:16px;overflow:hidden;box-shadow:0 4px 24px rgba(0,0,0,.1);margin-bottom:16px;font-family:Arial,sans-serif;}
.fhdr{padding:20px 24px;color:#fff;}
.fhdr-row{display:flex;justify-content:space-between;align-items:center;}
.flogo{height:36px;object-fit:contain;filter:brightness(0) invert(1);}
.fcname{font-size:20px;font-weight:900;}
.fbody{padding:20px 24px;}
.fcliente{display:grid;grid-template-columns:1fr 1fr;gap:16px;margin-bottom:16px;padding-bottom:16px;border-bottom:1px solid #f1f5f9;}
.flbl{font-size:11px;color:#94a3b8;text-transform:uppercase;letter-spacing:.5px;margin-bottom:2px;}
.fval{font-size:14px;font-weight:700;color:#02122c;}
.flineas{width:100%;border-collapse:collapse;font-size:13px;margin-bottom:16px;}
.flineas th{background:#f8fafc;padding:8px 10px;text-align:left;font-size:11px;font-weight:700;color:#94a3b8;text-transform:uppercase;}
.flineas td{padding:8px 10px;border-bottom:1px solid #f8fafc;}
.ftotal{background:#f8fafc;border-radius:12px;padding:14px 18px;display:flex;justify-content:space-between;align-items:center;margin-bottom:12px;}
.ftotal-lbl{font-size:15px;font-weight:800;color:#02122c;}
.ftotal-num{font-size:26px;font-weight:900;color:#5b4bff;}
.fahorro{background:linear-gradient(135deg,#dcfce7,#d1fae5);border-radius:12px;padding:12px 18px;display:flex;justify-content:space-between;align-items:center;}
.fahorro-lbl{font-size:13px;font-weight:700;color:#166534;}
.fahorro-num{font-size:18px;font-weight:900;color:#166534;}
.ffooter{padding:14px 24px;background:#f8fafc;font-size:11px;color:#94a3b8;text-align:center;}
.btn-dl{width:100%;height:44px;background:#02122c;color:#fff;border:none;border-radius:12px;font-size:14px;font-weight:700;cursor:pointer;margin-bottom:10px;}
.btn-wa{width:100%;height:44px;background:#25d366;color:#fff;border:none;border-radius:12px;font-size:14px;font-weight:700;cursor:pointer;display:flex;align-items:center;justify-content:center;gap:8px;text-decoration:none;}
.empty-state{text-align:center;padding:60px;color:#94a3b8;}
</style>
</head>
<body>
<?php include("../includes/sidebar.php"); ?>
<div class="content-area">
<div class="page-title">Comparativa de Factura</div>
<div class="page-subtitle">Sube la factura del cliente y la IA calculara el ahorro con tu oferta</div>
<div class="layout">
  <div>
    <div class="panel">
      <div class="panel-title">Factura del cliente</div>
      <div class="upload-zone" id="zone" onclick="document.getElementById('fi').click()">
        <div class="upload-icon" id="zicon">&#128196;</div>
        <div class="upload-text" id="ztxt"><strong>Clic para subir</strong> o arrastra aqui<br>PDF o imagen (JPG, PNG)</div>
        <input type="file" id="fi" accept=".pdf,.jpg,.jpeg,.png" style="display:none">
      </div>
      <div id="prev" style="display:none;text-align:center;margin-bottom:10px;">
        <img id="ipreview" style="max-width:100%;border-radius:10px;max-height:180px;object-fit:contain;display:none;">
        <div id="ppreview" style="display:none;padding:16px;background:#f8fafc;border-radius:10px;font-size:13px;color:#5b4bff;font-weight:700;">PDF listo</div>
      </div>
    </div>
    <div class="panel">
      <div class="panel-title">Selecciona oferta</div>
      <div class="product-list" id="productList">
        <?php if(empty($products_arr)): ?>
        <div style="text-align:center;padding:20px;color:#94a3b8;">Sin productos configurados. <?php if($is_admin): ?><a href="/pages/settings_products.php" style="color:#5b4bff;">Anadir</a><?php endif; ?></div>
        <?php else: ?>
        <?php foreach($products_arr as $p): ?>
        <label class="product-opt <?= $preselect_product==$p['id']?'sel':'' ?>">
          <input type="radio" name="pid" value="<?= $p['id'] ?>" <?= $preselect_product==$p['id']?'checked':'' ?>>
          <?php if($p['logo']): ?><img src="<?= htmlspecialchars($p['logo']) ?>" style="height:22px;object-fit:contain;"><?php else: ?><span style="width:20px;height:20px;border-radius:4px;background:<?= htmlspecialchars($p['color_hex']??'#5b4bff') ?>;display:inline-block;flex-shrink:0;"></span><?php endif; ?>
          <span class="opt-name"><?= htmlspecialchars($p['company_name'].' - '.$p['product_name']) ?></span>
          <span class="opt-price"><?php if($p['precio_kwh']>0) echo number_format($p['precio_kwh']*(1-$p['descuento']/100),4).' /kWh'; elseif($p['termino_fijo']>0) echo number_format($p['termino_fijo'],2).' /mes'; ?></span>
        </label>
        <?php endforeach; ?>
        <?php endif; ?>
      </div>
      <button class="btn-go" id="btnGo" <?= empty($products_arr)?'disabled':'' ?>>
        <span id="btxt">Analizar y comparar</span>
        <span class="spinner" id="bspin" style="display:none;"></span>
      </button>
    </div>
  </div>
  <div id="right">
    <div class="panel empty-state" id="s0">
      <div style="font-size:48px;margin-bottom:12px;">&#128202;</div>
      <div style="font-size:17px;font-weight:800;color:#02122c;margin-bottom:8px;">Sube una factura para empezar</div>
      <div style="font-size:14px;">La IA leera la factura, calculara el ahorro y generara la oferta personalizada</div>
    </div>
    <div class="panel" id="s1" style="display:none;text-align:center;padding:60px;">
      <div style="font-size:40px;margin-bottom:12px;">&#129302;</div>
      <div style="font-size:17px;font-weight:800;color:#02122c;margin-bottom:8px;">Analizando factura...</div>
      <div id="lmsg" style="font-size:14px;color:#64748b;margin-bottom:16px;">Leyendo la factura</div>
      <div style="background:#f1f5f9;border-radius:8px;height:6px;width:180px;margin:0 auto;overflow:hidden;"><div id="pbar" style="background:linear-gradient(90deg,#5b4bff,#7b61ff);height:100%;width:0%;transition:width .5s;border-radius:8px;"></div></div>
    </div>
    <div id="s2" style="display:none;">
      <div id="ahorroBox" class="ahorro-box"><div class="ahorro-num" id="ahorroNum">--</div><div class="ahorro-lbl">Ahorro mensual estimado</div><div class="ahorro-yr" id="ahorroYr">-- /ano</div></div>
      <div class="panel"><div class="panel-title">Analisis IA</div><div class="ia-box" id="iaBox"></div></div>
      <div class="panel">
        <div class="panel-title">Comparativa</div>
        <table class="cmp-table"><thead><tr><th>Concepto</th><th>Actual</th><th>Nueva oferta</th><th>Diferencia</th></tr></thead><tbody id="cmpBody"></tbody></table>
      </div>
      <div class="panel">
        <div class="panel-title">Factura simulada</div>
        <div class="factura" id="factura">
          <div class="fhdr" id="fhdr">
            <div class="fhdr-row">
              <div style="display:flex;align-items:center;gap:12px;"><img id="flogo" src="" class="flogo" style="display:none"><div class="fcname" id="fcname">--</div></div>
              <div style="font-size:12px;opacity:.8;text-align:right;"><div style="font-size:15px;font-weight:800;">FACTURA ESTIMADA</div><div><?= date('d/m/Y') ?></div></div>
            </div>
          </div>
          <div class="fbody">
            <div class="fcliente">
              <div><div class="flbl">Cliente</div><div class="fval" id="fnombre">--</div></div>
              <div><div class="flbl">CUPS</div><div class="fval" id="fcups">--</div></div>
              <div><div class="flbl">Direccion</div><div class="fval" id="fdir">--</div></div>
              <div><div class="flbl">Periodo</div><div class="fval" id="fper">--</div></div>
            </div>
            <table class="flineas"><thead><tr><th>Concepto</th><th>Cantidad</th><th>Precio unit.</th><th style="text-align:right">Importe</th></tr></thead><tbody id="flineas"></tbody></table>
            <div class="ftotal"><div class="ftotal-lbl">Total con IVA (21%)</div><div class="ftotal-num" id="ftotal">--</div></div>
            <div class="fahorro"><div class="fahorro-lbl">Ahorro vs factura anterior</div><div class="fahorro-num" id="fahorro">--</div></div>
          </div>
          <div class="ffooter">Estimacion generada por CRM Wolfxell. Los precios finales pueden variar segun consumo real y condiciones de contrato.</div>
        </div>
        <button class="btn-dl" onclick="window.print()">Descargar / Imprimir</button>
        <a href="#" id="btnWA" class="btn-wa" target="_blank">Enviar por WhatsApp</a>
      </div>
    </div>
  </div>
</div>
</div>
<script>
var PRODS = <?php echo $prods_json; ?>;
var selectedFile = null;
var resultData = null;

document.getElementById('fi').addEventListener('change', function(){ handleFile(this.files[0]); });

function handleFile(f){
  if(!f) return;
  selectedFile = f;
  var z = document.getElementById('zone');
  z.classList.add('done');
  document.getElementById('zicon').innerHTML = '&#9989;';
  document.getElementById('ztxt').innerHTML = '<strong>' + f.name + '</strong><br><span style="color:#10b981">Listo</span>';
  var prev = document.getElementById('prev');
  prev.style.display = 'block';
  if(f.type.indexOf('image') === 0){
    var reader = new FileReader();
    reader.onload = function(e){
      document.getElementById('ipreview').src = e.target.result;
      document.getElementById('ipreview').style.display = 'block';
      document.getElementById('ppreview').style.display = 'none';
    };
    reader.readAsDataURL(f);
  } else {
    document.getElementById('ipreview').style.display = 'none';
    document.getElementById('ppreview').style.display = 'block';
  }
}

function getSelectedProduct(){
  var r = document.querySelector('input[name="pid"]:checked');
  if(!r) return null;
  var id = parseInt(r.value);
  for(var i=0; i<PRODS.length; i++){ if(PRODS[i].id == id) return PRODS[i]; }
  return null;
}

function showPanel(id){
  var ids = ['s0','s1','s2'];
  for(var i=0; i<ids.length; i++){
    var el = document.getElementById(ids[i]);
    if(el) el.style.display = ids[i]===id ? 'block' : 'none';
  }
}

document.getElementById('btnGo').addEventListener('click', function(){ doAnalizar(); });

function doAnalizar(){
  if(!selectedFile){ alert('Sube una factura primero.'); return; }
  var prod = getSelectedProduct();
  if(!prod){ alert('Selecciona una oferta.'); return; }

  showPanel('s1');
  document.getElementById('btnGo').disabled = true;
  document.getElementById('btxt').style.display = 'none';
  document.getElementById('bspin').style.display = 'inline-block';

  var msgs = ['Leyendo la factura...','Extrayendo datos...','Calculando ahorro...','Generando oferta...'];
  var mi = 0;
  var pb = document.getElementById('pbar');
  var lm = document.getElementById('lmsg');
  var iv = setInterval(function(){
    mi = Math.min(mi+1, msgs.length-1);
    lm.textContent = msgs[mi];
    pb.style.width = ((mi+1)/msgs.length*85) + '%';
  }, 2000);

  var reader = new FileReader();
  reader.onload = function(e){
    var b64 = e.target.result.split(',')[1];
    var isPDF = selectedFile.type === 'application/pdf';
    var mt = isPDF ? 'application/pdf' : selectedFile.type;

    var imgPart = isPDF
      ? {type:'document', source:{type:'base64', media_type:'application/pdf', data:b64}}
      : {type:'image_url', image_url:{url:'data:'+mt+';base64,'+b64}};

    var prompt = 'Analiza esta factura de energia. Luego compara con:\n' +
      'Compania: ' + prod.company_name + '\n' +
      'Producto: ' + prod.product_name + '\n' +
      'Tipo: ' + prod.product_type + '\n' +
      'Precio energia P1 EUR/kWh: ' + prod.precio_kwh + '\n' +
      'Precio energia P2 EUR/kWh: ' + prod.precio_kwh_p2 + '\n' +
      'Potencia P1 EUR/kW ano: ' + prod.precio_potencia_p1 + '\n' +
      'Potencia P2 EUR/kW ano: ' + prod.precio_potencia_p2 + '\n' +
      'Termino fijo gas EUR/mes: ' + prod.termino_fijo + '\n' +
      'Descuento energia: ' + prod.descuento + '%\n' +
      'Permanencia: ' + (prod.permanencia ? prod.meses_permanencia+' meses' : 'Sin permanencia') + '\n' +
      'Promo: ' + (prod.promo || 'Ninguna') + '\n\n' +
      'Responde SOLO JSON valido sin backticks:\n' +
      '{"cliente":{"nombre":"","cups":"","direccion":"","nif":""},"periodo":{"inicio":"","fin":"","dias":30},"factura_actual":{"compania_actual":"","tipo":"luz","consumo_kwh":0,"consumo_kwh_p2":0,"potencia_kw_p1":0,"potencia_kw_p2":0,"precio_kwh_actual":0,"precio_kwh_p2_actual":0,"precio_potencia_p1_actual":0,"precio_potencia_p2_actual":0,"termino_fijo_actual":0,"importe_energia":0,"importe_potencia":0,"importe_otros":0,"subtotal_sin_iva":0,"iva":0,"total_con_iva":0},"nueva_oferta":{"importe_energia":0,"importe_potencia":0,"termino_fijo":0,"subtotal_sin_iva":0,"iva":0,"total_con_iva":0,"ahorro_mensual":0,"ahorro_anual":0,"ahorro_porcentaje":0},"analisis_ia":"texto analisis espanol 2-3 parrafos","lineas_factura":[{"concepto":"","cantidad":"","precio_unitario":"","importe":0}]}';

    var payload = {
      model: 'gemini',
      max_tokens: 2000,
      messages: [{role:'user', content:[imgPart, {type:'text', text:prompt}]}]
    };

    fetch('/api/ai/claude_proxy.php', {
      method: 'POST',
      headers: {'Content-Type':'application/json'},
      body: JSON.stringify(payload)
    })
    .then(function(r){ return r.json(); })
    .then(function(resp){
      clearInterval(iv);
      pb.style.width = '100%';
      if(!resp.success) throw new Error(resp.error || 'Error del servidor');
      var txt = resp.data.content[0].text || '';
      var clean = txt.replace(/```json|```/g,'').trim();
      resultData = JSON.parse(clean);
      resultData.product = prod;
      setTimeout(function(){ renderResult(resultData); }, 500);
    })
    .catch(function(err){
      clearInterval(iv);
      console.error(err);
      alert('Error: ' + err.message);
      showPanel('s0');
    })
    .finally(function(){
      document.getElementById('btnGo').disabled = false;
      document.getElementById('btxt').style.display = 'inline';
      document.getElementById('bspin').style.display = 'none';
    });
  };
  reader.readAsDataURL(selectedFile);
}

function renderResult(d){
  var fa = d.factura_actual, no = d.nueva_oferta, p = d.product;
  showPanel('s2');

  var ah = no.ahorro_mensual || 0;
  var box = document.getElementById('ahorroBox');
  box.className = 'ahorro-box' + (ah < 0 ? ' neg' : '');
  document.getElementById('ahorroNum').textContent = (ah>=0?'-':'+')+'\u20ac'+Math.abs(ah).toFixed(2)+'/mes';
  document.getElementById('ahorroYr').textContent = (ah>=0?'Ahorro anual: ':'Coste adicional: ')+'\u20ac'+Math.abs(no.ahorro_anual||0).toFixed(2);
  document.getElementById('iaBox').innerHTML = (d.analisis_ia||'').replace(/\n/g,'<br>');

  var rows = [
    ['Consumo kWh', fa.consumo_kwh+' kWh', '--', '--'],
    ['Precio /kWh', '\u20ac'+fa.precio_kwh_actual, '\u20ac'+(p.precio_kwh*(1-p.descuento/100)).toFixed(5), calcDelta(fa.precio_kwh_actual, p.precio_kwh*(1-p.descuento/100))],
    ['Importe energia', '\u20ac'+fa.importe_energia, '\u20ac'+no.importe_energia, calcDelta(fa.importe_energia, no.importe_energia)],
    ['Importe potencia', '\u20ac'+fa.importe_potencia, '\u20ac'+no.importe_potencia, calcDelta(fa.importe_potencia, no.importe_potencia)],
    ['<strong>Total IVA</strong>', '<strong>\u20ac'+fa.total_con_iva+'</strong>', '<strong>\u20ac'+no.total_con_iva+'</strong>', '<strong>'+calcDelta(fa.total_con_iva, no.total_con_iva)+'</strong>'],
  ];
  document.getElementById('cmpBody').innerHTML = rows.map(function(r){
    return '<tr><td>'+r[0]+'</td><td>'+r[1]+'</td><td class="green">'+r[2]+'</td><td>'+r[3]+'</td></tr>';
  }).join('');

  var col = p.color_hex || '#5b4bff';
  document.getElementById('fhdr').style.background = 'linear-gradient(135deg,'+col+','+col+'cc)';
  document.getElementById('fcname').textContent = p.company_name;
  if(p.logo){ document.getElementById('flogo').src=p.logo; document.getElementById('flogo').style.display='block'; }
  document.getElementById('fnombre').textContent = d.cliente&&d.cliente.nombre ? d.cliente.nombre : 'Cliente';
  document.getElementById('fcups').textContent = d.cliente&&d.cliente.cups ? d.cliente.cups : '--';
  document.getElementById('fdir').textContent = d.cliente&&d.cliente.direccion ? d.cliente.direccion : '--';
  document.getElementById('fper').textContent = (d.periodo&&d.periodo.inicio?d.periodo.inicio:'')+' - '+(d.periodo&&d.periodo.fin?d.periodo.fin:'');
  document.getElementById('flineas').innerHTML = (d.lineas_factura||[]).map(function(l){
    return '<tr><td>'+l.concepto+'</td><td>'+l.cantidad+'</td><td>'+l.precio_unitario+'</td><td style="text-align:right">\u20ac'+Number(l.importe).toFixed(2)+'</td></tr>';
  }).join('');
  document.getElementById('ftotal').textContent = '\u20ac'+Number(no.total_con_iva||0).toFixed(2);
  document.getElementById('fahorro').textContent = '\u20ac'+Math.abs(ah).toFixed(2)+'/mes';

  var wamsg = encodeURIComponent('Hola! Oferta personalizada con '+p.company_name+'.\n\nFactura actual: \u20ac'+fa.total_con_iva+'/mes\nCon '+p.product_name+': \u20ac'+no.total_con_iva+'/mes\nAhorro: \u20ac'+ah.toFixed(2)+'/mes\n\nLlamanos y lo gestionamos!');
  document.getElementById('btnWA').href = 'https://wa.me/?text='+wamsg;
}

function calcDelta(v1, v2){
  var d = Number(v2)-Number(v1);
  if(isNaN(d)) return '--';
  var s = d>0?'+':'';
  var c = d>0?'red':(d<0?'green':'');
  return '<span class="'+c+'">'+s+'\u20ac'+d.toFixed(2)+'</span>';
}

// Drag and drop
var z = document.getElementById('zone');
z.addEventListener('dragover', function(e){ e.preventDefault(); z.style.borderColor='#5b4bff'; });
z.addEventListener('dragleave', function(){ z.style.borderColor=''; });
z.addEventListener('drop', function(e){
  e.preventDefault(); z.style.borderColor='';
  if(e.dataTransfer.files[0]) handleFile(e.dataTransfer.files[0]);
});

// Seleccion de producto
document.querySelectorAll('.product-opt').forEach(function(el){
  el.addEventListener('click', function(){
    document.querySelectorAll('.product-opt').forEach(function(e){ e.classList.remove('sel'); });
    el.classList.add('sel');
  });
});
</script>
</body>
</html>