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

// In a real app, we'd get this from the Session. 
// For demo, we'll fetch the first merchant from the DB.
$merchant_res = supabase_request('GET', 'merchants?limit=1');
$merchant = !empty($merchant_res['data']) ? $merchant_res['data'][0] : null;

if(!$merchant) {
    die("No merchants found. Please create one from Admin Panel.");
}

$merchant_id = $merchant['id'];

// Fetch Merchant Stats
$tx_res = supabase_request('GET', "transactions?merchant_id=eq.$merchant_id&order=created_at.desc");
$transactions = !empty($tx_res['data']) ? $tx_res['data'] : [];

$total_collected = 0;
$today_volume = 0;
$today = date('Y-m-d');

foreach($transactions as $tx) {
    if($tx['status'] === 'completed') {
        $total_collected += (float)$tx['amount'];
        if(strpos($tx['created_at'], $today) !== false) {
            $today_volume += (float)$tx['amount'];
        }
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Merchant Dashboard - <?php echo $merchant['business_name']; ?></title>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="../assets/dashboard.css">
</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="#transactions" class="nav-link">Transactions</a></li>
            <li class="nav-item"><a href="#api-settings" class="nav-link">API Keys</a></li>
            <li class="nav-item"><a href="#settlements" class="nav-link">Settlements</a></li>
            <li class="nav-item"><a href="/index.php" class="nav-link">Test Gateway</a></li>
        </ul>
    </div>

    <!-- Main Content -->
    <div class="main-body">
        <div class="header">
            <div>
                <p style="color: var(--text-muted); font-size: 0.875rem;">Welcome back,</p>
                <h1><?php echo $merchant['business_name']; ?></h1>
            </div>
            <div class="header-actions">
                <span class="status-badge status-success">Merchant ID: <?php echo substr($merchant_id, 0, 8); ?></span>
            </div>
        </div>

        <!-- Stats Grid -->
        <div class="stats-grid">
            <div class="stat-card">
                <div class="stat-label">Wallet Balance</div>
                <div class="stat-value" style="color: var(--primary);">₹<?php echo number_format($merchant['balance'], 2); ?></div>
                <div style="font-size: 0.75rem; color: var(--text-muted); margin-top: 4px;">Ready for settlement</div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Today's Collection</div>
                <div class="stat-value">₹<?php echo number_format($today_volume, 2); ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">Total Volume</div>
                <div class="stat-value">₹<?php echo number_format($total_collected, 2); ?></div>
            </div>
            <div class="stat-card">
                <div class="stat-label">KYC Status</div>
                <div class="stat-value" style="color: var(--success); font-size: 1.25rem;">VERIFIED ✓</div>
            </div>
        </div>

        <!-- Transaction Table -->
        <div class="card" id="transactions">
            <div class="card-header">
                <h3>Recent Payments</h3>
                <button class="btn btn-outline">Export CSV</button>
            </div>
            <div class="table-responsive">
                <table>
                    <thead>
                        <tr>
                            <th>Transaction ID</th>
                            <th>Customer ID</th>
                            <th>Amount</th>
                            <th>Status</th>
                            <th>Date</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($transactions)): ?>
                        <tr><td colspan="5" style="text-align:center; padding: 40px; color: var(--text-muted);">No transactions yet. Start accepting payments!</td></tr>
                        <?php else: ?>
                            <?php foreach($transactions as $tx): ?>
                            <tr>
                                <td><code><?php echo $tx['order_id']; ?></code></td>
                                <td><?php echo $tx['customer_id'] ?? 'Anonymous'; ?></td>
                                <td><b>₹<?php echo number_format($tx['amount'], 2); ?></b></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 Y, H:i', strtotime($tx['created_at'])); ?></td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>

        <!-- API Settings Card -->
        <div class="card" id="api-settings">
            <div class="card-header">
                <h3>Integration Settings</h3>
                <p style="color: var(--text-muted); font-size: 0.8rem;">Use these keys to connect your website</p>
            </div>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 24px; margin-top: 10px;">
                <div style="background: var(--bg-main); padding: 16px; border-radius: 12px;">
                    <label style="font-size: 0.75rem; font-weight: 700; color: var(--text-muted);">API KEY (PUBLIC)</label>
                    <div style="display: flex; gap: 10px; margin-top: 8px;">
                        <input type="text" readonly value="<?php echo $merchant['api_key']; ?>" style="flex:1; background: transparent; border:none; font-family: monospace; font-size: 0.9rem;">
                        <button class="btn btn-outline" style="padding: 4px 10px; font-size: 0.7rem;">Copy</button>
                    </div>
                </div>
                <div style="background: var(--bg-main); padding: 16px; border-radius: 12px;">
                    <label style="font-size: 0.75rem; font-weight: 700; color: var(--text-muted);">CALLBACK URL</label>
                    <div style="display: flex; gap: 10px; margin-top: 8px;">
                        <input type="text" readonly value="<?php echo $merchant['callback_url'] ?? 'Not set'; ?>" style="flex:1; background: transparent; border:none; font-family: monospace; font-size: 0.9rem;">
                        <button class="btn btn-outline" style="padding: 4px 10px; font-size: 0.7rem;">Edit</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

</body>
</html>
