<?php
require_once 'config.php';
require_once 'includes/db.php';
require_once 'includes/functions.php';
require_once 'includes/kindamba.php';

require_login();

$user_id = $_SESSION['user_id'];
$success = '';
$error = '';

// Fetch the user's actual API Key from the database
try {
    $stmt = $pdo->prepare("SELECT api_key FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $db_api_key = $stmt->fetchColumn() ?: '';
} catch (PDOException $e) {
    $db_api_key = '';
}

// Global fallback if no DB key exists
$initial_token = !empty($db_api_key) ? $db_api_key : KINDAMBA_PUBLIC_KEY;

// Handle AJAX Requests
if (isset($_GET['ajax'])) {
    header('Content-Type: application/json');
    if (!is_logged_in()) {
        echo json_encode(['code' => 401, 'data' => ['success' => false, 'message' => 'Session expired. Please refresh and log in again.']]);
        exit;
    }
    
    $action = $_GET['ajax'];
    $input = json_decode(file_get_contents('php://input'), true);

    if ($action === 'create') {
        $token  = $input['token']  ?? KINDAMBA_PUBLIC_KEY;
        $number = $input['number'] ?? '';
        $amount = (int)($input['amount'] ?? 0);
        $name   = $input['name']   ?? 'Sandbox Test';

        $res = kindamba_initiate_payment($number, $amount, $name, 'guest@kindamba.site', 'SANDBOX-' . time(), SITE_URL . '/webhook.php', $token);
        echo json_encode($res);
        exit;
    }

    if ($action === 'status') {
        $token  = $input['token']  ?? KINDAMBA_PUBLIC_KEY;
        $tranId = $input['tranid'] ?? '';

        $res = kindamba_verify_status($tranId, $token);
        echo json_encode($res);
        exit;
    }
    
    echo json_encode(['code' => 400, 'data' => ['success' => false, 'message' => 'Invalid action']]);
    exit;
}

require_login();

?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Kindamba Pay Sandbox</title>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link href="https://fonts.googleapis.com/css2?family=IBM+Plex+Mono:wght@400;500;600&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">
<style>
/* ─── Design tokens ─────────────────────────────────── */
:root {
    --bg:         #0d0f12;
    --surface:    #141720;
    --surface2:   #1c2030;
    --border:     #262c3d;
    --accent:     #00e5a0;
    --accent2:    #0096ff;
    --text:       #e8eaf0;
    --muted:      #6b7394;
    --danger:     #ff4d6d;
    --warn:       #ffaa00;
    --purple:     #b48eff;
    --mono:       'IBM Plex Mono', monospace;
    --sans:       'IBM Plex Sans', sans-serif;
    --radius:     8px;
    --radius-lg:  14px;
}

*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

body {
    font-family: var(--sans);
    background: var(--bg);
    color: var(--text);
    min-height: 100vh;
    padding: 28px 20px 60px;
    line-height: 1.6;
}

/* Subtle grid background */
body::before {
    content: '';
    position: fixed; inset: 0;
    background-image:
        linear-gradient(rgba(0,229,160,.025) 1px, transparent 1px),
        linear-gradient(90deg, rgba(0,229,160,.025) 1px, transparent 1px);
    background-size: 40px 40px;
    pointer-events: none;
    z-index: 0;
}

.wrapper {
    max-width: 1040px;
    margin: 0 auto;
    position: relative;
    z-index: 1;
}

/* ─── Header ─────────────────────────────────────────── */
.header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 32px;
    padding-bottom: 20px;
    border-bottom: 1px solid var(--border);
}
.header-brand {
    display: flex; align-items: center; gap: 14px;
}
.logo-mark {
    width: 40px; height: 40px;
    background: linear-gradient(135deg, var(--accent), var(--accent2));
    border-radius: 10px;
    display: grid; place-items: center;
    font-family: var(--mono);
    font-weight: 600;
    font-size: 1rem;
    color: #000;
    flex-shrink: 0;
}
.brand-name {
    font-size: 1.25rem;
    font-weight: 600;
    letter-spacing: -.02em;
    color: var(--text);
    text-decoration: none;
}
.brand-sub {
    font-size: .75rem;
    color: var(--muted);
    font-family: var(--mono);
}
.header-right {
    display: flex;
    align-items: center;
    gap: 15px;
}
.header-pill {
    background: rgba(0,229,160,.1);
    border: 1px solid rgba(0,229,160,.25);
    color: var(--accent);
    font-size: .7rem;
    font-family: var(--mono);
    padding: 4px 10px;
    border-radius: 20px;
    letter-spacing: .06em;
}

