<?php
/**
 * GT BOGO Engine — REST API Manager (Enterprise)
 * @package GT_BOGO_Engine
 * @since   3.11.0
 */
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 = '';

// ── Generate API Key ──────────────────────────────────────────────────────
if ($is_pro && isset($_POST['gtbogo_generate_key']) && check_admin_referer('gtbogo_generate_key')) {
    $label      = sanitize_text_field($_POST['api_key_label'] ?? 'API Key');
    $permission = sanitize_text_field($_POST['api_key_permission'] ?? 'read');
    $expires    = sanitize_text_field($_POST['api_key_expires'] ?? '');
    $new_key    = 'gtbogo_' . bin2hex(random_bytes(24));
    $keys       = get_option('gtbogo_api_keys', []);
    $key_id     = uniqid('k_', true);
    $keys[$key_id] = [
        'label'      => $label,
        'key'        => $new_key,
        'permission' => $permission,
        'expires'    => $expires,
        'created'    => current_time('mysql'),
        'last_used'  => '',
        'calls'      => 0,
        'enabled'    => true,
    ];
    update_option('gtbogo_api_keys', $keys);
    if (function_exists('gt_bogo_log')) gt_bogo_log('API key generated', $label.' ('.$permission.')', 'success');
    update_option('gtbogo_new_api_key_display', $new_key);
    $message = 'API key generated. Copy it now — it will not be shown again in full.'; $message_type = 'success';
}

// ── Revoke API Key ────────────────────────────────────────────────────────
if ($is_pro && isset($_GET['revoke_key']) && check_admin_referer('revoke_key_'.sanitize_text_field($_GET['revoke_key']))) {
    $kid  = sanitize_text_field($_GET['revoke_key']);
    $keys = get_option('gtbogo_api_keys', []);
    if (isset($keys[$kid])) {
        if (function_exists('gt_bogo_log')) gt_bogo_log('API key revoked', $keys[$kid]['label'], 'warn');
        unset($keys[$kid]);
        update_option('gtbogo_api_keys', $keys);
    }
    $message = 'API key revoked.'; $message_type = 'success';
}

// ── Toggle Key ────────────────────────────────────────────────────────────
if ($is_pro && isset($_GET['toggle_key']) && check_admin_referer('toggle_key_'.sanitize_text_field($_GET['toggle_key']))) {
    $kid  = sanitize_text_field($_GET['toggle_key']);
    $keys = get_option('gtbogo_api_keys', []);
    if (isset($keys[$kid])) {
        $keys[$kid]['enabled'] = !$keys[$kid]['enabled'];
        update_option('gtbogo_api_keys', $keys);
        $message = 'Key '.($keys[$kid]['enabled']?'enabled':'disabled').'.'; $message_type = 'success';
    }
}

// ── Save API Settings ─────────────────────────────────────────────────────
if ($is_pro && isset($_POST['gtbogo_save_api_settings']) && check_admin_referer('gtbogo_api_settings')) {
    update_option('gtbogo_api_enabled',       isset($_POST['api_enabled']));
    update_option('gtbogo_api_rate_limit',    intval($_POST['api_rate_limit'] ?? 60));
    update_option('gtbogo_api_log_calls',     isset($_POST['api_log_calls']));
    update_option('gtbogo_api_require_https', isset($_POST['api_require_https']));
    update_option('gtbogo_api_whitelist_ips', sanitize_textarea_field($_POST['api_whitelist_ips'] ?? ''));
    $message = 'API settings saved.'; $message_type = 'success';
}

$api_keys       = get_option('gtbogo_api_keys', []);
$api_enabled    = get_option('gtbogo_api_enabled', true);
$api_rate_limit = get_option('gtbogo_api_rate_limit', 60);
$api_log_calls  = get_option('gtbogo_api_log_calls', true);
$api_https      = get_option('gtbogo_api_require_https', true);
$api_whitelist  = get_option('gtbogo_api_whitelist_ips', '');
$new_key_flash  = get_option('gtbogo_new_api_key_display', '');
if ($new_key_flash) delete_option('gtbogo_new_api_key_display');

$base_url = rest_url('gt-bogo/v1');
$total_calls = array_sum(array_column($api_keys, 'calls'));
$active_keys = count(array_filter($api_keys, fn($k) => !empty($k['enabled'])));

