<?php
/**
 * GT BOGO Engine — Integrations
 * @package GT_BOGO_Engine
 * @since   3.10.1
 */
if (!defined('ABSPATH')) exit;
if (!current_user_can('manage_options')) return;

$is_pro = function_exists('gt_bogo_has_pro') ? gt_bogo_has_pro() : false;
$message = ''; $message_type = '';

if ($is_pro && isset($_POST['gtbogo_save_integrations']) && check_admin_referer('gtbogo_integrations', 'gtbogo_int_nonce')) {
    $int = [
        'mailchimp_key'        => sanitize_text_field(wp_unslash($_POST['mailchimp_key']        ?? '')),
        'klaviyo_key'          => sanitize_text_field(wp_unslash($_POST['klaviyo_key']          ?? '')),
        'mailchimp_tag_bogo'   => sanitize_text_field(wp_unslash($_POST['mailchimp_tag_bogo']   ?? 'bogo-customer')),
        'klaviyo_event'        => sanitize_text_field(wp_unslash($_POST['klaviyo_event']        ?? 'BOGO Redeemed')),
        'webhook_url'          => esc_url_raw(wp_unslash($_POST['webhook_url']          ?? '')),
        'webhook_on_redeem'    => isset($_POST['webhook_on_redeem']),
        'webhook_on_activate'  => isset($_POST['webhook_on_activate']),
    ];
    update_option('gtbogo_integrations', $int);
    $message = 'Integration settings saved.'; $message_type = 'success';
}

$int = get_option('gtbogo_integrations', []);

// Detect installed plugins
$has_wc          = class_exists('WooCommerce');
$has_mailchimp   = defined('MAILCHIMP_FOR_WP_VERSION') || class_exists('MailChimp_WooCommerce');
$has_klaviyo     = defined('KLAVIYO_FOR_WC') || class_exists('WC_Klaviyo');
$has_memberships = class_exists('WC_Memberships');
$has_subscriptions = class_exists('WC_Subscriptions');
$has_yith_points = class_exists('YITH_WC_Points_Rewards');

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
    <div>
        <h1 class="gt-page-title">🔌 Integrations</h1>
        <p class="gt-page-subtitle">Connect GT BOGO Engine with your marketing and membership tools</p>
    </div>
</div>

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

<?php if (!$is_pro): ?>
<div class="gt-pro-gate gt-animate-in">
    <span class="gt-pro-gate-icon">🔌</span>
    <h2>PRO License Required</h2>
    <p>Integrations connect GT BOGO Engine with Mailchimp, Klaviyo, WooCommerce Memberships, and webhooks.</p>
    <div class="gt-flex" style="justify-content:center;gap:12px;flex-wrap:wrap">
        <a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">Purchase PRO — $19.99/yr</a>
        <a href="<?php echo esc_url(admin_url('admin.php?page=gt-bogo-engine&tab=license')); ?>" class="gt-btn gt-btn-ghost">Activate License</a>
    </div>
</div>
<?php else: ?>