/* ─── Cards ──────────────────────────────────────────── */
.card {
    background: var(--surface);
    border: 1px solid var(--border);
    border-radius: var(--radius-lg);
    padding: 24px;
    margin-bottom: 20px;
}
.card-title {
    font-size: .7rem;
    font-family: var(--mono);
    color: var(--muted);
    letter-spacing: .1em;
    text-transform: uppercase;
    margin-bottom: 18px;
    display: flex;
    align-items: center;
    gap: 8px;
}
.card-title::before {
    content: '';
    width: 3px; height: 14px;
    background: var(--accent);
    border-radius: 2px;
}

/* ─── Two-column layout ──────────────────────────────── */
.cols { display: grid; grid-template-columns: 1fr 1fr; gap: 20px; }
@media (max-width: 680px) { .cols { grid-template-columns: 1fr; } }

/* ─── Form elements ──────────────────────────────────── */
.form-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
@media (max-width: 540px) { .form-grid { grid-template-columns: 1fr; } }

.field { display: flex; flex-direction: column; gap: 5px; }
.field-full { grid-column: 1 / -1; }
label {
    font-size: .72rem;
    font-family: var(--mono);
    color: var(--muted);
    letter-spacing: .05em;
    text-transform: uppercase;
}
input[type=text], input[type=email], input[type=tel], input[type=number] {
    background: var(--bg);
    border: 1px solid var(--border);
    color: var(--text);
    font-family: var(--mono);
    font-size: .875rem;
    padding: 9px 12px;
    border-radius: var(--radius);
    transition: border-color .15s;
    width: 100%;
}
input:focus { outline: none; border-color: var(--accent); }
input::placeholder { color: var(--muted); }

/* ─── Buttons ────────────────────────────────────────── */
.btn-row { display: flex; gap: 10px; margin-top: 18px; flex-wrap: wrap; }
.btn {
    font-family: var(--mono);
    font-size: .8rem;
    font-weight: 500;
    letter-spacing: .04em;
    padding: 10px 20px;
    border: none;
    border-radius: var(--radius);
    cursor: pointer;
    transition: opacity .15s, transform .1s;
    white-space: nowrap;
    text-decoration: none;
    display: inline-flex;
    align-items: center;
    justify-content: center;
}
.btn:hover { opacity: .85; transform: translateY(-1px); }
.btn:active { transform: translateY(0); }
.btn-primary {
    background: var(--accent);
    color: #000;
}
.btn-secondary {
    background: rgba(0,150,255,.15);
    border: 1px solid rgba(0,150,255,.35);
    color: var(--accent2);
}
.btn-ghost {
    background: var(--surface2);
    border: 1px solid var(--border);
    color: var(--muted);
}
.btn-sm { padding: 5px 12px; font-size: .72rem; }

