<?php
if (!defined('ABSPATH')) {
  exit;
}

if (!defined('ITP_LICENSE_API_BASE')) {
  define('ITP_LICENSE_API_BASE', 'https://invalid-traffic.com/license');
}

function itp_license_get_domain(): string {
  $host = wp_parse_url(home_url(), PHP_URL_HOST);

  if (!$host) {
    return '';
  }

  $host = strtolower($host);
  $host = preg_replace('/^www\./', '', $host);
  $host = preg_replace('/:\d+$/', '', $host);

  return trim($host);
}

function itp_license_remote_request(string $endpoint, array $payload): array {
  $url = trailingslashit(ITP_LICENSE_API_BASE) . $endpoint . '.php';

  $response = wp_remote_post($url, [
    'timeout' => 15,
    'headers' => [
      'Content-Type' => 'application/json',
      'Accept' => 'application/json',
    ],
    'body' => wp_json_encode($payload),
  ]);

  if (is_wp_error($response)) {
    return [
      'success' => false,
      'code' => 'connection_error',
      'message' => $response->get_error_message(),
      'data' => [],
    ];
  }

  $body = wp_remote_retrieve_body($response);
  $json = json_decode($body, true);

  if (!is_array($json)) {
    return [
      'success' => false,
      'code' => 'invalid_response',
      'message' => 'Invalid license server response.',
      'data' => [],
    ];
  }

  return $json;
}

function itp_license_payload(string $license_key = ''): array {
  if ($license_key === '') {
    $license_key = (string) get_option('itp_license_key', '');
  }

  return [
    'license_key' => trim($license_key),
    'domain' => itp_license_get_domain(),
    'site_url' => home_url(),
    'plugin_version' => defined('ITP_VERSION') ? ITP_VERSION : '0.18.1',
    'wp_version' => get_bloginfo('version'),
    'php_version' => PHP_VERSION,
  ];
}

function itp_license_activate(string $license_key): array {
  $license_key = trim(sanitize_text_field($license_key));

  if ($license_key === '') {
    return [
      'success' => false,
      'code' => 'missing_key',
      'message' => 'License key is required.',
      'data' => [],
    ];
  }

  $result = itp_license_remote_request('activate', itp_license_payload($license_key));

  if (!empty($result['success'])) {
    update_option('itp_license_key', $license_key, false);
    update_option('itp_license_status', 'active', false);
    update_option('itp_license_data', $result['data'] ?? [], false);
    update_option('itp_license_last_check', time(), false);
    delete_transient('itp_license_cached_valid');
  } else {
    update_option('itp_license_status', 'inactive', false);
    update_option('itp_license_last_error', $result['message'] ?? 'Activation failed.', false);
    delete_transient('itp_license_cached_valid');
  }

  return $result;
}