// API endpoints reference
$endpoints = [
    ['GET',   '/rules',           'read',  'List all active BOGO rules with their configuration'],
    ['GET',   '/rules/{id}',      'read',  'Get a single rule by ID with full detail'],
    ['POST',  '/rules',           'write', 'Create a new BOGO rule'],
    ['PUT',   '/rules/{id}',      'write', 'Update an existing rule by ID'],
    ['PATCH', '/rules/{id}/status','write','Toggle a rule active/inactive'],
    ['DELETE','/rules/{id}',      'write', 'Delete a rule permanently'],
    ['GET',   '/analytics',       'read',  'Get analytics summary (orders, revenue, discounts)'],
    ['GET',   '/analytics/daily', 'read',  'Get day-by-day analytics breakdown'],
    ['GET',   '/rules/{id}/stats','read',  'Get per-rule performance stats'],
    ['POST',  '/validate-cart',   'read',  'Validate whether a cart qualifies for a BOGO rule'],
    ['GET',   '/settings',        'read',  'Get current plugin settings'],
    ['PUT',   '/settings',        'write', 'Update plugin settings'],
];

require_once __DIR__ . '/../ui-system/wrapper-start.php';
?>
<div class="gt-page-header gt-animate-in">
    <div>
        <h1 class="gt-page-title">🔌 REST API Manager</h1>
        <p class="gt-page-subtitle">Manage API keys, view endpoints, and integrate GT BOGO Engine with external systems</p>
    </div>
    <div style="display:flex;gap:8px;align-items:center">
        <span class="gt-badge <?php echo $api_enabled?'gt-badge-active':'gt-badge-free'; ?>"><?php echo $api_enabled?'● API Enabled':'○ API Disabled'; ?></span>
        <code style="font-size:11px;color:var(--gt-subtle);background:rgba(255,255,255,0.04);padding:4px 10px;border-radius:6px;border:1px solid var(--gt-border)"><?php echo esc_url($base_url); ?></code>
    </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 ($new_key_flash): ?>
<div class="gt-notice gt-animate-in" style="background:rgba(34,197,94,0.06);border-color:rgba(34,197,94,0.25);margin-bottom:20px">
    <div style="font-size:13px;font-weight:700;color:#86efac;margin-bottom:8px">🔑 Your New API Key — Copy It Now</div>
    <div style="display:flex;gap:10px;align-items:center">
        <code id="new-key-val" style="font-family:'DM Mono',monospace;font-size:13px;background:rgba(0,0,0,0.4);padding:10px 16px;border-radius:8px;border:1px solid rgba(34,197,94,0.2);color:#86efac;word-break:break-all;flex:1"><?php echo esc_html($new_key_flash); ?></code>
        <button onclick="navigator.clipboard.writeText(document.getElementById('new-key-val').textContent);this.textContent='✓ Copied!';setTimeout(()=>this.textContent='📋 Copy',2000)" class="gt-btn gt-btn-ghost gt-btn-sm" style="white-space:nowrap">📋 Copy</button>
    </div>
    <div style="font-size:12px;color:var(--gt-soft);margin-top:8px">⚠ This key will not be shown in full again. Store it securely in your integration environment.</div>
</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>The REST API gives external tools, headless storefronts, and automation platforms read and write access to your BOGO rules and analytics.</p>
    <div style="display:grid;grid-template-columns:repeat(2,1fr);gap:12px;max-width:480px;margin:24px auto 0">
        <?php foreach(['API key management with permissions','Rate limiting and IP whitelisting','12 REST endpoints for rules and analytics','Compatible with Zapier, Make, and custom apps'] as $f): ?>
        <div style="display:flex;align-items:flex-start;gap:8px;text-align:left"><span style="color:#e10000;font-weight:700">—</span><span style="font-size:13px;color:var(--gt-soft)"><?php echo esc_html($f); ?></span></div>
        <?php endforeach; ?>
    </div>
    <div style="margin-top:24px;display:flex;justify-content:center;gap:12px">
        <a href="https://graphictshirts.shop/bogo/" target="_blank" rel="noopener" class="gt-btn gt-btn-primary">Purchase PRO — $19.99/yr</a>
    </div>
</div>
<?php else: ?>