/* ─── Alerts ─────────────────────────────────────────── */
.alert {
    border-radius: var(--radius);
    padding: 14px 16px;
    font-size: .875rem;
    margin-bottom: 18px;
    border-left: 3px solid;
    display: none;
}
.alert-success { background: rgba(0,229,160,.07); border-color: var(--accent); }
.alert-error   { background: rgba(255,77,109,.07); border-color: var(--danger); color: #ff8099; }
.alert strong  { font-weight: 600; }

/* ─── Code/pre ───────────────────────────────────────── */
pre, code {
    font-family: var(--mono);
}
pre {
    background: var(--bg);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 14px;
    font-size: .78rem;
    overflow-x: auto;
    color: #a8b2d8;
    margin-top: 14px;
    max-height: 360px;
    overflow-y: auto;
}
code {
    background: rgba(255,255,255,.07);
    padding: 2px 6px;
    border-radius: 4px;
    font-size: .82em;
    color: var(--accent);
}

/* ─── Result Box ─────────────────────────────────────── */
.result-box { position: relative; }
.copy-btn { 
    position: absolute; top: 10px; right: 10px; 
    background: rgba(255,255,255,0.1); border: none; color: #fff; 
    padding: 4px 8px; border-radius: 4px; font-size: 11px; cursor: pointer; transition: 0.2s;
}
.copy-btn:hover { background: rgba(255,255,255,0.2); }
.quick-actions { margin-top: 15px; display: none; align-items: center; gap: 10px; }

/* ─── Badges ─────────────────────────────────────────── */
.badge {
    display: inline-block;
    font-family: var(--mono);
    font-size: .68rem;
    font-weight: 600;
    letter-spacing: .07em;
    padding: 3px 9px;
    border-radius: 20px;
    text-transform: uppercase;
}
.badge-method { font-size: 10px; padding: 4px 8px; border-radius: 6px; margin-right: 8px; vertical-align: middle; border: none !important;}
.badge-post { background: #e3f2fd; color: #0d47a1; }
.badge-get { background: #e8f5e9; color: #1b5e20; }
.badge-success   { background: rgba(0,229,160,.12); color: var(--accent); border: 1px solid rgba(0,229,160,.3); }
.badge-pending   { background: rgba(255,170,0,.1);  color: var(--warn);   border: 1px solid rgba(255,170,0,.3); }
.badge-progress  { background: rgba(0,150,255,.1);  color: var(--accent2);border: 1px solid rgba(0,150,255,.3); }
.badge-cancelled { background: rgba(180,142,255,.1);color: var(--purple); border: 1px solid rgba(180,142,255,.3);}
.badge-rejected  { background: rgba(255,77,109,.1); color: var(--danger); border: 1px solid rgba(255,77,109,.3); }

/* ─── Reference section ──────────────────────────────── */
.ref-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 10px;
    margin-top: 4px;
}
.ref-item {
    background: var(--bg);
    border: 1px solid var(--border);
    border-radius: var(--radius);
    padding: 10px 12px;
    display: flex;
    flex-direction: column;
    gap: 4px;
}
.ref-item small { font-size: .75rem; color: var(--muted); }

/* ─── Spinner ────────────────────────────────────────── */
.spin {
    display: none;
    width: 16px; height: 16px;
    border: 2px solid var(--border);
    border-top-color: var(--accent);
    border-radius: 50%;
    animation: rotate .6s linear infinite;
    flex-shrink: 0;
}
@keyframes rotate { to { transform: rotate(360deg); } }
.loader-container { display: flex; align-items: center; gap: 8px; font-size: 0.8rem; color: var(--accent); }

/* ─── Input Group ────────────────────────────────────── */
.input-group { display: flex; }
.input-group input { border-top-right-radius: 0; border-bottom-right-radius: 0; flex: 1; }
.input-group .btn { border-top-left-radius: 0; border-bottom-left-radius: 0; border: 1px solid var(--border); border-left: none; }

</style>
</head>
<body>
<div class="wrapper">

<!-- ─── Header ────────────────────────────────────────── -->
<header class="header">
    <div class="header-brand">
        <div class="logo-mark">KP</div>
        <div>
            <a href="dashboard.php" class="brand-name">Kindamba Pay Sandbox</a>
            <div class="brand-sub">api.kindamba.site / v1.0</div>
        </div>
    </div>
    <div class="header-right">
        <a href="dashboard.php" class="btn btn-ghost btn-sm">← Back to Dashboard</a>
        <div class="header-pill">SANDBOX MODE</div>
    </div>
</header>

<!-- ─── Two-column: Create + Check ──────────────────────── -->
<div class="cols">

    <!-- Create Order -->
    <div class="card">
        <div class="card-title"><span class="badge badge-method badge-post">POST</span> Create Payment Order</div>
        <form id="createForm">
            <div class="form-grid">
                <div class="field field-full">
                    <label>API Public Key</label>
                    <input type="text" name="token" id="createToken" value="<?= htmlspecialchars($initial_token) ?>" placeholder="pk_live_..." required>
                </div>
                <div class="field">
                    <label>Buyer Name</label>
                    <input type="text" name="name" value="Sandbox Tester" required>
                </div>
                <div class="field">
                    <label>Phone (0XXXXXXXXX)</label>
                    <input type="tel" name="number" value="0695123456" required>
                </div>
                <div class="field field-full">
                    <label>Amount (TZS)</label>
                    <input type="number" name="amount" value="1000" min="1" required>
                </div>
            </div>
            <div class="btn-row">
                <button type="submit" class="btn btn-primary">
                    ⚡ Initiate Transaction
                </button>
            </div>
        </form>
    </div>

    <!-- Check Status -->
    <div class="card">
        <div class="card-title"><span class="badge badge-method badge-get">GET</span> Check Order Status</div>
        <p style="font-size:.83rem;color:var(--muted);margin-bottom:16px;">
            Verify the real-time status of a specific transaction ID.
        </p>
        <form id="statusForm" style="display:flex;flex-direction:column;gap:14px;">
            <div class="field">
                <label>API Public Key</label>
                <input type="text" name="token" id="statusToken" value="<?= htmlspecialchars($initial_token) ?>" placeholder="pk_live_..." required>
            </div>
            <div class="field">
                <label>Transaction ID</label>
                <div class="input-group">
                    <input type="text" name="tranid" id="statusTranId" placeholder="pay_xxxxxxxxxxxx" required>
                    <button class="btn btn-ghost" type="button" onclick="pasteTranId()" title="Paste from clipboard">
                        📋
                    </button>
                </div>
            </div>
            <div class="btn-row">
                <button type="submit" class="btn btn-secondary">
                    🔍 Check Status
                </button>
            </div>
        </form>
    </div>

</div><!-- /cols -->

<!-- ─── API Result ──────────────────────────────────────── -->
<div class="card">
    <div class="card-title" style="justify-content:space-between; display:flex;">
        <span>API Response Dashboard</span>
        <div id="loadingIndicator" style="display:none;" class="loader-container">
            <div class="spin" style="display:block;"></div> Processing...
        </div>
    </div>
    
    <div class="result-box" id="resultContainer">
        <button class="copy-btn" onclick="copyResult()">Copy JSON</button>
        <pre id="jsonOutput">Waiting for request...</pre>
    </div>
    
    <div class="quick-actions" id="quickActions">
        <span class="text-sm" style="font-size:0.8rem;color:var(--muted)">Quick Actions:</span>
        <button class="btn btn-ghost btn-sm" onclick="sendToStatus()">
            → Use ID in Status Check
        </button>
    </div>
</div>

<!-- ─── Reference ────────────────────────────────────────── -->
<div class="cols">
    <div class="card">
        <div class="card-title">Payment Status Reference</div>
        <div class="ref-grid">
            <div class="ref-item">
                <span class="badge badge-success">SUCCESS</span>
                <small>Payment confirmed ✅</small>
            </div>
            <div class="ref-item">
                <span class="badge badge-pending">PENDING</span>
                <small>Awaiting USSD approval</small>
            </div>
            <div class="ref-item">
                <span class="badge badge-progress">INPROGRESS</span>
                <small>Processing in progress</small>
            </div>
            <div class="ref-item">
                <span class="badge badge-cancelled">CANCELLED</span>
                <small>Cancelled by system</small>
            </div>
            <div class="ref-item">
                <span class="badge badge-cancelled">USERCANCELLED</span>
                <small>Customer declined USSD</small>
            </div>
            <div class="ref-item">
                <span class="badge badge-rejected">REJECTED</span>
                <small>Insufficient funds / wrong PIN</small>
            </div>
        </div>
    </div>

    <div class="card">
        <div class="card-title">Setup Checklist</div>
        <ul style="list-style:none;display:flex;flex-direction:column;gap:9px;font-size:.85rem;color:var(--text);">
            <li>☐ Use your <strong>API Public Key</strong> (starts with <code>pk_live_</code>)</li>
            <li>☐ Phone numbers can be standard local format (e.g., <code>0695...</code> or <code>255...</code>)</li>
            <li>☐ Set webhook URL in Kindamba Dashboard to receive final status</li>
            <li>☐ Transaction results include a <code>transaction_id</code> which is used for Status checks.</li>
        </ul>
    </div>
</div>

</div><!-- /wrapper -->

<script>
    let lastTranId = '';

    // Load persisted token on startup
    document.addEventListener('DOMContentLoaded', () => {
        const savedToken = localStorage.getItem('kindamba_api_key');
        if (savedToken) {
            document.getElementById('createToken').value = savedToken;
            document.getElementById('statusToken').value = savedToken;
        }
    });

    async function handleRequest(action, data) {
        // Persist the token used for this request
        if (data.token) {
            localStorage.setItem('kindamba_api_key', data.token);
            // Sync the other token input
            document.getElementById('createToken').value = data.token;
            document.getElementById('statusToken').value = data.token;
        }

        const output = document.getElementById('jsonOutput');
        const loader = document.getElementById('loadingIndicator');
        const quickActions = document.getElementById('quickActions');
        
        output.innerText = 'Sending request...';
        loader.style.display = 'flex';
        quickActions.style.display = 'none';

        try {
            const response = await fetch(`kindamba_sandbox.php?ajax=${action}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(data)
            });
            
            const result = await response.json();
            output.innerText = JSON.stringify(result, null, 4);
            
            // If we got a transaction ID, store it (handles nested Kindamba response)
            if (result.data && result.data.transaction_id) {
                lastTranId = result.data.transaction_id;
                quickActions.style.display = 'flex';
            } else if (result.data && result.data.data && result.data.data.transaction_id) {
                lastTranId = result.data.data.transaction_id;
                quickActions.style.display = 'flex';
            } else if (result.transaction_id) {
                lastTranId = result.transaction_id;
                quickActions.style.display = 'flex';
            }

        } catch (error) {
            output.innerText = 'Error: ' + error.message;
        } finally {
            loader.style.display = 'none';
        }
    }

    document.getElementById('createForm').onsubmit = function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        handleRequest('create', Object.fromEntries(formData));
    };

    document.getElementById('statusForm').onsubmit = function(e) {
        e.preventDefault();
        const formData = new FormData(this);
        handleRequest('status', Object.fromEntries(formData));
    };

    function sendToStatus() {
        if (lastTranId) {
            document.getElementById('statusTranId').value = lastTranId;
            window.scrollTo({ top: document.getElementById('statusForm').offsetTop - 100, behavior: 'smooth' });
            // Add highlight effect
            const input = document.getElementById('statusTranId');
            input.style.backgroundColor = 'rgba(0, 229, 160, 0.2)';
            setTimeout(() => input.style.backgroundColor = '', 1000);
        }
    }

    function copyResult() {
        const text = document.getElementById('jsonOutput').innerText;
        navigator.clipboard.writeText(text).then(() => {
            alert('Copied JSON to clipboard!');
        });
    }

    function pasteTranId() {
        navigator.clipboard.readText().then(text => {
            if (text) {
                document.getElementById('statusTranId').value = text.trim();
            }
        }).catch(err => {
            alert('Unable to read clipboard. Please paste manually.');
        });
    }
</script>

</body>
</html>
