<?php
session_start();
require_once '../config.php';

if (!isset($_SESSION['admin_id'])) {
    header("Location: login.php");
    exit;
}
global $pdo;

$message = '';

// Approve
if (isset($_GET['approve'])) {
    $id = (int)$_GET['approve'];
    $row = $pdo->prepare("SELECT * FROM deposit_requests WHERE id = ? AND status = 'pending'");
    $row->execute([$id]);
    $req = $row->fetch(PDO::FETCH_ASSOC);
    
    if ($req) {
        // FIX 1: Table banane ka kaam Transaction shuru hone se pehle kar diya
        $pdo->exec("CREATE TABLE IF NOT EXISTS spin_credits (user_id INT PRIMARY KEY, credits INT NOT NULL DEFAULT 0)");

        $pdo->beginTransaction();
        try {
            // 1. Request ko 'approved' mark karo
            $pdo->prepare("UPDATE deposit_requests SET status = 'approved' WHERE id = ?")->execute([$id]);
            
            // 🔥 MAIN FIX: Seedha 'users' table mein 'balance' add karo 🔥
            $upd = $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?");
            $upd->execute([$req['amount'], $req['user_id']]);
            
            // Spin credit: 1 spin per recharge for depositor
            $pdo->prepare("INSERT INTO spin_credits (user_id, credits) VALUES (?, 1) ON DUPLICATE KEY UPDATE credits = credits + 1")->execute([$req['user_id']]);
            
            // Referrer spin: if this user was referred and this is their first approved deposit, give referrer 1 spin
            $ref = $pdo->prepare("SELECT referred_by FROM users WHERE id = ?");
            $ref->execute([$req['user_id']]);
            $referredBy = $ref->fetchColumn();
            
            if ($referredBy) {
                $firstDep = $pdo->prepare("SELECT COUNT(*) FROM deposit_requests WHERE user_id = ? AND status = 'approved'");
                $firstDep->execute([$req['user_id']]);
                if ($firstDep->fetchColumn() == 1) {
                    $pdo->prepare("INSERT INTO spin_credits (user_id, credits) VALUES (?, 1) ON DUPLICATE KEY UPDATE credits = credits + 1")->execute([$referredBy]);
                }
            }
            $pdo->commit();
            $message = '<div class="alert alert-success fw-bold"><i class="fas fa-check"></i> Deposit approved & user balance updated successfully.</div>';
        } catch (Exception $e) {
            // FIX 2: Check for active transaction before rollback
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }
            $message = '<div class="alert alert-danger">Error: ' . htmlspecialchars($e->getMessage()) . '</div>';
        }
    }
}

// Reject
if (isset($_GET['reject'])) {
    $id = (int)$_GET['reject'];
    $pdo->prepare("UPDATE deposit_requests SET status = 'rejected' WHERE id = ? AND status = 'pending'")->execute([$id]);
    $message = '<div class="alert alert-warning fw-bold"><i class="fas fa-times"></i> Deposit rejected.</div>';
}

$list = $pdo->query("
    SELECT d.*, u.username, u.mobile
    FROM deposit_requests d
    LEFT JOIN users u ON u.id = d.user_id
    ORDER BY d.id DESC
    LIMIT 100
")->fetchAll(PDO::FETCH_ASSOC);

$pageTitle = 'Deposit Requests';
require_once 'includes/header.php';
?>
<?= $message ?>
<div class="custom-card">
    <div class="custom-card-header"><i class="fas fa-inbox me-2"></i> User Deposit Requests</div>
    <div class="table-responsive">
        <table class="table table-hover mb-0">
            <thead class="table-light">
                <tr>
                    <th>ID</th>
                    <th>User</th>
                    <th>Amount</th>
                    <th>UTR / Ref</th>
                    <th>Date</th>
                    <th>Status</th>
                    <th class="text-end">Action</th>
                </tr>
            </thead>
            <tbody>
                <?php if (empty($list)): ?>
                    <tr><td colspan="7" class="text-center py-4 text-muted">No deposit requests.</td></tr>
                <?php else: foreach ($list as $r): ?>
                    <tr>
                        <td>#<?= $r['id'] ?></td>
                        <td><?= htmlspecialchars($r['username'] ?? '-') ?><br><small class="text-muted"><?= htmlspecialchars($r['mobile'] ?? '') ?></small></td>
                        <td class="fw-bold">₹<?= number_format($r['amount'], 2) ?></td>
                        <td><code><?= htmlspecialchars($r['utr_number'] ?? '-') ?></code></td>
                        <td><small><?= $r['created_at'] ?></small></td>
                        <td>
                            <?php if ($r['status'] === 'pending'): ?>
                                <span class="badge bg-warning">Pending</span>
                            <?php elseif ($r['status'] === 'approved'): ?>
                                <span class="badge bg-success">Approved</span>
                            <?php else: ?>
                                <span class="badge bg-danger">Rejected</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end">
                            <?php if ($r['status'] === 'pending'): ?>
                                <a href="?approve=<?= $r['id'] ?>" class="btn btn-sm btn-success" onclick="return confirm('Approve this deposit?');"><i class="fas fa-check"></i> Approve</a>
                                <a href="?reject=<?= $r['id'] ?>" class="btn btn-sm btn-outline-danger" onclick="return confirm('Reject this deposit?');"><i class="fas fa-times"></i> Reject</a>
                            <?php else: ?>—<?php endif; ?>
                        </td>
                    </tr>
                <?php endforeach; endif; ?>
            </tbody>
        </table>
    </div>
</div>
<?php require_once 'includes/footer.php'; ?>