<?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 : (defined('KINDAMBA_PUBLIC_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']  ?? (defined('KINDAMBA_PUBLIC_KEY') ? 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']  ?? (defined('KINDAMBA_PUBLIC_KEY') ? 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" data-theme="dark">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Kindamba Pay Sandbox (Legacy)</title>
    <?php include 'includes/head.php'; ?>
    <style>
        .sandbox-card { border-radius: 16px; border: 1px solid #eef0f7; box-shadow: 0 4px 12px rgba(0,0,0,0.03); margin-bottom: 24px; transition: all 0.3s ease; }
        .sandbox-card:hover { box-shadow: 0 8px 24px rgba(0,0,0,0.06); }
        .result-box { background: #1e1e2e; color: #a6accd; padding: 20px; border-radius: 12px; font-family: 'Fira Code', monospace; font-size: 13px; max-height: 400px; overflow-y: auto; position: relative;}
        .result-box pre { margin: 0; color: inherit; }
        .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); }
        .badge-method { font-size: 10px; padding: 4px 8px; border-radius: 6px; font-weight: 700; margin-right: 8px; vertical-align: middle; }
        .badge-post { background: #e3f2fd; color: #0d47a1; }
        .badge-get { background: #e8f5e9; color: #1b5e20; }
        .form-label { font-weight: 600; color: #475569; margin-bottom: 6px; }
        .input-group-text { background-color: #f8fafc; border-color: #e2e8f0; }
        .form-control:focus { box-shadow: 0 0 0 4px rgba(59, 130, 246, 0.1); border-color: #3b82f6; }
        .status-pill { width: 12px; height: 12px; border-radius: 50%; display: inline-block; margin-right: 6px; }
    </style>
</head>
<body>
    <?php include 'includes/sidebar.php'; ?>
    <main class="dashboard-main">
        <?php include 'includes/header.php'; ?>
        
        <div class="dashboard-main-body">
            <div class="d-flex flex-wrap align-items-center justify-content-between gap-3 mb-24">
                <h6 class="fw-semibold mb-0">Kindamba Pay API Sandbox (Legacy)</h6>
                <ul class="d-flex align-items-center gap-2">
                    <li class="fw-medium">
                        <a href="dashboard.php" class="d-flex align-items-center gap-1 hover-text-primary">
                            <iconify-icon icon="solar:home-smile-angle-outline" class="icon text-lg"></iconify-icon>
                            Dashboard
                        </a>
                    </li>
                    <li>-</li>
                    <li class="fw-medium">Sandbox</li>
                </ul>
            </div>

            <div class="row">
                <!-- Create Transaction Section -->
                <div class="col-lg-6">
                    <div class="card sandbox-card">
                        <div class="card-header bg-white border-bottom py-16 px-24">
                            <h6 class="mb-0"><span class="badge badge-method badge-post">POST</span> Create Transaction</h6>
                            <p class="text-sm text-secondary-light mb-0 mt-1">Simulate an STK push request to a customer's phone.</p>
                        </div>
                        <div class="card-body p-24">
                            <form id="createForm">
                                <div class="row gy-3">
                                    <div class="col-12">
                                        <label class="form-label">API Public Key</label>
                                        <input type="text" class="form-control" name="token" id="createToken" value="<?= htmlspecialchars($initial_token) ?>" placeholder="pk_live_...">
                                    </div>
                                    <div class="col-sm-6">
                                        <label class="form-label">Phone Number</label>
                                        <input type="text" class="form-control" name="number" placeholder="0XXXXXXXXX (10 digits)" value="0695123456">
                                    </div>
                                    <div class="col-sm-6">
                                        <label class="form-label">Amount (TZS)</label>
                                        <input type="number" class="form-control" name="amount" placeholder="1000" value="1000">
                                    </div>
                                    <div class="col-12">
                                        <label class="form-label">Customer Name</label>
                                        <input type="text" class="form-control" name="name" placeholder="John Doe" value="Sandbox Tester">
                                    </div>
                                    <div class="col-12 mt-24">
                                        <button type="submit" class="btn btn-primary w-100 py-12 radius-8 d-flex align-items-center justify-content-center gap-2">
                                            <iconify-icon icon="lucide:send" class="text-lg"></iconify-icon>
                                            Initiate Transaction
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- Status Check Section -->
                <div class="col-lg-6">
                    <div class="card sandbox-card">
                        <div class="card-header bg-white border-bottom py-16 px-24">
                            <h6 class="mb-0"><span class="badge badge-method badge-get">GET</span> Check Status</h6>
                            <p class="text-sm text-secondary-light mb-0 mt-1">Verify the real-time status of a specific transaction ID.</p>
                        </div>
                        <div class="card-body p-24">
                            <form id="statusForm">
                                <div class="row gy-3">
                                    <div class="col-12">
                                        <label class="form-label">API Public Key</label>
                                        <input type="text" class="form-control" name="token" id="statusToken" value="<?= htmlspecialchars($initial_token) ?>" placeholder="pk_live_...">
                                    </div>
                                    <div class="col-12">
                                        <label class="form-label">Transaction ID</label>
                                        <div class="input-group">
                                            <input type="text" class="form-control" name="tranid" placeholder="pay_xxxxxxxxxxxx" id="statusTranId">
                                            <button class="btn btn-outline-secondary" type="button" onclick="pasteTranId()">
                                                <iconify-icon icon="lucide:clipboard-paste"></iconify-icon>
                                            </button>
                                        </div>
                                    </div>
                                    <div class="col-12 mt-24">
                                        <button type="submit" class="btn btn-info w-100 py-12 radius-8 text-white d-flex align-items-center justify-content-center gap-2">
                                            <iconify-icon icon="lucide:refresh-cw" class="text-lg"></iconify-icon>
                                            Check Transaction Status
                                        </button>
                                    </div>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>

                <!-- Results Section -->
                <div class="col-12">
                    <div class="card sandbox-card">
                        <div class="card-header bg-white border-bottom py-16 px-24 d-flex justify-content-between align-items-center">
                            <h6 class="mb-0">API Response Dashboard</h6>
                            <div id="loadingIndicator" style="display:none;">
                                <div class="spinner-border spinner-border-sm text-primary" role="status"></div>
                                <span class="ms-2 text-sm text-primary">Processing...</span>
                            </div>
                        </div>
                        <div class="card-body p-24">
                            <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="mt-16 d-flex align-items-center gap-3" id="quickActions" style="display:none !important;">
                                <span class="text-sm fw-semibold">Quick Actions:</span>
                                <button class="btn btn-sm btn-outline-primary radius-8" onclick="sendToStatus()">
                                    <iconify-icon icon="lucide:arrow-right" class="me-1"></iconify-icon> Use ID in Status Check
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php include 'includes/footer.php'; ?>
    </main>

    <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 = 'block';
            quickActions.style.display = 'none';

            try {
                const response = await fetch(`sonicpesa_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 (Kindamba format)
                if (result.data && result.data.transaction_id) {
                    lastTranId = result.data.transaction_id;
                    quickActions.style.setProperty('display', 'flex', 'important');
                } else if (result.data && result.data.data && result.data.data.transaction_id) {
                    lastTranId = result.data.data.transaction_id;
                    quickActions.style.setProperty('display', 'flex', 'important');
                } else if (result.data && result.data.tranID) {
                    lastTranId = result.data.tranID;
                    quickActions.style.setProperty('display', 'flex', 'important');
                } else if (result.transaction_id) {
                    lastTranId = result.transaction_id;
                    quickActions.style.setProperty('display', 'flex', 'important');
                }

            } 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 = '#fff3cd';
                setTimeout(() => input.style.backgroundColor = '', 1000);
            }
        }

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

        function pasteTranId() {
            navigator.clipboard.readText().then(text => {
                if (text && text.trim()) {
                    document.getElementById('statusTranId').value = text.trim();
                } else {
                    alert('Clipboard is empty');
                }
            });
        }
    </script>
</body>
</html>