<!-- Plugin Status -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">Detected Plugins</h2>
        <span class="gt-text-soft gt-text-sm">GT BOGO Engine auto-detects compatible plugins</span>
    </div>
    <div style="display:grid;grid-template-columns:repeat(3,1fr);gap:12px">
        <?php foreach([
            ['WooCommerce',             $has_wc,            'Required for all BOGO functionality',           'woocommerce'],
            ['Mailchimp for WooCommerce',$has_mailchimp,     'Tag BOGO customers in Mailchimp automatically', 'mailchimp'],
            ['Klaviyo',                 $has_klaviyo,       'Fire Klaviyo events on BOGO redemptions',        'klaviyo'],
            ['WC Memberships',          $has_memberships,   'Restrict rules to membership plan holders',     'wc-memberships'],
            ['WC Subscriptions',        $has_subscriptions, 'Apply rules to subscription products',          'wc-subscriptions'],
            ['YITH Points & Rewards',   $has_yith_points,   'Stack BOGO with loyalty points programs',       'yith'],
        ] as $plugin): ?>
        <div style="background:<?php echo $plugin[1] ? 'rgba(34,197,94,0.05)' : 'rgba(255,255,255,0.02)'; ?>;border:1px solid <?php echo $plugin[1] ? 'rgba(34,197,94,0.15)' : 'rgba(255,255,255,0.06)'; ?>;border-radius:10px;padding:14px">
            <div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:6px">
                <span style="font-size:13px;font-weight:700;color:var(--gt-white)"><?php echo esc_html($plugin[0]); ?></span>
                <span style="font-size:11px;font-weight:700;color:<?php echo $plugin[1] ? '#86efac' : '#94a3b8'; ?>"><?php echo $plugin[1] ? '✓ Active' : '○ Not Found'; ?></span>
            </div>
            <div style="font-size:11px;color:var(--gt-soft);line-height:1.4"><?php echo esc_html($plugin[2]); ?></div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<form method="post" action="">
    <?php wp_nonce_field('gtbogo_integrations', 'gtbogo_int_nonce'); ?>

    <!-- Mailchimp -->
    <div class="gt-card gt-animate-in" style="margin-bottom:20px">
        <div class="gt-card-header">
            <h2 class="gt-card-title">🐵 Mailchimp</h2>
            <span class="gt-badge <?php echo !empty($int['mailchimp_key']) ? 'gt-badge-active' : 'gt-badge-free'; ?>"><?php echo !empty($int['mailchimp_key']) ? 'Connected' : 'Not Connected'; ?></span>
            <?php if ( !empty($int['mailchimp_key']) ): ?>
            <button type="button" class="gt-btn gt-btn-ghost gt-btn-sm" onclick="gtBogoTestIntegration('mailchimp',this)">Test Connection</button>
            <?php endif; ?>
        </div>
        <div class="gt-feature-grid gt-feature-grid--2col">
            <div class="gt-form-group" style="margin:0">
                <label class="gt-form-label">Mailchimp API Key</label>
                <input type="password" name="mailchimp_key" class="gt-input"
                       value="<?php echo esc_attr($int['mailchimp_key'] ?? ''); ?>"
                       placeholder="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx-us1">
                <div class="gt-form-hint">Found in Mailchimp → Account → Extras → API keys</div>
            </div>
            <div class="gt-form-group" style="margin:0">
                <label class="gt-form-label">Tag Applied on BOGO Redemption</label>
                <input type="text" name="mailchimp_tag_bogo" class="gt-input"
                       value="<?php echo esc_attr($int['mailchimp_tag_bogo'] ?? 'bogo-customer'); ?>"
                       placeholder="bogo-customer">
                <div class="gt-form-hint">Customers who redeem a BOGO rule get this tag in Mailchimp</div>
            </div>
        </div>
    </div>

    <!-- Klaviyo -->
    <div class="gt-card gt-animate-in" style="margin-bottom:20px">
        <div class="gt-card-header">
            <h2 class="gt-card-title">📧 Klaviyo</h2>
            <span class="gt-badge <?php echo !empty($int['klaviyo_key']) ? 'gt-badge-active' : 'gt-badge-free'; ?>"><?php echo !empty($int['klaviyo_key']) ? 'Connected' : 'Not Connected'; ?></span>
            <?php if ( !empty($int['klaviyo_key']) ): ?>
            <button type="button" class="gt-btn gt-btn-ghost gt-btn-sm" onclick="gtBogoTestIntegration('klaviyo',this)">Test Connection</button>
            <?php endif; ?>
        </div>
        <div class="gt-feature-grid gt-feature-grid--2col">
            <div class="gt-form-group" style="margin:0">
                <label class="gt-form-label">Klaviyo Private API Key</label>
                <input type="password" name="klaviyo_key" class="gt-input"
                       value="<?php echo esc_attr($int['klaviyo_key'] ?? ''); ?>"
                       placeholder="pk_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx">
                <div class="gt-form-hint">Found in Klaviyo → Settings → API Keys</div>
            </div>
            <div class="gt-form-group" style="margin:0">
                <label class="gt-form-label">Event Name on BOGO Redemption</label>
                <input type="text" name="klaviyo_event" class="gt-input"
                       value="<?php echo esc_attr($int['klaviyo_event'] ?? 'BOGO Redeemed'); ?>"
                       placeholder="BOGO Redeemed">
                <div class="gt-form-hint">Klaviyo metric fired when a customer redeems a BOGO rule</div>
            </div>
        </div>
    </div>

    <!-- Webhooks -->
    <div class="gt-card gt-animate-in" style="margin-bottom:20px">
        <div class="gt-card-header">
            <h2 class="gt-card-title">🔗 Webhook</h2>
            <span class="gt-badge <?php echo !empty($int['webhook_url']) ? 'gt-badge-active' : 'gt-badge-free'; ?>"><?php echo !empty($int['webhook_url']) ? 'Active' : 'Not Set'; ?></span>
            <?php if ( !empty($int['webhook_url']) ): ?>
            <button type="button" class="gt-btn gt-btn-ghost gt-btn-sm" onclick="gtBogoTestIntegration('webhook',this)">Send Test</button>
            <?php endif; ?>
        </div>
        <div class="gt-form-group" style="margin-bottom:16px">
            <label class="gt-form-label">Webhook URL</label>
            <input type="url" name="webhook_url" class="gt-input"
                   value="<?php echo esc_attr($int['webhook_url'] ?? ''); ?>"
                   placeholder="https://hooks.zapier.com/hooks/catch/...">
            <div class="gt-form-hint">POST request sent to this URL on the selected events. Compatible with Zapier, Make, n8n.</div>
        </div>
        <div style="display:flex;gap:20px;flex-wrap:wrap">
            <label style="display:flex;align-items:center;gap:8px;cursor:pointer">
                <input type="checkbox" name="webhook_on_redeem" value="1" <?php checked(!empty($int['webhook_on_redeem'])); ?> style="accent-color:var(--gt-red)">
                <span style="font-size:13px;color:var(--gt-white)">Fire on BOGO redemption</span>
            </label>
            <label style="display:flex;align-items:center;gap:8px;cursor:pointer">
                <input type="checkbox" name="webhook_on_activate" value="1" <?php checked(!empty($int['webhook_on_activate'])); ?> style="accent-color:var(--gt-red)">
                <span style="font-size:13px;color:var(--gt-white)">Fire on rule activation/deactivation</span>
            </label>
        </div>
    </div>

    <div class="gt-card gt-animate-in">
        <div style="display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:16px">
            <div class="gt-text-soft gt-text-sm">Integration credentials are stored securely in your WordPress database.</div>
            <button type="submit" name="gtbogo_save_integrations" class="gt-btn gt-btn-primary" style="padding:12px 32px">💾 Save Integrations</button>
        </div>
    </div>
