<?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';

// Handle activate
if (isset($_POST['gtbogo_activate']) && check_admin_referer('gtbogo_license_nonce', 'gtbogo_nonce')) {
    $key = sanitize_text_field(wp_unslash($_POST['license_key'] ?? ''));
    if (empty($key)) {
        $msg = 'Please enter a license key.'; $msg_type = 'error';
    } else {
        $res = wp_remote_post(defined('GT_BOGO_LICENSE_VERIFY_URL') ? GT_BOGO_LICENSE_VERIFY_URL : 'https://graphictshirts.shop/bogo/api/license-verify.php', [
            'timeout' => 20,
            'body'    => ['license' => $key, 'site' => home_url(), 'action' => 'activate'],
        ]);
        if (is_wp_error($res)) {
            $msg = 'Connection error: ' . $res->get_error_message(); $msg_type = 'error';
        } else {
            $body = json_decode(wp_remote_retrieve_body($res), true);
            if (!empty($body['status']) && in_array($body['status'], ['active','valid'])) {
                update_option('gtbogo_license_key',    $key);
                update_option('gtbogo_license_status', 'active');
                update_option('gtbogo_license_expires', $body['expires'] ?? '');
                update_option('gtbogo_license_data',   $body);
                delete_transient('gtbogo_license_verified');
                $license_key = $key; $license_status = 'active';
                $license_exp = $body['expires'] ?? '';
                $is_pro = true;
                $msg = '🎉 License activated! PRO features are now unlocked.'; $msg_type = 'success';
            } else {
                $msg = $body['message'] ?? 'Activation failed. Please check your key and try again.'; $msg_type = 'error';
            }
        }
    }
}

// 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">Manage your GT BOGO Engine PRO license</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>

<?php if ($msg): ?>
<div class="gt-notice gt-notice-<?php echo esc_attr($msg_type); ?> gt-animate-in"><?php echo esc_html($msg); ?></div>
<?php endif; ?>

<?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 $license_exp ? esc_html(date('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>

<div class="gt-card gt-animate-in">
  <div class="gt-card-header"><h2 class="gt-card-title">Deactivate License</h2></div>
  <p class="gt-text-sm gt-soft" style="margin-bottom:20px">Remove this license from your site. You can reactivate at any time.</p>
  <form method="post">
    <?php wp_nonce_field('gtbogo_license_nonce', 'gtbogo_nonce'); ?>
    <button type="submit" name="gtbogo_deactivate" value="1" class="gt-btn gt-btn-ghost">Deactivate License</button>
  </form>
</div>

<?php else: ?>
<!-- Activation Form -->
<div class="gt-card-premium gt-animate-in">
  <div class="gt-card-header"><h2 class="gt-card-title">Activate PRO License</h2></div>
  <p class="gt-text-sm gt-soft" style="margin-bottom:24px">Enter your GT BOGO Engine PRO license key to unlock all features and PRO Pack importing.</p>
  <form method="post">
    <?php wp_nonce_field('gtbogo_license_nonce', 'gtbogo_nonce'); ?>
    <div class="gt-form-group">
      <label class="gt-form-label">License Key</label>
      <input type="text" name="license_key" class="gt-input gt-mono" style="max-width:480px;font-size:15px;letter-spacing:1px" placeholder="GTBOGO-XXXX-XXXX-XXXX-XXXX" value="<?php echo esc_attr($license_key); ?>" required>
      <p class="gt-form-hint">Your license key was emailed to you after purchase. <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>
    <button type="submit" name="gtbogo_activate" value="1" class="gt-btn gt-btn-primary">🔑 Activate License</button>
  </form>
</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">$19<span style="font-size:16px">.99</span></div>
    <div style="font-size:11px;color:var(--gt-soft);margin-bottom:16px">per year</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 4 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>

<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'; ?>
