<?php
require_once '../backend/config.php';

// Fetch Global Stats
$merchants_res = supabase_request('GET', 'merchants?select=*');
$merchants = !empty($merchants_res['data']) ? $merchants_res['data'] : [];

$transactions_res = supabase_request('GET', 'transactions?select=amount,status&order=created_at.desc');
$transactions = !empty($transactions_res['data']) ? $transactions_res['data'] : [];

$total_volume = 0;
$successful_count = 0;
foreach($transactions as $tx) {
    if($tx['status'] === 'completed') {
        $total_volume += (float)$tx['amount'];
        $successful_count++;
    }
}

$pending_settlements_res = supabase_request('GET', 'settlements?status=eq.pending');
$pending_settlements = !empty($pending_settlements_res['data']) ? $pending_settlements_res['data'] : [];
$settlement_amount = 0;
foreach($pending_settlements as $s) { $settlement_amount += (float)$s['amount']; }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CodexVertex - Admin Gateway Panel</title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../dashboard/assets/dashboard.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>

<div class="dashboard-wrapper">
    <!-- Sidebar -->
    <div class="sidebar">
        <div class="logo">Codex<span>Vertex</span></div>
        <ul class="nav-menu">
            <li class="nav-item"><a href="#" class="nav-link active">Dashboard</a></li>
            <li class="nav-item"><a href="#merchants" class="nav-link">Merchants</a></li>
            <li class="nav-item"><a href="#transactions" class="nav-link">Global Transactions</a></li>
            <li class="nav-item"><a href="#settlements" class="nav-link">Settlements</a></li>
            <li class="nav-item"><a href="#" class="nav-link">Settings</a></li>
        </ul>
    </div>

    <!-- Main Content -->
    <div class="main-body">
        <div class="header">
            <h1>Admin Overview</h1>
            <div class="header-actions">
                <button class="btn btn-outline">Generate Report</button>
            </div>
        </div>

        <!-- Stats Grid -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-label">Total Volume</div>
                <div class="stat-value">₹<?php echo number_format($total_volume, 2); ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Successful Trans.</div>
                <div class="stat-value"><?php echo $successful_count; ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Active Merchants</div>
                <div class="stat-value"><?php echo count($merchants); ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Pending Settlement</div>
                <div class="stat-value">₹<?php echo number_format($settlement_amount, 2); ?></div>
            </div>
        </div>

        <!-- Merchants Table -->
        <div class="card" id="merchants">
            <div class="card-header">
                <h3>Registered Merchants</h3>
                <button class="btn btn-primary" onclick="$('#addMerchantModal').show()">+ New Merchant</button>
            </div>
            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>Business Name</th>
                            <th>Email</th>
                            <th>API Key</th>
                            <th>Balance</th>
                            <th>Status</th>
                            <th>Action</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach($merchants as $m): ?>
                        <tr>
                            <td><b><?php echo $m['business_name']; ?></b></td>
                            <td><?php echo $m['email']; ?></td>
                            <td><code><?php echo substr($m['api_key'], 0, 8); ?>...</code></td>
                            <td>₹<?php echo number_format($m['balance'], 2); ?></td>
                            <td><span class="status-badge status-success">Active</span></td>
                            <td>
                                <button class="btn btn-outline" style="padding: 5px 10px;">Edit</button>
                            </td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- Recent Transactions -->
        <div class="card" id="transactions">
            <div class="card-header">
                <h3>Global Transactions (Recent)</h3>
                <a href="#" style="font-size: 0.875rem; color: var(--primary);">View All</a>
            </div>
            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>Order ID</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th>Created At</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php
                        $limited_tx = array_slice($transactions, 0, 10);
                        foreach($limited_tx as $tx): ?>
                        <tr>
                            <td><?php echo $tx['order_id'] ?? 'N/A'; ?></td>
                            <td>₹<?php echo number_format($tx['amount'], 2); ?></td>
                            <td>
                                <span class="status-badge <?php echo ($tx['status'] === 'completed') ? 'status-success' : 'status-pending'; ?>">
                                    <?php echo ucfirst($tx['status']); ?>
                                </span>
                            </td>
                            <td><?php echo date('d M, H:i', strtotime($tx['created_at'] ?? 'now')); ?></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- Simple Modal (Hidden by default) -->
<div id="addMerchantModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:1000; justify-content:center; align-items:center;">
    <div style="background:white; padding:32px; border-radius:16px; width:100%; max-width:400px;">
        <h2 style="margin-bottom:24px;">Add New Merchant</h2>
        <form id="merchantForm">
            <div style="margin-bottom:16px;">
                <label style="display:block; margin-bottom:8px; font-weight:600;">Business Name</label>
                <input type="text" name="business_name" required style="width:100%; padding:10px; border:1px solid #e2e8f0; border-radius:8px;">
            </div>
            <div style="margin-bottom:16px;">
                <label style="display:block; margin-bottom:8px; font-weight:600;">Email Address</label>
                <input type="email" name="email" required style="width:100%; padding:10px; border:1px solid #e2e8f0; border-radius:8px;">
            </div>
            <div style="margin-bottom:24px;">
                <label style="display:block; margin-bottom:8px; font-weight:600;">Callback URL</label>
                <input type="url" name="callback_url" placeholder="https://..." style="width:100%; padding:10px; border:1px solid #e2e8f0; border-radius:8px;">
            </div>
            <div style="display:flex; gap:12px;">
                <button type="submit" class="btn btn-primary" style="flex:1;">Create Merchant</button>
                <button type="button" class="btn btn-outline" style="flex:1;" onclick="$('#addMerchantModal').hide()">Cancel</button>
            </div>
        </form>
    </div>
</div>

<script>
$('#merchantForm').on('submit', function(e) {
    e.preventDefault();
    const data = $(this).serialize();
    $.post('../backend/manage_merchant.php', data, function(res) {
        alert("Merchant created successfully!");
        location.reload();
    });
});
</script>

</body>
</html>
