<?php
/**
 * Admin Withdrawals Management
 */
$pageTitle = 'Withdrawals';
require_once 'includes/header.php';

$filter = $_GET['status'] ?? 'pending';
$page = max(1, (int)($_GET['page'] ?? 1));
$perPage = 25;

$whereClause = "1=1";
$params = [];
if ($filter !== 'all') {
    $whereClause .= " AND w.status = :status";
    $params['status'] = $filter;
}

$totalWithdrawals = dbFetch("SELECT COUNT(*) as cnt FROM withdrawals w WHERE {$whereClause}", $params)['cnt'];
$totalPages = ceil($totalWithdrawals / $perPage);
$offset = ($page - 1) * $perPage;

$withdrawals = dbFetchAll(
    "SELECT w.*, u.email, u.first_name, u.last_name, u.id as uid
     FROM withdrawals w
     LEFT JOIN users u ON w.user_id = u.id
     WHERE {$whereClause}
     ORDER BY w.created_at DESC
     LIMIT {$perPage} OFFSET {$offset}",
    $params
);

// Stats
$stats = dbFetch("SELECT 
    COUNT(CASE WHEN status = 'pending' THEN 1 END) as pending_count,
    COUNT(CASE WHEN status = 'approved' THEN 1 END) as approved_count,
    SUM(CASE WHEN status = 'approved' THEN net_amount ELSE 0 END) as total_paid,
    SUM(CASE WHEN status = 'pending' THEN net_amount ELSE 0 END) as pending_amount
FROM withdrawals");

// Handle actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $wdId = $_POST['withdrawal_id'] ?? '';
    
    $withdrawal = dbFetch("SELECT * FROM withdrawals WHERE id = :id", ['id' => $wdId]);
    
    if ($withdrawal && $action === 'approve') {
        dbUpdate('withdrawals', [
            'status' => 'approved',
            'processed_at' => date('Y-m-d H:i:s'),
            'processed_by' => $admin['id']
        ], 'id = :id', ['id' => $wdId]);
        
        // Deduct from balance and bonus_balance priority
        $wallet = dbFetch("SELECT balance, bonus_balance FROM user_wallets WHERE user_id = :id", ['id' => $withdrawal['user_id']]);
        
        $amtToDeduct = (float)$withdrawal['amount'];
        $distBal = min((float)$wallet['balance'], $amtToDeduct);
        $distBonus = max(0, $amtToDeduct - $distBal);
        
        $newBalance = max(0, $wallet['balance'] - $distBal);
        
        dbUpdate('user_wallets', [
            'balance' => $newBalance,
            'bonus_balance' => max(0, $wallet['bonus_balance'] - $distBonus)
        ], 'user_id = :id', ['id' => $withdrawal['user_id']]);
        
        // Log transaction
        dbInsert('transactions', [
            'transaction_id' => 'TXN' . strtoupper(substr(md5(uniqid()), 0, 10)),
            'user_id' => $withdrawal['user_id'],
            'type' => 'withdrawal',
            'amount' => -$withdrawal['amount'],
            'balance_after' => $newBalance,
            'description' => 'Withdrawal approved: ' . $withdrawal['withdrawal_id']
        ]);
        
        // Notify user
        dbInsert('notifications', [
            'user_id' => $withdrawal['user_id'],
            'title' => 'Withdrawal Approved',
            'message' => 'Your withdrawal of ' . formatCurrency($withdrawal['net_amount']) . ' has been approved.',
            'type' => 'success'
        ]);
        
        redirect('withdrawals.php?status=' . $filter, 'Withdrawal approved!', 'success');
    } elseif ($withdrawal && $action === 'reject') {
        $reason = trim($_POST['reason'] ?? 'Rejected by admin');
        
        dbUpdate('withdrawals', [
            'status' => 'rejected',
            'reject_reason' => $reason,
            'processed_at' => date('Y-m-d H:i:s'),
            'processed_by' => $admin['id']
        ], 'id = :id', ['id' => $wdId]);
        
        // Notify user
        dbInsert('notifications', [
            'user_id' => $withdrawal['user_id'],
            'title' => 'Withdrawal Rejected',
            'message' => 'Your withdrawal of ' . formatCurrency($withdrawal['net_amount']) . ' has been rejected. Reason: ' . $reason,
            'type' => 'danger'
        ]);
        
        redirect('withdrawals.php?status=' . $filter, 'Withdrawal rejected!', 'success');
    }
}
?>

<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon yellow"><i class="fas fa-clock"></i></div>
        <div class="stat-value"><?= $stats['pending_count'] ?></div>
        <div class="stat-label">Pending</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon green"><i class="fas fa-check-circle"></i></div>
        <div class="stat-value"><?= $stats['approved_count'] ?></div>
        <div class="stat-label">Approved</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon blue"><i class="fas fa-money-bill-wave"></i></div>
        <div class="stat-value"><?= formatCurrency($stats['total_paid']) ?></div>
        <div class="stat-label">Total Paid</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon red"><i class="fas fa-hourglass-half"></i></div>
        <div class="stat-value"><?= formatCurrency($stats['pending_amount']) ?></div>
        <div class="stat-label">Pending Amount</div>
    </div>
