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

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

// Handle settings update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'update_settings') {
    $user['qr_center_image'] = isset($_POST['qr_center_image']) ? 1 : 0;
    $user['webhook_url'] = trim($_POST['webhook_url'] ?? '');
    saveUser($user);
    header('Location: api_keys.php?updated=1');
    exit;
}

$adminSettings = getAdminSettings();
$isExpired = strtotime($user['plan_expires_at']) <= time();
if (!is_array($user['api_keys'])) $user['api_keys'] = [];
$canBuyMoreKeys = count($user['api_keys']) < 3;

$pageTitle = 'API Keys';
$activeNav = 'api_keys';
include __DIR__ . '/includes/user_header.php';
?>

<div class="page-head">
  <h1 class="page-title">API keys</h1>
  <p class="page-sub">Your keys authenticate API requests. Any key below works — keep them safe and never share them.</p>
</div>

<?php if ($isExpired): ?>
  <div class="alert alert-warn">
    <strong>Your plan has expired.</strong> Your API keys will not work until you renew. <a href="plans.php" style="font-weight:600; text-decoration:underline;">Renew now →</a>
  </div>
<?php endif; ?>

<!-- QR & Webhook Settings -->
<div class="card">
  <div style="display:flex;align-items:center;gap:12px;margin-bottom:20px;">
    <div style="width:40px;height:40px;border-radius:12px;background:var(--soft);display:flex;align-items:center;justify-content:center;">
      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--primary)" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="7" height="7"/><rect x="14" y="3" width="7" height="7"/><rect x="3" y="14" width="7" height="7"/><path d="M14 14h3v3h-3zM20 14h-1M14 20h-1M20 20h-1"/></svg>
    </div>
    <div>
      <h2 class="card-title" style="margin-bottom:0;">QR Code & Webhook Settings</h2>
      <div class="card-sub" style="margin-bottom:0;">Customize QR appearance and payment notifications</div>
    </div>
  </div>
  
  <form method="POST" action="api_keys.php" id="settingsForm">
    <input type="hidden" name="action" value="update_settings">
    
    <div style="display:grid;grid-template-columns:1fr 1fr;gap:20px;">
      <!-- QR Center Image Toggle -->
      <div style="padding:16px;background:var(--surface-soft);border:1px solid var(--hairline);border-radius:12px;">
        <div style="display:flex;align-items:center;gap:12px;">
          <label class="switch">
            <input type="checkbox" name="qr_center_image" value="1" <?= $user['qr_center_image'] ? 'checked' : '' ?>>
            <span class="switch-track"><span class="switch-thumb"></span></span>
          </label>
          <div>
            <div style="font-weight:600;font-size:14px;color:var(--ink);">Logo in QR Center</div>
            <div style="font-size:12px;color:var(--muted);">Show your avatar in generated QR codes</div>
          </div>
        </div>
      </div>
      
      <!-- Webhook URL -->
      <div style="padding:16px;background:var(--surface-soft);border:1px solid var(--hairline);border-radius:12px;">
        <label style="font-weight:600;font-size:14px;color:var(--ink);display:block;margin-bottom:8px;">Webhook URL</label>
        <input class="input" type="url" name="webhook_url" placeholder="https://your-server.com/webhook" value="<?= htmlspecialchars($user['webhook_url']) ?>" style="margin:0;">
        <div style="font-size:11px;color:var(--muted);margin-top:6px;">We'll send POST requests for payment events</div>
      </div>
    </div>
    
    <button type="submit" class="btn btn-primary" style="margin-top:16px;">Save Settings</button>
  </form>
</div>

<!-- API Keys Section -->
<div class="card">
  <div class="justify-between flex flex-wrap items-center" style="gap:14px;">
    <div>
      <h2 class="card-title">Your keys (<?= count($user['api_keys']) ?>/3)</h2>
      <div class="card-sub" style="margin-bottom:0;">Plan: <?= htmlspecialchars($user['plan_label']) ?></div>
    </div>
    <div class="badge badge-gray">
      <span class="mono" id="resetChancesDisplay"><?= (int)$user['reset_chances'] ?></span>&nbsp;/ 10 reset chances
    </div>
  </div>
</div>

