<?php
if (!defined('ABSPATH')) exit;
if (!current_user_can('manage_options')) return;

$msg = ''; $msg_type = '';
$license_key    = get_option('gtbogo_license_key', '');
$license_status = get_option('gtbogo_license_status', '');
$license_exp    = get_option('gtbogo_license_expires', '');
$is_pro         = $license_status === 'active';

// Activation handled via AJAX — no page reload needed

// Handle deactivate
if (isset($_POST['gtbogo_deactivate']) && check_admin_referer('gtbogo_license_nonce', 'gtbogo_nonce')) {
    update_option('gtbogo_license_key', '');
    update_option('gtbogo_license_status', '');
    update_option('gtbogo_license_expires', '');
    delete_transient('gtbogo_license_verified');
    $license_key = ''; $license_status = ''; $is_pro = false;
    $msg = 'License deactivated. You can reactivate at any time.'; $msg_type = 'info';
}

$days_left = $is_pro && $license_exp ? (int)ceil((strtotime($license_exp) - time()) / 86400) : 0;

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
  <div>
    <h1 class="gt-page-title">🔑 License</h1>
    <p class="gt-page-subtitle">Activate your PRO license, Pro Pack keys, and bundle keys</p>
  </div>
  <?php if ($is_pro): ?>
  <span class="gt-badge gt-badge-active"><span class="gt-dot gt-dot-green" style="width:6px;height:6px"></span> PRO Active</span>
  <?php endif; ?>
</div>

<div id="gt-license-result" style="display:none;margin-bottom:20px"></div>

<?php if ($is_pro): ?>
<!-- Active License Status -->
<div class="gt-card-premium gt-animate-in">
  <div class="gt-card-header">
    <h2 class="gt-card-title">License Status</h2>
    <span class="gt-badge <?php echo $days_left > 0 && $days_left <= 14 ? 'gt-badge-expiring' : 'gt-badge-active'; ?>">
      <?php echo $days_left > 0 && $days_left <= 14 ? '⚠ Expiring Soon' : '✓ Active'; ?>
    </span>
  </div>
  <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px">
    <div>
      <div class="gt-card-label">License Key</div>
      <div class="gt-mono" style="font-size:13px;color:var(--gt-white)"><?php echo esc_html(substr($license_key,0,24).'...'); ?></div>
    </div>
    <div>
      <div class="gt-card-label">Expires</div>
      <div style="font-size:16px;font-weight:700;color:var(--gt-white)"><?php echo esc_html( $license_exp ) ? esc_html(gmdate('M j, Y',strtotime($license_exp))) : '—'; ?></div>
      <?php if ($days_left > 0): ?><div class="gt-text-xs gt-soft"><?php echo (int)$days_left; ?> days remaining</div><?php endif; ?>
    </div>
    <div>
      <div class="gt-card-label">PRO Features</div>
      <div class="gt-flex gt-gap-sm"><span class="gt-dot gt-dot-green"></span><span style="color:var(--gt-green);font-weight:700">Unlocked</span></div>
    </div>
  </div>
  <?php if ($days_left > 0 && $days_left <= 14): ?>
  <div style="margin-top:20px;padding-top:16px;border-top:1px solid var(--gt-border);display:flex;justify-content:flex-end">
    <a href="https://graphictshirts.shop/bogo/" target="_blank" class="gt-btn gt-btn-primary">Renew License Now →</a>
  </div>
  <?php endif; ?>
</div>