</form>
<?php endif; ?>

<div class="gt-card gt-animate-in" style="margin-bottom:20px;background:linear-gradient(135deg,rgba(59,130,246,0.06),rgba(7,12,28,0));border-color:rgba(59,130,246,0.15)">
    <div class="gt-card-header"><h2 class="gt-card-title">💡 Integration ROI Guide</h2><span class="gt-text-soft gt-text-sm">How to turn BOGO data into retention revenue</span></div>
    <div class="gt-feature-grid gt-feature-grid--2col" style="gap:12px">
        <div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;padding:16px">
            <div style="font-size:15px;font-weight:700;color:var(--gt-white);margin-bottom:8px">📧 Mailchimp BOGO Sequence</div>
            <p style="font-size:13px;color:var(--gt-soft);line-height:1.6;margin:0">Tag BOGO redeemers then build a 3-email sequence: thank them 24 hours after purchase, cross-sell a related product at full price 7 days later, offer a time-limited repeat deal at 30 days. This sequence typically recovers 15 to 25% of deal customers at full margin.</p>
        </div>
        <div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;padding:16px">
            <div style="font-size:15px;font-weight:700;color:var(--gt-white);margin-bottom:8px">⚡ Klaviyo Flow Trigger</div>
            <p style="font-size:13px;color:var(--gt-soft);line-height:1.6;margin:0">The BOGO Redeemed event unlocks Klaviyo predictive analytics. Use it to identify which redeemers are high-LTV vs one-time bargain hunters. High-LTV redeemers graduate to your loyalty tier. Bargain hunters receive increasingly smaller deals to test price sensitivity.</p>
        </div>
        <div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;padding:16px">
            <div style="font-size:15px;font-weight:700;color:var(--gt-white);margin-bottom:8px">🔗 Webhook to Zapier</div>
            <p style="font-size:13px;color:var(--gt-soft);line-height:1.6;margin:0">Connect the redemption webhook to a Zapier automation that logs every deal to a Google Sheet, sends a Slack notification to your team, and adds the customer to a CRM segment — giving you real-time deal velocity data without opening WordPress.</p>
        </div>
        <div style="background:rgba(255,255,255,0.02);border:1px solid var(--gt-border);border-radius:10px;padding:16px">
            <div style="font-size:15px;font-weight:700;color:var(--gt-white);margin-bottom:8px">🧩 Memberships and BOGO</div>
            <p style="font-size:13px;color:var(--gt-soft);line-height:1.6;margin:0">If WC Memberships is active, restrict your best BOGO deals to membership holders only. Silver members get Buy 1 Get 1 on all tees every month is a compelling acquisition hook that also prevents public deal dilution.</p>
        </div>
    </div>
</div>

<div id="gt-integration-test-result" style="display:none;margin-bottom:16px"></div>
<script>
function gtBogoTestIntegration(type, btn) {
    var result = document.getElementById('gt-integration-test-result');
    btn.disabled = true;
    var orig = btn.textContent;
    btn.textContent = 'Testing\u2026';
    result.style.display = 'none';

    var fd = new FormData();
    fd.append('action', 'gtbogo_test_integration');
    fd.append('nonce',  '<?php echo esc_js( wp_create_nonce("gtbogo_test_integration") ); ?>');
    fd.append('type',   type);

    fetch(ajaxurl, { method: 'POST', body: fd })
        .then(function(r){ return r.json(); })
        .then(function(d){
            result.style.display = 'block';
            if (d.success) {
                result.innerHTML = '<div class="gt-notice gt-notice-success">\u2713 ' + d.data.message + '</div>';
            } else {
                result.innerHTML = '<div class="gt-notice gt-notice-error">\u2717 ' + (d.data ? d.data.message : 'Test failed.') + '</div>';
            }
        })
        .catch(function(){ result.innerHTML = '<div class="gt-notice gt-notice-error">Request failed.</div>'; result.style.display='block'; })
        .finally(function(){ btn.disabled = false; btn.textContent = orig; });
}
</script>
<?php require_once __DIR__ . '/../ui-system/wrapper-end.php'; ?>