<!-- METRICS -->
<div class="gt-metrics gt-animate-in" style="margin-bottom:20px">
    <div class="gt-metric" style="--gt-metric-c:#22c55e">
        <span class="gt-metric-icon">🔑</span>
        <div class="gt-metric-label">Active Keys</div>
        <div class="gt-metric-value"><?php echo $active_keys; ?></div>
        <div class="gt-metric-trend"><?php echo count($api_keys); ?> total issued</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#3b82f6">
        <span class="gt-metric-icon">📡</span>
        <div class="gt-metric-label">Total API Calls</div>
        <div class="gt-metric-value"><?php echo number_format($total_calls); ?></div>
        <div class="gt-metric-trend">Across all keys</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#8b5cf6">
        <span class="gt-metric-icon">⚡</span>
        <div class="gt-metric-label">Rate Limit</div>
        <div class="gt-metric-value"><?php echo $api_rate_limit; ?></div>
        <div class="gt-metric-trend">Requests per minute</div>
    </div>
    <div class="gt-metric" style="--gt-metric-c:#e10000">
        <span class="gt-metric-icon">🛡️</span>
        <div class="gt-metric-label">HTTPS Required</div>
        <div class="gt-metric-value" style="font-size:16px"><?php echo $api_https?'Yes':'No'; ?></div>
        <div class="gt-metric-trend">Security enforcement</div>
    </div>
</div>

<!-- GENERATE KEY -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">➕ Generate New API Key</h2></div>
    <form method="post" action="">
        <?php wp_nonce_field('gtbogo_generate_key'); ?>
        <div style="display:grid;grid-template-columns:1fr 1fr 1fr auto;gap:16px;align-items:end">
            <div class="gt-form-group" style="margin:0">
                <label class="gt-form-label">Key Label</label>
                <input type="text" name="api_key_label" class="gt-input" placeholder="e.g. Zapier Integration" required>
                <div class="gt-form-hint">Internal label to identify this key</div>
            </div>
            <div class="gt-form-group" style="margin:0">
                <label class="gt-form-label">Permission Level</label>
                <select name="api_key_permission" class="gt-select">
                    <option value="read">Read Only — GET requests</option>
                    <option value="write">Read + Write — all methods</option>
                    <option value="analytics">Analytics Only — stats endpoints</option>
                </select>
            </div>
            <div class="gt-form-group" style="margin:0">
                <label class="gt-form-label">Expiry Date (optional)</label>
                <input type="date" name="api_key_expires" class="gt-input" min="<?php echo date('Y-m-d', strtotime('+1 day')); ?>">
                <div class="gt-form-hint">Leave blank for no expiry</div>
            </div>
            <div>
                <button type="submit" name="gtbogo_generate_key" class="gt-btn gt-btn-primary" style="padding:11px 24px;white-space:nowrap">🔑 Generate Key</button>
            </div>
        </div>
    </form>
</div>