<!-- ── Pack Key Activation (PRO only) ─────────────────────────────────── -->
<div class="gt-card gt-animate-in">
  <div class="gt-card-header">
    <h2 class="gt-card-title">Activate a Pro Pack</h2>
    <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=my-packs')); ?>" class="gt-btn gt-btn-ghost gt-btn-sm">My Packs →</a>
  </div>
  <p class="gt-text-sm gt-soft" style="margin:0 0 20px">After purchasing a Pro Pack or bundle, enter the key from your confirmation email to activate and import the rules.</p>
  <div style="display:flex;gap:12px;align-items:flex-start;flex-wrap:wrap;margin-bottom:14px">
    <input type="text" id="gt-pack-key-input"
      placeholder="PACK-XXXXXXXXXXXXXXXXXXXX or GTBOGO-BUNDLE-XXXXXXXXXXXXXXXX"
      class="gt-input gt-mono"
      style="flex:1;min-width:280px;font-size:13px;letter-spacing:.05em;text-transform:uppercase">
    <button id="gt-activate-pack-btn" class="gt-btn gt-btn-primary" style="flex-shrink:0">Activate Key</button>
  </div>
  <div id="gt-pack-key-result" style="display:none"></div>
  <p class="gt-form-hint" style="margin-top:8px">
    Pack keys start with <code style="background:rgba(255,255,255,0.06);padding:2px 6px;border-radius:4px">PACK-</code> · 
    Bundle keys start with <code style="background:rgba(255,255,255,0.06);padding:2px 6px;border-radius:4px">GTBOGO-BUNDLE-</code> · 
    <a href="https://graphictshirts.shop/bogo/retrieve-license.php" target="_blank" style="color:var(--gt-red);text-decoration:none;font-weight:600">Lost your key?</a>
  </p>
</div>

<script>
(function() {
  var btn = document.getElementById('gt-activate-pack-btn');
  var inp = document.getElementById('gt-pack-key-input');
  var res = document.getElementById('gt-pack-key-result');
  if (!btn || !inp) return;

  function showResult(type, msg) {
    var colors = {success:'rgba(34,197,94,0.08)', error:'rgba(239,68,68,0.08)', info:'rgba(59,130,246,0.08)'};
    var borders = {success:'rgba(34,197,94,0.3)', error:'rgba(239,68,68,0.3)', info:'rgba(59,130,246,0.3)'};
    var textcols = {success:'#86efac', error:'#fca5a5', info:'#93c5fd'};
    res.style.display = 'block';
    res.style.padding = '12px 16px';
    res.style.borderRadius = '8px';
    res.style.background = colors[type] || colors.info;
    res.style.border = '1px solid ' + (borders[type] || borders.info);
    res.style.color = textcols[type] || textcols.info;
    res.style.fontSize = '13px';
    res.style.lineHeight = '1.6';
    res.innerHTML = msg;
  }

  btn.addEventListener('click', function() {
    var key = inp.value.trim().toUpperCase();
    if (!key) { showResult('error', 'Enter a key first.'); return; }
    if (!key.match(/^(GTBOGO-)?(PACK-|BUNDLE-)[A-F0-9]{10,}/i) && !key.match(/^GTBOGO-BUNDLE-/i)) {
      showResult('error', 'Invalid format. Pack keys start with PACK- · Bundle keys start with GTBOGO-BUNDLE-');
      return;
    }
    btn.textContent = 'Activating...';
    btn.disabled = true;
    var fd = new FormData();
    var action = key.indexOf('BUNDLE') !== -1 ? 'gtbogo_activate_bundle_key' : 'gtbogo_activate_pack_key';
    fd.append('action', action);
    fd.append('nonce', '<?php echo esc_js(wp_create_nonce("gtbogo_activate_pack_key")); ?>');
    fd.append('pack_key', key);
    fetch(ajaxurl, {method:'POST', body:fd})
      .then(function(r){return r.json();})
      .then(function(d) {
        btn.textContent = 'Activate Key';
        btn.disabled = false;
        if (d.success) {
          showResult('success', '&#10003; ' + (d.data && d.data.message ? d.data.message : 'Key activated and rules imported successfully.') +
            ' <a href="<?php echo esc_js(admin_url("admin.php?page=gt-bogo-engine&tab=my-packs")); ?>" style="color:#86efac;font-weight:700">View My Packs →</a>');
          inp.value = '';
        } else {
          showResult('error', '&#10007; ' + (d.data && d.data.message ? d.data.message : 'Activation failed. Check the key and try again.'));
        }
      })
      .catch(function() {
        btn.textContent = 'Activate Key';
        btn.disabled = false;
        showResult('error', 'Connection error. Please try again.');
      });
  });

  inp.addEventListener('keydown', function(e) { if (e.key === 'Enter') btn.click(); });
})();
</script>



