<?php
require_once __DIR__ . '/includes/functions.php';
startSecureSession();
requireLogin();

$user = getUserById($_SESSION['user_id']);
if (!$user) {
    header('Location: logout.php');
    exit;
}

$message = '';
$messageType = '';

$canBuyMoreKeys = count($user['api_keys']) < 100;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php 
$pageTitle = "API Keys — FamGateway";
include 'includes/header.php'; 
?>
</head>
<body>
<?php include 'includes/nav.php'; ?>
    
<main class="main-content">
    <div class="wrap">

    <?php if ($message): ?>
        <div class="callout callout-<?= $messageType === 'success' ? 'success' : 'error' ?>"><?= htmlspecialchars($message) ?></div>
    <?php endif; ?>

    <!-- Page Title -->
    <div class="dash-anim-right" style="margin-bottom: 24px;">
      <h1 style="font-size: 22px; font-weight: 700; color: var(--color-ink); letter-spacing: -0.5px;">
        API Keys
      </h1>
      <p style="font-size: 13px; color: var(--color-ink-mute); margin-top: 4px;">Manage your authentication keys for API requests and integrations.</p>
    </div>

    <!-- API KEY(S) CARD -->
    <div class="card dash-anim-up">
        <div class="card-header" style="margin-bottom: 16px;">
            <div class="card-title"><i data-lucide="key" style="width:18px;height:18px;color:var(--color-primary);"></i> Your API Key<?= count($user['api_keys']) > 1 ? 's' : '' ?></div>
            <div class="card-sub">Any of your active keys below can be used to authenticate with our servers.</div>
        </div>

        <?php if (empty($user['gmail_connected'])): ?>
            <div class="callout callout-error" style="margin-bottom: 16px;">
                <strong>Action Required:</strong> You must <a href="integrations.php" style="color: inherit; text-decoration: underline;">connect your FamPay Gmail App Password</a> before you can view or use your API keys.
            </div>
        <?php endif; ?>

        <?php foreach ($user['api_keys'] as $idx => $keyData): ?>
        <div style="display: flex; gap: 12px; align-items: center; flex-wrap: wrap; margin-bottom: 8px; <?= empty($user['gmail_connected']) ? 'opacity: 0.6; pointer-events: none;' : '' ?>">
            <span class="form-input tnum" id="apiKeyText<?= $idx ?>" style="flex: 1; min-width: 200px; padding: 12px 16px; background: var(--surface-page); color: var(--color-ink); font-weight: 600; word-break: break-all; border-radius: var(--r-md); <?= empty($user['gmail_connected']) ? 'filter: blur(5px); user-select: none;' : '' ?>"><?= empty($user['gmail_connected']) ? 'fam_hidden_key_please_connect_gmail_first' : htmlspecialchars($keyData['key']) ?></span>
            <button class="btn btn-secondary" <?= empty($user['gmail_connected']) ? 'disabled' : '' ?> onclick="copyText('apiKeyText<?= $idx ?>', this)"><i data-lucide="copy" style="width:14px;height:14px;"></i> Copy</button>
            <button class="btn btn-danger" <?= empty($user['gmail_connected']) ? 'disabled' : '' ?> onclick="regenerateKey(<?= $idx ?>)"><i data-lucide="refresh-cw" style="width:14px;height:14px;"></i> Generate New</button>
        </div>
        <div style="font-size:12px; color:var(--color-ink-mute); margin-bottom:20px; margin-left:4px;">Key Label: <strong style="color:var(--color-ink-secondary);"><?= htmlspecialchars($keyData['label']) ?></strong></div>
        <?php endforeach; ?>
    </div>
    <!-- QUICK INTEGRATION CARD -->
    <div class="card dash-anim-up" style="animation-delay: 0.1s; margin-top: 24px;">
        <div class="card-header" style="margin-bottom: 16px;">
            <div class="card-title"><i data-lucide="code" style="width:18px;height:18px;color:var(--color-primary);"></i> Quick Integration</div>
            <div class="card-sub">Use your API key to generate secure checkout links from your backend.</div>
        </div>
        
        <div style="background: #1e293b; border-radius: 8px; padding: 16px; position: relative;">
            <button class="btn btn-secondary" onclick="copySnippet()" style="position: absolute; top: 12px; right: 12px; font-size: 11px; padding: 6px 10px; background: rgba(255,255,255,0.1); color: #fff; border: 1px solid rgba(255,255,255,0.2);"><i data-lucide="copy" style="width:12px;height:12px;"></i></button>
            <pre id="codeSnippet" style="margin: 0; color: #e2e8f0; font-family: monospace; font-size: 13px; overflow-x: auto; white-space: pre;"><code>$curl = curl_init();
curl_setopt_array($curl, [
  CURLOPT_URL => "https://famgateway.in/api/create-order.php",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_POST => true,
  CURLOPT_POSTFIELDS => json_encode([
    "amount" => 500.00,
    "redirect_url" => "https://your-website.com/success"
  ]),
  CURLOPT_HTTPHEADER => [
    "Authorization: Bearer YOUR_API_KEY",
    "Content-Type: application/json"
  ],
]);

$response = curl_exec($curl);
$data = json_decode($response, true);
// Redirect user to: $data['checkout_url']
</code></pre>
        </div>
    </div>

    </div>
</main>
</div>

<script>
    function copyText(elId, btn) {
        const text = document.getElementById(elId).innerText;
        navigator.clipboard.writeText(text).then(() => {
            const old = btn.innerHTML;
            btn.innerHTML = '<i data-lucide="check" style="width:14px;height:14px;vertical-align:text-bottom;margin-right:4px;"></i> Copied!';
            if(window.lucide) window.lucide.createIcons();
            setTimeout(() => { btn.innerHTML = old; if(window.lucide) window.lucide.createIcons(); }, 1500);
        });
    }

    function regenerateKey(keyIndex) {
        if (!confirm('Generate a new key? The old one will stop working immediately.')) return;

        const fd = new FormData();
        fd.append('key_index', keyIndex);
        fd.append('csrf_token', document.querySelector('input[name="csrf_token"]').value);

        fetch('api/regenerate-key.php', { method: 'POST', body: fd })
            .then(res => res.json())
            .then(data => {
                if (data.status === 'success') {
                    document.getElementById('apiKeyText' + keyIndex).innerText = data.data.new_key;
                    alert('New key generated successfully!');
                } else {
                    alert(data.message || 'Something went wrong.');
                }
            })
            .catch(() => alert('Connection error. Please try again.'));
    }

    function copySnippet() {
        const text = document.getElementById('codeSnippet').innerText;
        navigator.clipboard.writeText(text).then(() => {
            alert('Code snippet copied to clipboard!');
        });
    }

</script>

<script src="https://unpkg.com/lucide@latest"></script>
<script>
  if (window.lucide) lucide.createIcons();
</script>
</body>
</html>