<div class="card">
  <?php foreach ($user['api_keys'] as $idx => $keyData): ?>
    <div class="key-row">
      <span class="key-text" id="apiKeyText<?= $idx ?>"><?= htmlspecialchars($keyData['key']) ?></span>
      <button class="btn btn-secondary btn-sm" onclick="copyText('apiKeyText<?= $idx ?>', this)">Copy</button>
      <button class="btn btn-outline btn-sm" onclick="regenerateKey(<?= $idx ?>)">Generate new</button>
    </div>
    <div class="key-label">Label: <?= htmlspecialchars($keyData['label']) ?></div>
  <?php endforeach; ?>

  <?php if ($canBuyMoreKeys): ?>
    <div class="divider"></div>
    <p style="font-size:14px; color:var(--body); margin-bottom:14px;">Need a custom-named key like <span class="mono">YourName_fampay1234</span>? Buy one for a one-time fee.</p>
    <button class="btn btn-primary" onclick="openCustomApiNameModal()">Buy custom API key — ₹<?= (int)$adminSettings['custom_api_price'] ?></button>
  <?php else: ?>
    <div class="divider"></div>
    <p style="font-size:14px; color:var(--body);">You've reached the maximum of 3 API keys.</p>
  <?php endif; ?>
</div>

<div class="card" style="background:var(--surface-soft); border-style:dashed;">
  <h2 class="card-title">How it works</h2>
  <p style="font-size:14px; color:var(--body); line-height:1.7;">
    Pass your key as <code class="mono">api_key</code> in the request. See the <a href="docs.php" style="font-weight:600;">documentation</a> for request &amp; response examples.<br>
    Regenerating a key invalidates the old one immediately and costs 1 of your 10 reset chances.
  </p>
</div>

<!-- Step 1: Ask for custom API key name -->
<div class="modal-overlay" id="customNameModal">
  <div class="modal">
    <div class="modal-title">Buy custom API key</div>
    <div class="modal-sub">Enter a name — your key will look like <span class="mono">YourName_fampay1234</span></div>
    <input class="input" type="text" id="customNameInput" placeholder="e.g. Aditya268" maxlength="30">
    <div id="customNameError" style="color:var(--down); font-size:12.5px; margin-top:10px; min-height:16px; text-align:left;"></div>
    <button class="btn btn-primary btn-block" style="margin-top:6px;" onclick="submitCustomApiName()">Continue — ₹<?= (int)$adminSettings['custom_api_price'] ?></button>
    <span class="modal-close" onclick="closeCustomNameModal()">Cancel</span>
  </div>
</div>

<!-- Step 2: QR for custom API purchase -->
<div class="modal-overlay" id="customApiModal">
  <div class="modal">
    <div class="modal-title">Custom API key</div>
    <div class="modal-price">₹<?= (int)$adminSettings['custom_api_price'] ?></div>
    <div class="qr-frame"><img id="customApiQrImage" src="" alt="QR Code"></div>
    <div class="qr-hint">Scan with any UPI app</div>
    <div class="modal-status" id="customApiModalStatus">Generating QR…</div>
    <span class="modal-close" onclick="closeCustomApiModal()">Cancel</span>
  </div>
</div>

<!-- Reset-unlock QR modal -->
<div class="modal-overlay" id="resetUnlockModal">
  <div class="modal">
    <div class="modal-title">Unlock 10 more resets</div>
    <div class="modal-price">₹<?= (int)$adminSettings['reset_unlock_price'] ?></div>
    <div class="qr-frame"><img id="resetUnlockQrImage" src="" alt="QR Code"></div>
    <div class="qr-hint">Scan with any UPI app</div>
    <div class="modal-status" id="resetUnlockModalStatus">Generating QR…</div>
    <span class="modal-close" onclick="closeResetUnlockModal()">Cancel</span>
  </div>
</div>

