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

// Demo: Fetch first merchant
$merchant_res = supabase_request('GET', 'merchants?limit=1');
$merchant = !empty($merchant_res['data']) ? $merchant_res['data'][0] : null;
$merchant_id = $merchant['id'];

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

// Handle Withdrawal Request
$error = "";
if(isset($_POST['request_amount'])) {
    $amount = (float)$_POST['request_amount'];
    if($amount > (float)$merchant['balance']) {
        $error = "Insufficient balance!";
    } elseif($amount < 100) {
        $error = "Minimum settlement amount is ₹100.";
    } else {
        // 1. Deduct from balance
        $new_balance = (float)$merchant['balance'] - $amount;
        supabase_request('PATCH', "merchants?id=eq.$merchant_id", ['balance' => $new_balance]);
        
        // 2. Create settlement record
        supabase_request('POST', 'settlements', [
            'merchant_id' => $merchant_id,
            'amount' => $amount,
            'status' => 'pending',
            'reference_id' => 'SETL_' . time()
        ]);
        
        header("Location: settlements.php?success=1");
        exit;
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Payouts & Settlements - <?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="index.php" class="nav-link">Dashboard</a></li>
            <li class="nav-item"><a href="index.php#transactions" class="nav-link">Transactions</a></li>
            <li class="nav-item"><a href="index.php#api-settings" class="nav-link">API Keys</a></li>
            <li class="nav-item"><a href="#" class="nav-link active">Settlements</a></li>
        </ul>
    </div>

    <!-- Main Content -->
    <div class="main-body">
        <div class="header">
            <h1>Settlements</h1>
        </div>

        <div style="display: grid; grid-template-columns: 1fr 350px; gap: 32px;">
            <!-- Left: Table -->
            <div class="card">
                <div class="card-header">
                    <h3>Settlement History</h3>
                </div>
                <table>
                    <thead>
                        <tr>
                            <th>Date</th>
                            <th>Amount</th>
                            <th>Reference</th>
                            <th>Status</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($settlements)): ?>
                            <tr><td colspan="4" style="text-align:center; padding:30px;">No settlements yet.</td></tr>
                        <?php else: ?>
                            <?php foreach($settlements as $s): ?>
                            <tr>
                                <td><?php echo date('d M Y', strtotime($s['created_at'])); ?></td>
                                <td>₹<?php echo number_format($s['amount'], 2); ?></td>
                                <td><code><?php echo $s['reference_id']; ?></code></td>
                                <td>
                                    <span class="status-badge <?php echo ($s['status'] === 'processed') ? 'status-success' : 'status-pending'; ?>">
                                        <?php echo ucfirst($s['status']); ?>
                                    </span>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>

            <!-- Right: Action Card -->
            <div class="card" style="height: fit-content;">
                <h3 style="margin-bottom: 20px;">Request Payout</h3>
                <div style="background: var(--primary-light); padding: 16px; border-radius: 12px; margin-bottom: 24px;">
                    <p style="font-size: 0.75rem; color: var(--primary); font-weight: 700; margin-bottom: 4px;">AVAILABLE BALANCE</p>
                    <p style="font-size: 1.5rem; font-weight: 800; color: var(--primary);">₹<?php echo number_format($merchant['balance'], 2); ?></p>
                </div>

                <form method="POST">
                    <div style="margin-bottom: 20px;">
                        <label style="display:block; margin-bottom:8px; font-weight:600; font-size: 0.875rem;">Enter Amount (₹)</label>
                        <input type="number" name="request_amount" required min="100" max="<?php echo $merchant['balance']; ?>" placeholder="0.00" style="width:100%; padding:12px; border:1px solid #e2e8f0; border-radius:10px; font-size: 1rem; font-weight: 700;">
                    </div>
                    <?php if($error): ?>
                        <p style="color: var(--danger); font-size: 0.8rem; margin-bottom: 15px; font-weight: 600;">⚠️ <?php echo $error; ?></p>
                    <?php endif; ?>
                    <button type="submit" class="btn btn-primary" style="width:100%; padding:14px;">Withdraw Funds</button>
                </form>
                
                <p style="color: var(--text-muted); font-size: 0.75rem; margin-top: 20px; text-align: center;">
                    Processing time: 1-2 Business Days.<br>Funds will be sent to your registered UPI/Bank.
                </p>
            </div>
        </div>
    </div>
</div>

</body>
</html>