<?php else: ?>
<!-- Activation Form -->
<div class="gt-card-premium gt-animate-in">
  <div class="gt-card-header"><h2 class="gt-card-title">Activate a Key</h2></div>
  <p class="gt-text-sm gt-soft" style="margin-bottom:24px">Enter any key from your purchase email. All three key types are accepted here.</p>
  <div class="gt-form-group">
    <label class="gt-form-label">License Key</label>
    <div style="display:flex;gap:10px;align-items:flex-start;flex-wrap:wrap;max-width:600px">
      <input type="text" id="gt-license-key-input" class="gt-input gt-mono"
        style="flex:1;min-width:260px;font-size:14px;letter-spacing:1px;text-transform:uppercase"
        placeholder="GTBOGO-XXXX-XXXX or PACK-XXXXXXXXXXXX or GTBOGO-BUNDLE-XXXXXXXX"
        value="">
      <button id="gt-license-activate-btn" class="gt-btn gt-btn-primary" style="flex-shrink:0">🔑 Activate Key</button>
    </div>
    <p class="gt-form-hint" style="margin-top:10px">
      <code style="background:rgba(255,255,255,0.06);padding:2px 6px;border-radius:4px">GTBOGO-XXXX-XXXX-XXXX-XXXX</code> PRO License &nbsp;·&nbsp;
      <code style="background:rgba(255,255,255,0.06);padding:2px 6px;border-radius:4px">PACK-XXXXXXXXXXXX</code> Pro Pack &nbsp;·&nbsp;
      <code style="background:rgba(255,255,255,0.06);padding:2px 6px;border-radius:4px">GTBOGO-BUNDLE-XXXXXXXX</code> Bundle<br>
      <a href="https://graphictshirts.shop/bogo/retrieve-license.php" target="_blank" style="color:var(--gt-red);text-decoration:none;font-weight:600">Lost your key? Retrieve it →</a>
    </p>
  </div>

<script>
(function() {
  var inp = document.getElementById('gt-license-key-input');
  var btn = document.getElementById('gt-license-activate-btn');
  var res = document.getElementById('gt-license-result');
  if (!btn || !inp) return;

  inp.addEventListener('input', function() {
    var p = this.selectionStart;
    this.value = this.value.toUpperCase();
    this.setSelectionRange(p, p);
  });

  function showResult(type, msg) {
    var colors  = {success:'rgba(34,197,94,0.08)',  error:'rgba(239,68,68,0.08)',  info:'rgba(59,130,246,0.08)'};
    var borders = {success:'rgba(34,197,94,0.3)',   error:'rgba(239,68,68,0.3)',   info:'rgba(59,130,246,0.3)'};
    var texts   = {success:'#86efac', error:'#fca5a5', info:'#93c5fd'};
    res.style.cssText = 'display:block;padding:14px 18px;border-radius:8px;font-size:13px;line-height:1.6;margin-bottom:20px;'
      + 'background:' + (colors[type]||colors.info) + ';'
      + 'border:1px solid ' + (borders[type]||borders.info) + ';'
      + 'color:' + (texts[type]||texts.info);
    res.innerHTML = msg;
  }

  btn.addEventListener('click', function() {
    var key = inp.value.trim().toUpperCase();
    if (!key) { showResult('error', 'Enter a key first.'); return; }

    var isProLicense = key.startsWith('GTBOGO-') && !key.startsWith('GTBOGO-BUNDLE-');
    var isBundle     = key.startsWith('GTBOGO-BUNDLE-');
    var isPack       = key.startsWith('PACK-');

    if (!isProLicense && !isBundle && !isPack) {
      showResult('error', 'Invalid key format. Check your purchase email for a GTBOGO-, PACK-, or GTBOGO-BUNDLE- key.');
      return;
    }

    btn.disabled = true;
    btn.textContent = 'Activating...';

    var action = isProLicense ? 'gtbogo_verify_license'
               : isBundle     ? 'gtbogo_activate_bundle_key'
               :                'gtbogo_activate_pack_key';

    var fd = new FormData();
    fd.append('action', action);
    fd.append('nonce', isProLicense
      ? '<?php echo esc_js(wp_create_nonce("gtbogo_license_nonce")); ?>'
      : '<?php echo esc_js(wp_create_nonce("gtbogo_activate_pack_key")); ?>');
    if (isProLicense) {
      fd.append('license_key', key);
      fd.append('site', '<?php echo esc_js(home_url()); ?>');
    } else {
      fd.append('pack_key', key);
    }

    fetch(ajaxurl, {method:'POST', body:fd})
      .then(function(r){return r.json();})
      .then(function(d) {
        btn.disabled = false;
        btn.textContent = '🔑 Activate Key';
        if (d.success) {
          var msg = (d.data && d.data.message) ? d.data.message : 'Key activated successfully.';
          showResult('success', '&#10003; ' + msg
            + (isProLicense ? ' <a href="" style="color:#86efac;font-weight:700" onclick="location.reload();return false;">Refresh to see PRO features →</a>' : ''));
          inp.value = '';
        } else {
          var emsg = (d.data && d.data.message) ? d.data.message : 'Activation failed. Check your key and try again.';
          showResult('error', '&#10007; ' + emsg);
        }
      })
      .catch(function() {
        btn.disabled = false;
        btn.textContent = '🔑 Activate Key';
        showResult('error', 'Connection error. Please try again.');
      });
  });

  inp.addEventListener('keydown', function(e) { if (e.key === 'Enter') btn.click(); });
})();
</script>
</div>