function itp_license_check(bool $force = false): array {

  $license_key = trim((string) get_option('itp_license_key', ''));

  if ($license_key === '') {
    update_option('itp_license_status', 'inactive', false);

    return [
      'success' => false,
      'code' => 'missing_key',
      'message' => 'No license key saved.',
      'data' => [],
    ];
  }

  $result = itp_license_remote_request('check', itp_license_payload($license_key));

 if (!empty($result['success'])) {
  $license = $result['data']['license'] ?? [];
  $domain  = $result['data']['domain'] ?? [];

  $state = [
    'license_key' => $license_key,
    'active' => true,
    'status' => sanitize_text_field($license['status'] ?? 'active'),
    'plan_code' => sanitize_text_field($license['plan_code'] ?? ''),
    'billing_interval' => sanitize_text_field($license['billing_interval'] ?? ''),
    'max_domains' => (int)($license['max_domains'] ?? 1),
    'current_period_end' => (int)($license['current_period_end'] ?? 0),
    'cancel_at_period_end' => (int)($license['cancel_at_period_end'] ?? 0),
    'domain' => sanitize_text_field($domain['domain'] ?? itp_license_get_domain()),
    'domain_status' => sanitize_text_field($domain['status'] ?? 'not_activated'),
    'server_code' => sanitize_text_field($result['code'] ?? ''),
    'server_message' => sanitize_text_field($result['message'] ?? ''),
    'last_checked' => time(),
  ];

  $license_status = (string)($state['status'] ?? '');
$domain_status  = (string)($state['domain_status'] ?? '');
$period_end     = (int)($state['current_period_end'] ?? 0);

$is_really_active =
  !empty($state['active'])
  && in_array($license_status, ['active', 'trialing'], true)
  && $domain_status === 'active'
  && ($period_end === 0 || $period_end >= time());

update_option('itp_license_state', $state, false);
update_option('itp_license_status', $is_really_active ? 'active' : 'inactive', false);
update_option('itp_license_data', $result['data'] ?? [], false);
update_option('itp_license_last_check', time(), false);
delete_option('itp_license_last_error');

  delete_transient('itp_license_cached_valid');
} else {
  $notice = $result['message'] ?? 'License check failed.';

  $old = get_option('itp_license_state', []);
  if (!is_array($old)) {
    $old = [];
  }

  $old['license_key'] = $license_key;
  $old['active'] = false;
  $old['status'] = 'inactive';
  $old['domain_status'] = 'not_activated';
  $old['server_code'] = sanitize_text_field($result['code'] ?? 'license_rejected');
  $old['server_message'] = sanitize_text_field($notice);
  $old['last_checked'] = time();

  update_option('itp_license_state', $old, false);
  update_option('itp_license_status', 'inactive', false);
  update_option('itp_license_last_error', $notice, false);
  update_option('itp_license_last_check', time(), false);

  delete_transient('itp_license_cached_valid');
}

  return $result;
}

function itp_license_is_active(): bool {
  $license_key = trim((string) get_option('itp_license_key', ''));

  // Sem chave salva = bloqueado por padrão.
  if ($license_key === '') {
    update_option('itp_license_status', 'inactive', false);
    delete_transient('itp_license_cached_valid');
    return false;
  }

  $state = get_option('itp_license_state', []);

  if (!is_array($state)) {
    $state = [];
  }

  $active = !empty($state['active']);
  $status = (string)($state['status'] ?? '');
  $domain_status = (string)($state['domain_status'] ?? '');
  $period_end = (int)($state['current_period_end'] ?? 0);

  // Só libera se a licença E o domínio estiverem ativos.
  if (
    $active
    && in_array($status, ['active', 'trialing'], true)
    && $domain_status === 'active'
    && ($period_end === 0 || $period_end >= time())
  ) {
    return true;
  }

  // Se o estado local já diz que o domínio não está ativo, bloqueia direto.
  if ($domain_status !== '' && $domain_status !== 'active') {
    update_option('itp_license_status', 'inactive', false);
    delete_transient('itp_license_cached_valid');
    return false;
  }

  // Última tentativa: checa no servidor.
  $check = itp_license_check(true);

  if (empty($check['success'])) {
    return false;
  }

  $state = get_option('itp_license_state', []);

  if (!is_array($state)) {
    return false;
  }

  $active = !empty($state['active']);
  $status = (string)($state['status'] ?? '');
  $domain_status = (string)($state['domain_status'] ?? '');
  $period_end = (int)($state['current_period_end'] ?? 0);

  return $active
    && in_array($status, ['active', 'trialing'], true)
    && $domain_status === 'active'
    && ($period_end === 0 || $period_end >= time());
}

