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

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

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

// Handle webhook save
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_webhook') {
    csrfVerify();
    $webhookUrl = trim($_POST['webhook_url'] ?? '');
    if ($webhookUrl) {
        if (!filter_var($webhookUrl, FILTER_VALIDATE_URL)) {
            $message = 'Invalid URL format.';
            $messageType = 'error';
        } else {
            $parsed = parse_url($webhookUrl);
            $host = $parsed['host'] ?? '';
            // Prevent SSRF by blocking private IPs, loopback, etc.
            $ip = gethostbyname($host);
            if ($ip && filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
                $message = 'Invalid webhook destination. Private and loopback IPs are not allowed.';
                $messageType = 'error';
            } else {
                $user['webhook_url'] = $webhookUrl;
                saveUser($user);
                $message = 'Webhook URL saved!';
                $messageType = 'success';
            }
        }
    } else {
        $user['webhook_url'] = '';
        saveUser($user);
        $message = 'Webhook URL cleared!';
        $messageType = 'success';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<?php 
$pageTitle = "Webhooks — 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;">
        Webhooks
      </h1>
      <p style="font-size: 13px; color: var(--color-ink-mute); margin-top: 4px;">Receive real-time HTTP notifications for payment events.</p>
    </div>

    <!-- WEBHOOK SETTINGS CARD -->
    <div class="card dash-anim-up">
        <div class="card-header" style="margin-bottom: 16px;">
            <div class="card-title"><i data-lucide="send" style="width:18px;height:18px;color:#8b5cf6;"></i> Webhook Settings</div>
            <div class="card-sub">When a payment succeeds, FamGateway will send a signed HTTP POST to your server. Use this to fulfill orders automatically — even if the customer closes their browser.</div>
        </div>

        <form method="POST">
            <input type="hidden" name="action" value="save_webhook">
            <input type="hidden" name="csrf_token" value="<?= csrfToken() ?>">
            <div class="form-group">
                <label class="form-label">Webhook Endpoint URL <span style="color:var(--color-ink-mute);font-weight:400;">(optional)</span></label>
                <input type="url" name="webhook_url" class="form-input" value="<?= htmlspecialchars($user['webhook_url'] ?? '') ?>" placeholder="https://yoursite.com/api/fampay-webhook">
                <div style="font-size:12px;color:var(--color-ink-mute);margin-top:6px;">FamGateway will POST a signed JSON payload to this URL on every successful payment.</div>
            </div>
            <div style="display:flex; gap:12px;">
                <button type="submit" class="btn btn-secondary" style="flex:1;"><i data-lucide="save" style="width:14px;height:14px;"></i> Save Webhook URL</button>
                <?php if (!empty($user['webhook_url'])): ?>
                <button type="button" class="btn btn-primary" style="flex:1; background: #8b5cf6; border-color: #7c3aed; color: #fff;" onclick="verifyWebhook(this)"><i data-lucide="check-circle" style="width:14px;height:14px;"></i> Test & Verify</button>
                <?php endif; ?>
            </div>
        </form>

        <div style="margin-top: 16px; text-align: center;">
            <a href="docs.php" class="btn btn-secondary" style="width: 100%; justify-content: center; background: transparent; border: 1px solid var(--color-hairline); color: var(--color-ink-secondary);"><i data-lucide="file-text" style="width:14px;height:14px;"></i> View Webhook Documentation & Examples</a>
        </div>
    </div>

    <!-- WEBHOOK LOGS CARD -->
    <div class="card dash-anim-up" style="animation-delay: 0.2s; margin-top: 24px; padding: 0; overflow: hidden;">
        <div style="padding: 22px 28px; border-bottom: 1px solid var(--color-hairline); display:flex; justify-content:space-between; align-items:center;">
            <div>
                <div class="card-title"><i data-lucide="list" style="width:18px;height:18px;color:var(--color-primary);"></i> Recent Webhook Logs</div>
                <div class="card-sub">History of webhook requests sent to your server.</div>
            </div>
        </div>

        <?php
        $logs = getWebhookLogs($user['id'], 50);
        ?>
        <div class="table-container" style="margin: 0; border-top: none; <?= empty($logs) ? 'display:none;' : '' ?>">
            <table class="table" style="margin:0;">
                <thead>
                    <tr>
                        <th>DATE & TIME</th>
                        <th>ENDPOINT URL</th>
                        <th>STATUS</th>
                        <th>PAYLOAD / RESPONSE</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($logs as $log): 
                        $statusClass = 'status-pending';
                        $statusText = 'Failed/0';
                        if ($log['response_code'] >= 200 && $log['response_code'] < 300) {
                            $statusClass = 'status-success';
                            $statusText = 'HTTP ' . $log['response_code'];
                        } elseif ($log['response_code'] > 0) {
                            $statusClass = 'status-failed';
                            $statusText = 'HTTP ' . $log['response_code'];
                        }
                    ?>
                    <tr>
                        <td class="tnum" style="white-space: nowrap;"><?= date('d M Y, h:i A', strtotime($log['created_at'])) ?></td>
                        <td>
                            <div style="max-width: 200px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 12px; color: var(--color-ink-secondary);" title="<?= htmlspecialchars($log['endpoint_url']) ?>">
                                <?= htmlspecialchars($log['endpoint_url']) ?>
                            </div>
                        </td>
                        <td>
                            <span class="status-badge <?= $statusClass ?>"><?= $statusText ?></span>
                        </td>
                        <td>
                            <button class="btn btn-secondary btn-sm" onclick="showLogDetails(this)" data-payload="<?= htmlspecialchars($log['payload']) ?>" data-response="<?= htmlspecialchars($log['response_body'] ?? 'No response') ?>">View Details</button>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        
        <?php if (empty($logs)): ?>
        <div class="empty-state" style="padding: 60px 20px;">
            <div class="empty-state-icon" style="background:#f1f5f9; color:#94a3b8;"><i data-lucide="inbox" style="width:24px;height:24px;"></i></div>
            <div style="font-weight:600; font-size:16px; margin-bottom:4px; color:var(--color-ink);">No logs yet</div>
            <div style="color:var(--color-ink-mute); font-size:14px; max-width:300px; margin:0 auto;">Webhook delivery attempts will appear here.</div>
        </div>
        <?php endif; ?>
    </div>

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

<!-- Log Details Modal -->
<div id="logModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(15, 23, 42, 0.6); backdrop-filter:blur(4px); z-index:999; align-items:center; justify-content:center; padding:20px;">
    <div style="background:var(--surface-page); width:100%; max-width:600px; border-radius:var(--r-lg); box-shadow:var(--shadow-lg); overflow:hidden; display:flex; flex-direction:column; max-height:90vh;">
        <div style="padding:16px 24px; border-bottom:1px solid var(--color-hairline); display:flex; justify-content:space-between; align-items:center;">
            <h3 style="margin:0; font-size:16px; font-weight:600; color:var(--color-ink);">Webhook Details</h3>
            <button onclick="document.getElementById('logModal').style.display='none'" style="background:transparent; border:none; cursor:pointer; color:var(--color-ink-secondary); padding:4px;"><i data-lucide="x" style="width:20px;height:20px;"></i></button>
        </div>
        <div style="padding:24px; overflow-y:auto; flex:1;">
            <div style="margin-bottom:16px;">
                <div style="font-size:12px; font-weight:600; color:var(--color-ink-mute); margin-bottom:8px; text-transform:uppercase; letter-spacing:0.5px;">Payload (JSON)</div>
                <pre id="logPayload" style="background:var(--color-canvas); padding:16px; border-radius:var(--r-md); border:1px solid var(--color-hairline); font-size:13px; color:var(--color-ink); overflow-x:auto; margin:0; white-space:pre-wrap;"></pre>
            </div>
            <div>
                <div style="font-size:12px; font-weight:600; color:var(--color-ink-mute); margin-bottom:8px; text-transform:uppercase; letter-spacing:0.5px;">Server Response</div>
                <pre id="logResponse" style="background:var(--color-canvas); padding:16px; border-radius:var(--r-md); border:1px solid var(--color-hairline); font-size:13px; color:var(--color-ink); overflow-x:auto; margin:0; white-space:pre-wrap;"></pre>
            </div>
        </div>
        <div style="padding:16px 24px; border-top:1px solid var(--color-hairline); text-align:right; background:var(--color-canvas-soft);">
            <button class="btn btn-secondary" onclick="document.getElementById('logModal').style.display='none'">Close</button>
        </div>
    </div>
</div>

<script>
    function showLogDetails(btn) {
        let payload = btn.getAttribute('data-payload');
        let response = btn.getAttribute('data-response');
        try {
            payload = JSON.stringify(JSON.parse(payload), null, 2);
        } catch(e) {}
        document.getElementById('logPayload').textContent = payload;
        document.getElementById('logResponse').textContent = response || 'No response body.';
        document.getElementById('logModal').style.display = 'flex';
    }

    function verifyWebhook(btn) {
        const oldHtml = btn.innerHTML;
        btn.innerHTML = '<i data-lucide="loader" style="width:14px;height:14px;animation:spin 1s linear infinite;"></i> Testing...';
        btn.disabled = true;

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

        fetch('api/verify-webhook.php', { method: 'POST', body: fd })
            .then(res => res.json())
            .then(data => {
                alert(data.message);
                window.location.reload();
            })
            .catch(() => alert('Connection error. Please try again.'))
            .finally(() => {
                btn.innerHTML = oldHtml;
                btn.disabled = false;
                if(window.lucide) window.lucide.createIcons();
            });
    }
</script>

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