<?php
require_once __DIR__.'/api/generar_codigo.php';
$protocolo = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? "https://" : "http://";
$host = $_SERVER['HTTP_HOST'];
$path = rtrim(dirname($_SERVER['PHP_SELF']), '/\\');
$urlActivacion = $protocolo . $host . $path . "/activar_publico.php";

$mostrarModal = false;
$codigoGenerado = '';
$macGenerada = '';
$cliente_whatsapp = '';
$mensajeWhatsApp = '';

if (isset($_GET['success'], $_GET['codigo'], $_GET['mac'])) {
    $mostrarModal = true;
    $codigoGenerado = $_GET['codigo'];
    $macGenerada = $_GET['mac'];
    $cliente_whatsapp = $_GET['whatsapp'] ?? '';
    $cliente_nombre = $_GET['nombre'] ?? '';
    $expiracion = $_GET['expiracion'] ?? '';

    // Mensaje para enviar por WhatsApp
    $mensajeWhatsApp = "Hola $cliente_nombre 👋\n\nAquí tienes tu código de acceso IPTV:\n\n🔑 Código: $codigoGenerado\n🖥️ MAC: $macGenerada\n📅 Válido hasta: $expiracion\n\n✅ Activa tu código aquí: $urlActivacion\n\n¡Gracias por preferirnos!";
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Generar Código — Público</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://kit.fontawesome.com/4fa1f3b6b2.js" crossorigin="anonymous"></script>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <style>
    body {
      font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
      padding: 20px;
      background: linear-gradient(to right, #0f2027, #203a43, #2c5364);
      color: #f0f0f0;
      min-height: 100vh;
    }
    .container {
      max-width: 600px;
      margin: auto;
      background: #1e1e2f;
      padding: 30px 25px;
      border-radius: 14px;
      box-shadow: 0 15px 40px rgba(0, 0, 0, 0.4);
    }
    h2, h1 {
      text-align: center;
      margin-bottom: 25px;
      color: #ffffff;
      font-weight: 600;
    }
    button {
      background-color: #00c851;
      color: white;
      font-weight: bold;
      font-size: 16px;
      border: none;
      transition: background-color 0.3s ease;
    }
    button:hover {
      background-color: #007e33;
    }
    .alert {
      background-color: #1c352d;
      color: #28a745;
      padding: 12px;
      border-radius: 6px;
      margin-top: 10px;
      border-left: 4px solid #28a745;
    }
    .alert.error {
      background-color: #3b1f1f;
      color: #e74c3c;
      border-left-color: #e74c3c;
    }
  </style>
</head>
<body class="bg-dark text-light">
<div class="container py-5">
  <h1 class="text-center mb-4">🎯 Generar Códigos</h1>
  <?php if ($error): ?>
    <div class="alert alert-danger"><?= htmlspecialchars($error) ?></div>
  <?php endif; ?>

  <?php if ($mostrarModal && $codigoGenerado && $macGenerada): ?>
  <!-- Modal -->
  <div class="modal fade" id="codigoModal" tabindex="-1" aria-labelledby="codigoModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content border-success">
        <div class="modal-header bg-success text-white">
          <h5 class="modal-title" id="codigoModalLabel">✅ ¡Código generado con éxito!</h5>
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Cerrar"></button>
        </div>
        <div class="modal-body text-center">
          <div class="alert alert-info">
            <p>
              🔑 <strong>Código:</strong>
              <span id="codigoGenerado"><?= htmlspecialchars($codigoGenerado) ?></span>
              <button class="btn btn-sm btn-outline-primary ms-2" id="btnCopiarCodigo" title="Copiar código">📋 Copiar</button>
            </p>
            <p>🖥️ <strong>MAC:</strong> <?= htmlspecialchars($macGenerada) ?></p>
          </div>
        </div>
        <div class="modal-footer justify-content-center flex-wrap">
          <button type="button" class="btn btn-success m-1" data-bs-dismiss="modal">Aceptar</button>
          <a href="activar_publico.php" class="btn btn-primary m-1">🚀 Activar</a>
          <a href="https://wa.me/<?= urlencode($cliente_whatsapp) ?>?text=<?= urlencode($mensajeWhatsApp) ?>" target="_blank" class="btn btn-success m-1" style="background-color: #25D366; border-color: #25D366;">💬 Enviar por WhatsApp</a>
        </div>
      </div>
    </div>
  </div>
  <?php endif; ?>

  <form id="formGen" method="POST" action="api/generar_codigo.php">
    <?php
    $fields = [
      ['mac_address','MAC','text','id="mac_address" pattern="^([0-9A-F]{2}[:-]){2,7}[0-9A-F]{2}$" placeholder="Mac del dispositivo"','',''],
      ['username','Usuario','text','minlength="3" maxlength="20"','',''],
      ['password','Contraseña','text','minlength="4"','',''],
      ['dns_id','Servidor DNS','select','','',''],
      ['cliente_nombre','Nombre cliente','text','minlength="2" maxlength="50"','',''],
      ['cliente_whatsapp','WhatsApp (código país)','text','pattern="^\\+?[0-9]{7,15}$" placeholder="Ejemplo: 593980649398"','',''],
      ['expiracion','Vencimiento','date','min="'.date('Y-m-d').'"','',''],
    ];
    foreach($fields as $f):
      if ($f[2]==='select'): ?>
        <div class="mb-3">
          <label class="form-label"><?=$f[1]?></label>
          <select id="dns_id" name="dns_id" class="form-select" required>
            <option value="">Cargando DNS...</option>
          </select>
        </div>
      <?php else: ?>
        <div class="mb-3">
          <label class="form-label"><?=$f[1]?></label>
          <input type="<?=$f[2]?>" name="<?=$f[0]?>" class="form-control" <?=$f[3]?> required>
        </div>
      <?php endif;
    endforeach;
    ?>
    <div class="form-check mb-3">
      <input type="checkbox" id="is_protected" name="is_protected" class="form-check-input" value="1">
      <label class="form-check-label" for="is_protected"><i class="fas fa-lock"></i> 🔐Proteger lista (evita edicion en la app)</label>
    </div>
    <button class="btn btn-success w-100"><i class="fas fa-key"></i> Generar</button>
  </form>
</div>

<script>
$(function(){
  $.getJSON('api/generar_codigo.php?ajax=dns', function(res){
    if(res.success){
      let opt = '<option value="">Seleccione DNS...</option>';
      res.dns.forEach(d => opt += `<option value="${d.id}">${d.title}</option>`);
      $('#dns_id').html(opt);
    } else {
      $('#dns_id').html('<option>Error cargando DNS</option>');
    }
  });
  $('#mac_address').on('input', function() {
    let value = $(this).val().toUpperCase().replace(/[^0-9A-F]/g, '');
    let formatted = '';
    for (let i = 0; i < value.length; i++) {
      if (i > 0 && i % 2 === 0) formatted += ':';
      formatted += value[i];
    }
    $(this).val(formatted);
  });

  // Validación MAC al enviar
  $('#formGen').on('submit',function(e){
    let mac = $('#mac_address').val().trim();
    let pat = /^([0-9A-F]{2}[:-]){2,7}[0-9A-F]{2}$/i;
    if(!pat.test(mac)) {
      alert('MAC inválida. Debe tener entre 3 y 7 pares de caracteres hexadecimales separados por :');
      e.preventDefault();
    }
  });
  <?php if ($mostrarModal && $codigoGenerado && $macGenerada): ?>
  var modal = new bootstrap.Modal(document.getElementById('codigoModal'));
  modal.show();

  document.getElementById("btnCopiarCodigo").addEventListener("click", function() {
    var codigo = document.getElementById("codigoGenerado").textContent;
    navigator.clipboard.writeText(codigo).then(() => {
      this.textContent = "✅ Copiado";
      setTimeout(() => { this.textContent = "📋 Copiar"; }, 2000);
    });
  });
  <?php endif; ?>
});
</script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>