function itp_license_admin_page_is_locked(): bool {
  if (!is_admin()) {
    return false;
  }

  $page = isset($_GET['page']) ? sanitize_text_field((string) $_GET['page']) : '';

  if ($page === '' || strpos($page, 'itp-') !== 0) {
    return false;
  }

  // Auto-check em toda tela do plugin.
  // Assim, se o dono removeu o domínio na /account/,
  // o plugin descobre sozinho ao abrir qualquer menu.
  if (function_exists('itp_license_check')) {
    $license_key = trim((string) get_option('itp_license_key', ''));

    if ($license_key !== '') {
      itp_license_check(true);
    }
  }

  // A página License continua aberta para o usuário poder reativar.
  if ($page === 'itp-license') {
    return false;
  }

  return !itp_license_is_active();
}
function itp_license_render_admin_preview_gate(): void {
  if (!itp_license_admin_page_is_locked()) {
    return;
  }

  $license_url = admin_url('admin.php?page=itp-license');
  $buy_url = 'https://invalid-traffic.com/';
  ?>
  <style>
    .itp-admin-wrap.itp-license-preview-locked {
      position: relative !important;
      min-height: 760px;
      overflow: hidden;
    }

    .itp-admin-wrap.itp-license-preview-locked > *:not(.itp-license-preview-gate) {
      filter: blur(7px) saturate(.82) brightness(.92);
      opacity: .44;
      pointer-events: none !important;
      user-select: none !important;
    }

    .itp-license-preview-gate {
      position: absolute;
      inset: 0;
      z-index: 99999;
      display: flex;
      align-items: flex-start;
      justify-content: center;
      padding: 150px 22px 80px;
      background:
        radial-gradient(circle at 50% 18%, rgba(31,224,255,.20), transparent 32%),
        radial-gradient(circle at 68% 26%, rgba(111,72,255,.14), transparent 34%),
        rgba(231, 244, 251, .34);
      backdrop-filter: blur(2px);
    }

    .itp-license-preview-card {
      width: min(560px, 92vw);
      position: relative;
      overflow: hidden;
      border-radius: 30px;
      padding: 34px 32px 30px;
      text-align: center;
      color: #fff;
      background:
        linear-gradient(135deg, rgba(7,22,47,.98) 0%, rgba(3,13,31,.99) 60%, rgba(2,43,55,.98) 100%);
      border: 1px solid rgba(97, 236, 255, .20);
      box-shadow: 0 34px 95px rgba(0,0,0,.32), inset 0 1px 0 rgba(255,255,255,.08);
    }

    .itp-license-preview-card:before {
      content: "";
      position: absolute;
      right: -90px;
      top: -110px;
      width: 270px;
      height: 270px;
      border-radius: 999px;
      background: radial-gradient(circle, rgba(34,230,255,.30), transparent 68%);
    }

    .itp-license-preview-card:after {
      content: "";
      position: absolute;
      left: -90px;
      bottom: -130px;
      width: 290px;
      height: 290px;
      border-radius: 999px;
      background: radial-gradient(circle, rgba(106,72,255,.24), transparent 68%);
    }

    .itp-license-preview-inner {
      position: relative;
      z-index: 2;
    }

    .itp-license-preview-icon {
      width: 62px;
      height: 62px;
      margin: 0 auto 17px;
      border-radius: 22px;
      display: grid;
      place-items: center;
      font-size: 28px;
      background: linear-gradient(135deg, #22e6ff 0%, #6d48ff 100%);
      box-shadow: 0 16px 38px rgba(34,230,255,.23);
    }

    .itp-license-preview-kicker {
      display: inline-flex;
      align-items: center;
      justify-content: center;
      margin: 0 0 12px;
      padding: 7px 12px;
      border-radius: 999px;
      color: #64efff;
      background: rgba(100,239,255,.09);
      border: 1px solid rgba(100,239,255,.18);
      font-size: 11px;
      font-weight: 950;
      letter-spacing: .14em;
      text-transform: uppercase;
    }

    .itp-license-preview-card h2 {
      margin: 0 0 12px;
      color: #fff;
      font-size: 34px;
      line-height: 1.04;
      letter-spacing: -.04em;
      font-weight: 1000;
    }

    .itp-license-preview-card p {
      max-width: 455px;
      margin: 0 auto 23px;
      color: rgba(255,255,255,.76);
      font-size: 14px;
      line-height: 1.65;
    }

    .itp-license-preview-mini {
      display: grid;
      grid-template-columns: repeat(3, 1fr);
      gap: 10px;
      margin: 0 0 24px;
    }

    .itp-license-preview-mini span {
      border-radius: 16px;
      padding: 12px 10px;
      background: rgba(255,255,255,.06);
      border: 1px solid rgba(255,255,255,.08);
      color: rgba(255,255,255,.84);
      font-size: 12px;
      font-weight: 850;
      line-height: 1.25;
    }

    .itp-license-preview-actions {
      display: flex;
      justify-content: center;
      gap: 12px;
      flex-wrap: wrap;
      margin: 0 0 12px;
    }

    .itp-license-preview-btn {
      min-width: 178px;
      min-height: 50px;
      display: inline-flex;
      align-items: center;
      justify-content: center;
      gap: 8px;
      border-radius: 999px;
      padding: 0 22px;
      font-size: 14px;
      font-weight: 950;
      text-decoration: none !important;
      transition: transform .18s ease, opacity .18s ease;
    }

    .itp-license-preview-btn:hover {
      transform: translateY(-2px);
      opacity: .96;
    }

    .itp-license-preview-primary {
      color: #041124 !important;
      background: linear-gradient(90deg, #22e6ff 0%, #20c8ff 100%);
      box-shadow: 0 14px 30px rgba(34,230,255,.25);
    }

    .itp-license-preview-secondary {
      color: #041124 !important;
      background: #fff;
    }

    .itp-license-preview-note {
      color: rgba(255,255,255,.56);
      font-size: 12px;
      line-height: 1.5;
    }

    @media (max-width: 782px) {
      .itp-license-preview-gate { padding: 95px 16px 50px; }
      .itp-license-preview-card { padding: 28px 20px 24px; border-radius: 24px; }
      .itp-license-preview-card h2 { font-size: 28px; }
      .itp-license-preview-mini { grid-template-columns: 1fr; }
      .itp-license-preview-btn { width: 100%; }
    }
  </style>
  <script>
    document.addEventListener('DOMContentLoaded', function () {
      var wrap = document.querySelector('.itp-admin-wrap');
      if (!wrap || wrap.classList.contains('itp-license-preview-locked')) return;

      wrap.classList.add('itp-license-preview-locked');

      var gate = document.createElement('div');
      gate.className = 'itp-license-preview-gate';
      gate.innerHTML = `
        <div class="itp-license-preview-card" role="dialog" aria-modal="true" aria-label="Invalid Traffic license required">
          <div class="itp-license-preview-inner">
            <div class="itp-license-preview-icon">🔒</div>
            <div class="itp-license-preview-kicker">Preview mode</div>
            <h2>Unlock Invalid Traffic<br>with your license.</h2>
            <p>You can preview the plugin screen behind this layer, but bridges, analytics, live signals, reports and campaign tools require an active license.</p>
            <div class="itp-license-preview-mini">
              <span>Bridge pages</span>
              <span>Traffic quality</span>
              <span>Evidence reports</span>
            </div>
            <div class="itp-license-preview-actions">
              <a class="itp-license-preview-btn itp-license-preview-primary" href="<?php echo esc_url($license_url); ?>">Activate license</a>
              <a class="itp-license-preview-btn itp-license-preview-secondary" href="<?php echo esc_url($buy_url); ?>" target="_blank" rel="noopener noreferrer">Buy license</a>
            </div>
            <div class="itp-license-preview-note">Already purchased? Click <strong>Activate license</strong> and paste your key.</div>
          </div>
        </div>
      `;

      wrap.appendChild(gate);
    });
  </script>
  <?php
}

add_action('admin_footer', 'itp_license_render_admin_preview_gate', 999);
