<?php
session_start();

if (!isset($_SESSION['loggedin']) || $_SESSION['loggedin'] !== true) {
    header('Location: index.php');
    exit;
}

include('includes/header.php');

// Función para normalizar MAC
function normalise_mac(string $raw): string {
    $raw = trim($raw);
    if (strpos($raw, '00:') === 0) $raw = substr($raw, 3);
    $hex = preg_replace('/[^0-9a-fA-F]/', '', $raw);
    $pairs = array_filter(str_split($hex, 2), fn($p) => strlen($p) === 2);
    return strtoupper(implode(':', $pairs));
}

// Función para generar código de 8 dígitos numéricos
function generar_codigo(): string {
    $chars = '0123456789';
    $codigo = '';
    for ($i = 0; $i < 8; $i++) {
        $codigo .= $chars[random_int(0, 9)];
    }
    return $codigo;
}

// Variables
$codigo_activacion = '';
$mensaje_whatsapp = '';
$modal_script = '';
$alerta_error = '';

// Procesar formulario
if (isset($_POST['generar_codigo'])) {

    $mac_raw = $_POST['mac_address'] ?? '';
    $dns_id = $_POST['dns_id'] ?? '';
    $username = $_POST['username'] ?? '';
    $password = $_POST['password'] ?? '';
    $pin = $_POST['pin'] ?? '0000';
    $device_key = $_POST['device_key'] ?? '';

    // Generate device key if not provided
    if (empty($device_key)) {
        $chars = '1234567890';
        $device_key = '';
        for ($i = 0; $i < 8; $i++) {
            $device_key .= $chars[random_int(0, strlen($chars) - 1)];
        }
    }

    // Validaciones básicas
    if (trim($mac_raw) === '' || trim($username) === '' || trim($password) === '' || $dns_id === '') {
        $alerta_error = "Por favor completa todos los campos obligatorios.";
    } else {
        $mac_normalizada = normalise_mac($mac_raw);
        $codigo_activacion = generar_codigo();

        // Preparar URL y mensaje de WhatsApp
        $is_https = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') || (isset($_SERVER['SERVER_PORT']) && $_SERVER['SERVER_PORT'] == 443);
        $scheme = $is_https ? 'https' : 'http';
        $host = $_SERVER['HTTP_HOST'] ?? 'localhost';
        $dir  = rtrim(dirname($_SERVER['PHP_SELF'] ?? ''), '/\\');
        $base = $dir ? "$scheme://$host$dir" : "$scheme://$host";
        $url_activacion = $base . "/activar_public.php";

        $mensaje_whatsapp = "🚀 *Estimado cliente se ha generado un código para la*
📡 MAC: *$mac_normalizada*

Tu *código de activación* es: 
🔐 *$codigo_activacion*

✅ Copia tu código y activa tu servicio aquí:
👉 $url_activacion

☺️ *Gracias por preferirnos*.";


        // Guardar en codes.db
        $api_db_path = __DIR__ . '/api/codes.db';
        $api_db = new SQLite3($api_db_path);

        $api_db->exec("CREATE TABLE IF NOT EXISTS codes (
            id INTEGER PRIMARY KEY AUTOINCREMENT,
            mac_address TEXT NOT NULL,
            dns_id INTEGER NOT NULL,
            username TEXT NOT NULL,
            password TEXT NOT NULL,
            pin TEXT DEFAULT '0000',
            device_key TEXT,
            codigo TEXT NOT NULL,
            estado INTEGER DEFAULT 0,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP
        )");

        $insert = $api_db->prepare("INSERT INTO codes (mac_address, dns_id, username, password, pin, device_key, codigo, estado) 
                            VALUES (:mac, :dns_id, :username, :password, :pin, :device_key, :codigo, 0)");
        $insert->bindValue(':mac', $mac_normalizada, SQLITE3_TEXT);
        $insert->bindValue(':dns_id', $dns_id, SQLITE3_INTEGER);
        $insert->bindValue(':username', $username, SQLITE3_TEXT);
        $insert->bindValue(':password', $password, SQLITE3_TEXT);
        $insert->bindValue(':pin', $pin, SQLITE3_TEXT);
        $insert->bindValue(':device_key', $device_key, SQLITE3_TEXT);
        $insert->bindValue(':codigo', $codigo_activacion, SQLITE3_TEXT);
        $insert->execute();
        $api_db->close();

        // Script para mostrar modal automáticamente (SIN Bootstrap)
        $modal_script = "<script>
            window.addEventListener('DOMContentLoaded', function () {
                if (typeof abrirModal === 'function') { abrirModal(); }
            });
        </script>";
    }
}

// Obtener DNS de la DB
$dnss = $db->select('dns', '*', '', '');
?>

<div class="col-md-8 mx-auto">
    <div class="card-body">
        <div class="card bg-primary text-white">
            <div class="card-header card-header-warning">
                <center><h2><i class="icon icon-bullhorn"></i> Generar Código de Activación</h2></center>
            </div>
            <div class="card-body">

                <?php if ($alerta_error): ?>
                    <div class="alert alert-danger" style="background:#f8d7da;color:#842029;border:1px solid #f5c2c7;padding:10px;border-radius:8px;">
                        <?= htmlspecialchars($alerta_error, ENT_QUOTES, 'UTF-8') ?>
                    </div>
                <?php endif; ?>

                <form method="post">
                    <div class="form-group">
                        <label class="form-label">DNS</label>
                        <select class="form-control" name="dns_id" required>
                            <option value="">Seleccionar DNS</option>
                            <?php foreach ($dnss as $dns): ?>
                                <option value="<?= htmlspecialchars($dns['id'], ENT_QUOTES, 'UTF-8') ?>">
                                    <?= htmlspecialchars($dns['title'], ENT_QUOTES, 'UTF-8') ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                    </div>

                    <div class="form-group">
                        <label class="form-label">MAC Address</label>
                        <input class="form-control" name="mac_address" placeholder="MAC Address" type="text" required />
                    </div>

                    <div class="form-group">
                        <label class="form-label">Username</label>
                        <input class="form-control" name="username" placeholder="Username" type="text" required />
                    </div>

                    <div class="form-group">
                        <label class="form-label">Password</label>
                        <input class="form-control" name="password" placeholder="Password" type="text" required />
                    </div>

                    <div class="form-group">
                        <label class="form-label">Parental Pin</label>
                        <input class="form-control" name="pin" placeholder="Parental Pin" type="text" value="0000" />
                    </div>

                    <div class="form-group">
                        <center>
                            <button class="btn btn-info" name="generar_codigo" type="submit" style="background:#0dcaf0;border:none;padding:10px 16px;border-radius:8px;color:#000;cursor:pointer;">
                                <i class="icon icon-check"></i> Generar Código
                            </button>
                        </center>
                    </div>
                </form>

            </div>
        </div>
    </div>
</div>

<!-- Modal SIN Bootstrap -->
<div id="codigoModal" class="custom-modal" aria-hidden="true" role="dialog" aria-labelledby="codigoModalTitulo">
  <div class="custom-modal-content" role="document">
    <div class="custom-modal-header">
      <h2 id="codigoModalTitulo">Código de Activación Generado</h2>
      <button type="button" class="custom-close" aria-label="Cerrar" onclick="cerrarModal()">&times;</button>
    </div>

    <div class="custom-modal-body">
      <?php if ($codigo_activacion): ?>
        <p style="margin:0 0 8px 0;">Comparte o guarda este código:</p>
        <h3 id="codigo_text" style="letter-spacing:2px;margin:0;"><strong><?= htmlspecialchars($codigo_activacion, ENT_QUOTES, 'UTF-8') ?></strong></h3>
        <div class="btn-group" style="margin-top:14px;">
          <button type="button" onclick="copiarCodigo()">📋 Copiar Código</button>
          <a href="https://api.whatsapp.com/send?text=<?= urlencode($mensaje_whatsapp) ?>" target="_blank" rel="noopener">📲 WhatsApp</a>
        </div>
      <?php else: ?>
        <p>No hay código generado en este momento.</p>
      <?php endif; ?>
    </div>

    <div class="custom-modal-footer">
      <button type="button" onclick="cerrarModal()">Cerrar</button>
    </div>
  </div>
</div>

<style>
/* Evita scroll del body cuando el modal está abierto */
body.modal-open { overflow: hidden; }

.custom-modal {
  display: none;
  position: fixed;
  z-index: 100000;
  inset: 0;
  background: rgba(0,0,0,0.7);
  justify-content: center;
  align-items: center;
  padding: 12px;
}

.custom-modal-content {
  background: #2c2c2c;
  color: #fff;
  padding: 20px;
  width: 100%;
  max-width: 420px;
  border-radius: 14px;
  box-shadow: 0 10px 30px rgba(0,0,0,0.6);
  animation: showModal 0.25s ease-out;
}

.custom-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
  border-bottom: 1px solid #444;
  padding-bottom: 8px;
}