</div>

<div class="card">
    <div class="card-header">
        <h3 class="card-title">Withdrawal Requests</h3>
        <div class="d-flex gap-2">
            <a href="?status=pending" class="btn btn-sm <?= $filter === 'pending' ? 'btn-primary' : 'btn-secondary' ?>">Pending</a>
            <a href="?status=approved" class="btn btn-sm <?= $filter === 'approved' ? 'btn-primary' : 'btn-secondary' ?>">Approved</a>
            <a href="?status=rejected" class="btn btn-sm <?= $filter === 'rejected' ? 'btn-primary' : 'btn-secondary' ?>">Rejected</a>
            <a href="?status=all" class="btn btn-sm <?= $filter === 'all' ? 'btn-primary' : 'btn-secondary' ?>">All</a>
        </div>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>User</th>
                        <th>Amount</th>
                        <th>Fee</th>
                        <th>Net</th>
                        <th>Method</th>
                        <th>Details</th>
                        <th>Status</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($withdrawals as $wd): ?>
                    <tr>
                        <td class="font-mono"><?= $wd['withdrawal_id'] ?></td>
                        <td>
                            <div class="font-semibold"><?= htmlspecialchars(($wd['first_name'] ?? '') . ' ' . ($wd['last_name'] ?? '')) ?></div>
                            <div class="text-muted" style="font-size: 0.75rem;"><?= $wd['uid'] ?></div>
                        </td>
                        <td class="font-mono"><?= formatCurrency($wd['amount']) ?></td>
                        <td class="font-mono text-red">-<?= formatCurrency($wd['fee']) ?></td>
                        <td class="font-mono font-semibold"><?= formatCurrency($wd['net_amount']) ?></td>
                        <td><?= ucfirst(str_replace('_', ' ', $wd['payment_method'])) ?></td>
                        <td style="font-size: 0.8rem;">
                            <?php if ($wd['payment_method'] === 'upi'): ?>
                                UPI: <?= $wd['upi_id'] ?>
                            <?php elseif ($wd['payment_method'] === 'bank_transfer'): ?>
                                <?= $wd['bank_name'] ?><br>
                                A/C: <?= $wd['account_number'] ?><br>
                                IFSC: <?= $wd['ifsc_code'] ?>
                            <?php elseif ($wd['payment_method'] === 'crypto'): ?>
                                <?= $wd['network'] ?>: <?= substr($wd['wallet_address'], 0, 15) ?>...
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php
                            $statusClasses = ['approved' => 'success', 'rejected' => 'danger'];
                            $statusClass = $statusClasses[$wd['status']] ?? 'warning';
                            ?>
                            <span class="badge badge-<?= $statusClass ?>"><?= ucfirst($wd['status']) ?></span>
                        </td>
                        <td class="text-muted"><?= formatDateTime($wd['created_at'], 'd M Y H:i') ?></td>
                        <td>
                            <?php if ($wd['status'] === 'pending'): ?>
                            <form method="POST" style="display: inline;">
                                <input type="hidden" name="withdrawal_id" value="<?= $wd['id'] ?>">
                                <input type="hidden" name="action" value="approve">
                                <button type="submit" class="btn btn-sm btn-success" onclick="return confirm('Approve this withdrawal?')">
                                    <i class="fas fa-check"></i>
                                </button>
                            </form>
                            <button type="button" class="btn btn-sm btn-danger" onclick="rejectWithdrawal(<?= $wd['id'] ?>)">
                                <i class="fas fa-times"></i>
                            </button>
                            <?php else: ?>
                            <span class="text-muted">--</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($withdrawals)): ?>
                    <tr><td colspan="10" class="text-center text-muted py-4">No withdrawals found</td></tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
</div>

<!-- Reject Modal -->
<div class="modal-overlay" id="rejectModal">
    <div class="modal-content">
        <div class="modal-header">
            <h4>Reject Withdrawal</h4>
            <button class="modal-close" onclick="closeModal('rejectModal')">&times;</button>
        </div>
        <form method="POST">
            <div class="modal-body">
                <input type="hidden" name="action" value="reject">
                <input type="hidden" name="withdrawal_id" id="rejectWdId">
                <div class="form-group">
                    <label class="form-label">Reason for Rejection</label>
                    <textarea name="reason" class="form-control" rows="3" required></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeModal('rejectModal')">Cancel</button>
                <button type="submit" class="btn btn-danger">Reject & Refund</button>
            </div>
        </form>
    </div>
</div>

<script>
function rejectWithdrawal(id) {
    document.getElementById('rejectWdId').value = id;
    document.getElementById('rejectModal').classList.add('active');
}

function closeModal(id) {
    document.getElementById(id).classList.remove('active');
}
</script>

<?php require_once 'includes/footer.php'; ?>