<!-- Purchase Box -->
<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:16px">
  <div class="gt-bundle-card gt-animate-in">
    <div class="gt-bundle-price">$149<span style="font-size:16px">/yr</span></div>
    <div style="font-size:13px;color:var(--gt-soft);margin-bottom:16px">per year · 200 PRO Packs available</div>
    <div class="gt-bundle-name">GT BOGO Engine PRO</div>
    <div class="gt-bundle-packs">Annual license · 1 site</div>
    <ul class="gt-bundle-features">
      <li>Unlimited BOGO rules</li>
      <li>PRO Pack importing</li>
      <li>Advanced analytics</li>
      <li>Priority support</li>
      <li>All 25 Superpowers</li>
    </ul>
    <div id="paypal-pro-btn"></div>
  </div>
  <div class="gt-card" style="grid-column:span 2;display:flex;flex-direction:column;justify-content:center;align-items:center;text-align:center;padding:36px">
    <div style="font-size:48px;margin-bottom:16px">🚀</div>
    <h3 style="font-size:20px;font-weight:800;color:var(--gt-white);margin:0 0 10px">Ready to scale your revenue?</h3>
    <p class="gt-text-sm gt-soft" style="max-width:400px;margin:0 0 20px">Join store owners using GT BOGO Engine to increase average order value by up to 40% with zero coupon codes.</p>
    <a href="https://graphictshirts.shop/bogo/" target="_blank" class="gt-btn gt-btn-ghost">Learn More →</a>
  </div>
</div>

<?php // phpcs:disable WordPress.WP.EnqueuedResources.NonEnqueuedScript ?>
<script src="https://www.paypal.com/sdk/js?client-id=BAAkNVcbBPDEWkSF9jV-WG8Ml8OvVn811izpWVLGAmx0RyY-gnfPO9Lw7x-hgy8zeQ9qZFv_Xn9ZpgysPU&components=hosted-buttons&disable-funding=venmo&currency=USD"></script>
<script>
if (window.paypal && paypal.HostedButtons) {
  paypal.HostedButtons({ hostedButtonId: '5KWJ8DPK67RDE' }).render('#paypal-pro-btn');
}
</script>
<?php endif; ?>

<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