<!-- KEY TABLE -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">🔑 API Keys</h2><span class="gt-text-soft gt-text-sm"><?php echo count($api_keys); ?> key<?php echo count($api_keys)!==1?'s':''; ?> issued</span></div>
    <?php if (!empty($api_keys)): ?>
    <div style="overflow-x:auto">
        <table class="gt-table">
            <thead><tr><th>Label</th><th>Key Preview</th><th>Permission</th><th>Expires</th><th>Created</th><th>Last Used</th><th>Calls</th><th>Status</th><th>Actions</th></tr></thead>
            <tbody>
            <?php foreach ($api_keys as $kid => $k):
                $expired = !empty($k['expires']) && strtotime($k['expires']) < time();
                $perm_colors = ['read'=>'#93c5fd','write'=>'#fca5a5','analytics'=>'#86efac'];
            ?>
            <tr style="opacity:<?php echo (!empty($k['enabled'])&&!$expired)?'1':'0.5'; ?>">
                <td style="font-weight:700;color:var(--gt-white)"><?php echo esc_html($k['label']); ?></td>
                <td style="font-family:'DM Mono',monospace;font-size:11px;color:var(--gt-soft)">
                    <?php echo esc_html(substr($k['key'],0,16)); ?>••••••••
                    <button onclick="navigator.clipboard.writeText('<?php echo esc_js($k['key']); ?>');this.textContent='✓';setTimeout(()=>this.textContent='📋',1500)"
                            style="background:none;border:none;cursor:pointer;font-size:11px;color:var(--gt-subtle);padding:0 4px">📋</button>
                </td>
                <td><span style="font-size:11px;font-weight:700;color:<?php echo $perm_colors[$k['permission']]??'#94a3b8'; ?>"><?php echo esc_html(strtoupper($k['permission'])); ?></span></td>
                <td style="font-size:12px;color:<?php echo $expired?'#fca5a5':'var(--gt-soft)'; ?>"><?php echo $k['expires'] ? esc_html($k['expires']).($expired?' ⚠ Expired':'') : '—'; ?></td>
                <td style="font-size:11px;color:var(--gt-subtle)"><?php echo esc_html(substr($k['created'],0,10)); ?></td>
                <td style="font-size:11px;color:var(--gt-subtle)"><?php echo $k['last_used'] ? esc_html(substr($k['last_used'],0,16)) : 'Never'; ?></td>
                <td style="font-family:'DM Mono',monospace;font-size:12px;color:var(--gt-white)"><?php echo number_format($k['calls']); ?></td>
                <td>
                    <?php if ($expired): ?>
                    <span class="gt-badge gt-badge-warn">Expired</span>
                    <?php elseif (!empty($k['enabled'])): ?>
                    <span class="gt-badge gt-badge-active">Active</span>
                    <?php else: ?>
                    <span class="gt-badge gt-badge-free">Disabled</span>
                    <?php endif; ?>
                </td>
                <td>
                    <div style="display:flex;gap:6px">
                        <a href="<?php echo esc_url(wp_nonce_url(add_query_arg(['toggle_key'=>$kid,'page'=>'gt-bogo-engine','tab'=>'rest-api'], admin_url('admin.php')), 'toggle_key_'.$kid)); ?>"
                           class="gt-btn gt-btn-ghost gt-btn-sm" style="padding:4px 10px"><?php echo !empty($k['enabled'])?'⏸ Disable':'▶ Enable'; ?></a>
                        <a href="<?php echo esc_url(wp_nonce_url(add_query_arg(['revoke_key'=>$kid,'page'=>'gt-bogo-engine','tab'=>'rest-api'], admin_url('admin.php')), 'revoke_key_'.$kid)); ?>"
                           class="gt-btn gt-btn-ghost gt-btn-sm" style="padding:4px 10px;color:#fca5a5"
                           onclick="return confirm('Revoke this key permanently? This cannot be undone.')">✕ Revoke</a>
                    </div>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
    <?php else: ?>
    <div style="text-align:center;padding:40px 24px">
        <div style="font-size:48px;margin-bottom:16px">🔑</div>
        <p class="gt-text-soft">No API keys yet. Generate your first key above.</p>
    </div>
    <?php endif; ?>
</div>

<!-- ENDPOINT REFERENCE -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header">
        <h2 class="gt-card-title">📡 Endpoint Reference</h2>
        <code style="font-size:11px;color:var(--gt-subtle);background:rgba(255,255,255,0.04);padding:4px 10px;border-radius:6px"><?php echo esc_url($base_url); ?></code>
    </div>
    <div style="margin-bottom:12px;font-size:13px;color:var(--gt-soft)">
        Authenticate with header: <code style="background:rgba(255,255,255,0.06);padding:2px 8px;border-radius:4px;font-size:12px">X-GT-BOGO-Key: your_api_key</code>
    </div>
    <div style="overflow-x:auto">
        <table class="gt-table">
            <thead><tr><th>Method</th><th>Endpoint</th><th>Auth</th><th>Description</th><th>Try It</th></tr></thead>
            <tbody>
            <?php
            $method_colors = ['GET'=>'#86efac','POST'=>'#93c5fd','PUT'=>'#fcd34d','PATCH'=>'#f59e0b','DELETE'=>'#fca5a5'];
            foreach ($endpoints as $ep): ?>
            <tr>
                <td><span style="font-size:11px;font-weight:800;color:<?php echo $method_colors[$ep[0]]??'#94a3b8'; ?>;font-family:'DM Mono',monospace"><?php echo esc_html($ep[0]); ?></span></td>
                <td style="font-family:'DM Mono',monospace;font-size:12px;color:var(--gt-white)"><?php echo esc_html($ep[1]); ?></td>
                <td><span style="font-size:10px;color:<?php echo $ep[2]==='write'?'#fca5a5':'#93c5fd'; ?>;font-weight:700"><?php echo strtoupper($ep[2]); ?></span></td>
                <td style="font-size:12px;color:var(--gt-soft)"><?php echo esc_html($ep[3]); ?></td>
                <td>
                    <?php if ($ep[0]==='GET' && !str_contains($ep[1],'{id}')): ?>
                    <a href="<?php echo esc_url($base_url.$ep[1]); ?>" target="_blank" class="gt-btn gt-btn-ghost gt-btn-sm" style="padding:3px 8px;font-size:11px">↗ Open</a>
                    <?php else: ?>
                    <span style="font-size:11px;color:var(--gt-subtle)">—</span>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>