<script>
    function copyText(elId, btn) {
        const text = document.getElementById(elId).innerText;
        navigator.clipboard.writeText(text).then(() => {
            const old = btn.innerText;
            btn.innerText = 'Copied';
            setTimeout(() => btn.innerText = old, 1500);
        });
    }

    // Generate new (reset) a specific key — shared 10-chance pool
    function regenerateKey(keyIndex) {
        if (!confirm('Generate a new key? The old one will stop working immediately.')) return;

        encryptedFetch('api/regenerate_key.php', { key_index: keyIndex })
            .then(data => {
                if (data.status === 'success') {
                    document.getElementById('apiKeyText' + keyIndex).innerText = data.data.new_key;
                    document.getElementById('resetChancesDisplay').innerText = data.data.reset_chances;
                    alert('New key generated! Reset chances left: ' + data.data.reset_chances);
                } else if (data.status === 'limit_reached') {
                    if (confirm('No reset chances left. Unlock 10 more for ₹<?= (int)$adminSettings['reset_unlock_price'] ?>?')) {
                        openResetUnlockModal();
                    }
                } else {
                    alert(data.message || 'Something went wrong.');
                }
            })
            .catch(() => alert('Connection error. Please try again.'));
    }

    // ============ Custom API purchase ============
    function openCustomApiNameModal() {
        document.getElementById('customNameInput').value = '';
        document.getElementById('customNameError').innerText = '';
        document.getElementById('customNameModal').classList.add('active');
    }
    function closeCustomNameModal() {
        document.getElementById('customNameModal').classList.remove('active');
    }

    function submitCustomApiName() {
        const name = document.getElementById('customNameInput').value.trim();
        if (!/^[A-Za-z0-9_]{2,30}$/.test(name)) {
            document.getElementById('customNameError').innerText = 'Use only letters, numbers, underscores (2-30 chars).';
            return;
        }
        closeCustomNameModal();
        openCustomApiModal(name);
    }

    let customApiPollInterval = null;

    function openCustomApiModal(customName) {
        document.getElementById('customApiModalStatus').innerText = 'Generating QR…';
        document.getElementById('customApiModalStatus').classList.remove('success');
        document.getElementById('customApiModal').classList.add('active');

        encryptedFetch('api/create_custom_api_order.php', { custom_name: customName })
            .then(data => {
                if (data.status === 'success') {
                    document.getElementById('customApiQrImage').src = data.data.qr_url;
                    document.getElementById('customApiModalStatus').innerText = 'Waiting for payment…';
                    pollCustomApiOrder(data.data.order_id);
                } else {
                    document.getElementById('customApiModalStatus').innerText = '⚠ ' + (data.message || 'Could not generate QR');
                }
            })
            .catch(() => {
                document.getElementById('customApiModalStatus').innerText = 'Connection error';
            });
    }

    function pollCustomApiOrder(orderId) {
        if (customApiPollInterval) clearInterval(customApiPollInterval);
        customApiPollInterval = setInterval(() => {
            encryptedFetch('api/check_custom_api_order.php', { order_id: orderId })
                .then(data => {
                    if (data.status === 'success') {
                        clearInterval(customApiPollInterval);
                        window.location.href = 'payment_success.php?type=custom_api&order_id=' + encodeURIComponent(orderId);
                    } else if (data.status === 'error') {
                        document.getElementById('customApiModalStatus').innerText = '⚠ ' + data.message;
                    }
                })
                .catch(() => {});
        }, 1200);
    }

    function closeCustomApiModal() {
        document.getElementById('customApiModal').classList.remove('active');
        if (customApiPollInterval) clearInterval(customApiPollInterval);
    }

    // ============ Reset-unlock ============
    let resetUnlockPollInterval = null;

    function openResetUnlockModal() {
        document.getElementById('resetUnlockModalStatus').innerText = 'Generating QR…';
        document.getElementById('resetUnlockModalStatus').classList.remove('success');
        document.getElementById('resetUnlockModal').classList.add('active');

        encryptedFetch('api/create_reset_unlock_order.php', {})
            .then(data => {
                if (data.status === 'success') {
                    document.getElementById('resetUnlockQrImage').src = data.data.qr_url;
                    document.getElementById('resetUnlockModalStatus').innerText = 'Waiting for payment…';
                    pollResetUnlockOrder(data.data.order_id);
                } else {
                    document.getElementById('resetUnlockModalStatus').innerText = '⚠ ' + (data.message || 'Could not generate QR');
                }
            })
            .catch(() => {
                document.getElementById('resetUnlockModalStatus').innerText = 'Connection error';
            });
    }

    function pollResetUnlockOrder(orderId) {
        if (resetUnlockPollInterval) clearInterval(resetUnlockPollInterval);
        resetUnlockPollInterval = setInterval(() => {
            encryptedFetch('api/check_reset_unlock_order.php', { order_id: orderId })
                .then(data => {
                    if (data.status === 'success') {
                        clearInterval(resetUnlockPollInterval);
                        window.location.href = 'payment_success.php?type=reset_unlock&order_id=' + encodeURIComponent(orderId);
                    } else if (data.status === 'error') {
                        document.getElementById('resetUnlockModalStatus').innerText = '⚠ ' + data.message;
                    }
                })
                .catch(() => {});
        }, 1200);
    }

    function closeResetUnlockModal() {
        document.getElementById('resetUnlockModal').classList.remove('active');
        if (resetUnlockPollInterval) clearInterval(resetUnlockPollInterval);
    }
</script>

<?php include __DIR__ . '/includes/user_footer.php'; ?>