.custom-close {
  cursor: pointer;
  font-size: 22px;
  font-weight: bold;
  color: #fff;
  background: transparent;
  border: none;
  line-height: 1;
}

.custom-modal-body {
  text-align: center;
  margin: 18px 0 8px 0;
}

.custom-modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  border-top: 1px solid #444;
  padding-top: 10px;
}

.btn-group {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.btn-group button,
.btn-group a,
.custom-modal-footer button {
  background: #0d6efd;
  color: #fff;
  border: none;
  padding: 9px 14px;
  border-radius: 10px;
  cursor: pointer;
  text-decoration: none;
  transition: transform .06s ease, opacity .2s ease, background .2s ease;
}

.btn-group a { background: #25D366; }
.btn-group a:hover { background: #1ea851; }
.btn-group button:hover,
.custom-modal-footer button:hover { background: #0b5ed7; }
.btn-group button:active,
.custom-modal-footer button:active,
.btn-group a:active { transform: scale(0.98); }

@keyframes showModal {
  from { transform: translateY(6px); opacity: 0; }
  to   { transform: translateY(0);   opacity: 1; }
}
</style>

<script>
function abrirModal() {
  const modal = document.getElementById('codigoModal');
  if (!modal) return;
  modal.style.display = 'flex';
  document.body.classList.add('modal-open');
  const closeBtn = modal.querySelector('.custom-close');
  if (closeBtn) closeBtn.focus();
}

function cerrarModal() {
  const modal = document.getElementById('codigoModal');
  if (!modal) return;
  modal.style.display = 'none';
  document.body.classList.remove('modal-open');
}

function copiarCodigo() {
  const el = document.getElementById('codigo_text');
  const codigo = el ? el.innerText.trim() : '';
  if (!codigo) return;
  navigator.clipboard.writeText(codigo).then(() => {
    alert('✅ Código copiado al portapapeles');
  }).catch(() => {
    alert('⚠️ Error al copiar el código');
  });
}

window.addEventListener('click', function(e) {
  const modal = document.getElementById('codigoModal');
  if (!modal) return;
  if (e.target === modal) cerrarModal();
});

window.addEventListener('keydown', function(e) {
  const modal = document.getElementById('codigoModal');
  if (!modal || modal.style.display !== 'flex') return;
  if (e.key === 'Escape') cerrarModal();
});
</script>

<?php
echo $modal_script;
include('includes/footer.php');
?>