<!-- QUICK TEST -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">🧪 Quick API Test</h2><span class="gt-text-soft gt-text-sm">Test your key against the rules endpoint</span></div>
    <div style="display:grid;grid-template-columns:1fr auto auto;gap:12px;align-items:end">
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">API Key</label>
            <input type="text" id="test-api-key" class="gt-input" placeholder="Paste an API key to test...">
        </div>
        <div class="gt-form-group" style="margin:0">
            <label class="gt-form-label">Endpoint</label>
            <select id="test-endpoint" class="gt-select">
                <option value="rules">GET /rules</option>
                <option value="analytics">GET /analytics</option>
                <option value="settings">GET /settings</option>
            </select>
        </div>
        <button onclick="runApiTest()" class="gt-btn gt-btn-primary" style="padding:11px 20px">▶ Test</button>
    </div>
    <div id="api-test-result" style="display:none;margin-top:16px">
        <div style="font-size:12px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Response</div>
        <pre id="api-test-output" style="background:rgba(0,0,0,0.4);border-radius:8px;padding:14px;font-family:'DM Mono',monospace;font-size:12px;color:#86efac;border:1px solid rgba(255,255,255,0.06);max-height:300px;overflow:auto;white-space:pre-wrap;word-break:break-word"></pre>
    </div>
    <script>
    async function runApiTest() {
        var key = document.getElementById('test-api-key').value.trim();
        var ep  = document.getElementById('test-endpoint').value;
        var out = document.getElementById('api-test-output');
        var res_div = document.getElementById('api-test-result');
        if (!key) { alert('Enter an API key first.'); return; }
        out.textContent = 'Requesting...';
        res_div.style.display = 'block';
        out.style.color = '#fcd34d';
        try {
            var r = await fetch('<?php echo esc_url(rest_url('gt-bogo/v1/')); ?>' + ep, {
                headers: { 'X-GT-BOGO-Key': key, 'Content-Type': 'application/json' }
            });
            var data = await r.json();
            out.style.color = r.ok ? '#86efac' : '#fca5a5';
            out.textContent = 'HTTP ' + r.status + ' ' + r.statusText + '\n\n' + JSON.stringify(data, null, 2);
        } catch(e) {
            out.style.color = '#fca5a5';
            out.textContent = 'Error: ' + e.message;
        }
    }
    </script>
</div>

<!-- API SETTINGS -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">⚙️ API Settings</h2></div>
    <form method="post" action="">
        <?php wp_nonce_field('gtbogo_api_settings'); ?>
        <div class="gt-setting-row">
            <div><div class="gt-setting-label">Enable REST API</div><div class="gt-setting-desc">When disabled, all API endpoints return 403. Existing keys are preserved.</div></div>
            <label class="gt-toggle"><input type="checkbox" name="api_enabled" value="1" <?php checked($api_enabled); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
        </div>
        <div class="gt-setting-row">
            <div><div class="gt-setting-label">Rate Limit (requests per minute)</div><div class="gt-setting-desc">Maximum requests per API key per minute. Requests exceeding this limit receive a 429 response. Recommended: 60.</div></div>
            <input type="number" name="api_rate_limit" class="gt-input" style="width:100px" value="<?php echo esc_attr($api_rate_limit); ?>" min="10" max="600">
        </div>
        <div class="gt-setting-row">
            <div><div class="gt-setting-label">Log All API Calls</div><div class="gt-setting-desc">Write every API request to the Audit Log. Useful for debugging integrations; disable on high-volume production stores.</div></div>
            <label class="gt-toggle"><input type="checkbox" name="api_log_calls" value="1" <?php checked($api_log_calls); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
        </div>
        <div class="gt-setting-row">
            <div><div class="gt-setting-label">Require HTTPS</div><div class="gt-setting-desc">Reject all API requests made over plain HTTP. Strongly recommended for production stores.</div></div>
            <label class="gt-toggle"><input type="checkbox" name="api_require_https" value="1" <?php checked($api_https); ?>><span class="gt-toggle-track"><span class="gt-toggle-thumb"></span></span></label>
        </div>
        <div class="gt-setting-row" style="border:none">
            <div><div class="gt-setting-label">IP Whitelist</div><div class="gt-setting-desc">Only allow API requests from these IP addresses. One per line. Leave blank to allow all IPs.</div></div>
            <textarea name="api_whitelist_ips" class="gt-input" rows="4" style="width:280px;resize:vertical;font-family:'DM Mono',monospace;font-size:12px" placeholder="192.168.1.1&#10;10.0.0.0/8"><?php echo esc_textarea($api_whitelist); ?></textarea>
        </div>
        <div style="margin-top:20px;text-align:right">
            <button type="submit" name="gtbogo_save_api_settings" class="gt-btn gt-btn-primary" style="padding:12px 32px">💾 Save API Settings</button>
        </div>
    </form>
</div>

<!-- INTEGRATION EXAMPLES -->
<div class="gt-card gt-animate-in" style="margin-bottom:20px">
    <div class="gt-card-header"><h2 class="gt-card-title">💡 Integration Examples</h2></div>
    <div style="display:flex;flex-direction:column;gap:14px">
        <?php foreach([
            ['cURL — List Active Rules', "curl -H 'X-GT-BOGO-Key: YOUR_KEY' \\\n  ".$base_url."/rules"],
            ['cURL — Activate a Rule',   "curl -X PATCH \\\n  -H 'X-GT-BOGO-Key: YOUR_KEY' \\\n  -H 'Content-Type: application/json' \\\n  -d '{\"status\":\"active\"}' \\\n  ".$base_url."/rules/7/status"],
            ['JavaScript (fetch)',        "const res = await fetch('".$base_url."/rules', {\n  headers: { 'X-GT-BOGO-Key': 'YOUR_KEY' }\n});\nconst rules = await res.json();"],
            ['PHP (wp_remote_get)',       "\$res = wp_remote_get(\n  '".$base_url."/analytics',\n  ['headers'=>['X-GT-BOGO-Key'=>'YOUR_KEY']]\n);\n\$data = json_decode(wp_remote_retrieve_body(\$res));"],
        ] as $ex): ?>
        <div>
            <div style="font-size:12px;font-weight:700;color:var(--gt-soft);margin-bottom:4px"><?php echo esc_html($ex[0]); ?></div>
            <div style="position:relative">
                <pre style="background:rgba(0,0,0,0.35);border-radius:8px;padding:12px 16px;font-family:'DM Mono',monospace;font-size:12px;color:#86efac;border:1px solid rgba(255,255,255,0.06);margin:0;overflow-x:auto"><?php echo esc_html($ex[1]); ?></pre>
                <button onclick="navigator.clipboard.writeText(this.dataset.code);this.textContent='✓';setTimeout(()=>this.textContent='📋',1500)"
                        data-code="<?php echo esc_attr($ex[1]); ?>"
                        style="position:absolute;top:8px;right:8px;background:rgba(255,255,255,0.06);border:1px solid rgba(255,255,255,0.1);border-radius:5px;padding:3px 8px;font-size:10px;color:var(--gt-soft);cursor:pointer">📋</button>
            </div>
        </div>
        <?php endforeach; ?>
    </div>
</div>

<!-- GUIDANCE -->
<div class="gt-card gt-animate-in" style="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">🧠 API Integration Guide</h2></div>
    <div class="gt-feature-grid gt-feature-grid--2col">
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Separate Keys Per Integration</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Generate a unique API key for each external integration — one for Zapier, one for your mobile app, one for your reporting dashboard. This lets you revoke a single integration without affecting others if a key is compromised.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Read-Only Keys for Analytics Integrations</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">When connecting a BI tool like Looker, Tableau, or Power BI to the analytics endpoints, always use a Read Only key. Write-permission keys should only be issued to integrations that genuinely need to create or modify rules — typically automation tools or headless WooCommerce setups.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Zapier and Make Automation</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Use the REST API with Zapier's Webhooks app or Make's HTTP module to automate rule activation based on external triggers — CRM data, email campaign sends, inventory levels from your warehouse system. Use the PATCH /rules/{id}/status endpoint to toggle rules on and off without touching the WordPress admin.</div></div>
        <div><div style="font-size:13px;font-weight:700;color:var(--gt-white);margin-bottom:6px">Validate Before You Build</div><div style="font-size:13px;color:var(--gt-soft);line-height:1.7">Use the Quick Test panel above to verify your key works and the response format matches your expectation before writing integration code. The validate-cart endpoint is especially useful for headless checkout flows — pass cart contents and get back which rules would apply.</div></div>
    </div>
</div>

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