<?php
/**
 * Admin - Deposit Management
 */

$pageTitle = 'Deposit Management';
require_once 'includes/header.php';

// Handle actions
if (isPost()) {
    $action = post('action');
    $depositId = (int)post('deposit_id');
    
    if (!verifyCsrfToken(post('csrf_token'))) {
        jsonError('Invalid request');
    }
    
    $deposit = dbFetch("SELECT * FROM deposits WHERE id = :id", ['id' => $depositId]);
    if (!$deposit) {
        jsonError('Deposit not found');
    }
    
    if ($deposit['status'] !== 'pending') {
        jsonError('Deposit already processed');
    }
    
    switch ($action) {
        case 'approve':
            try {
                dbBeginTransaction();
                
                // Update deposit status
                dbUpdate('deposits', [
                    'status' => 'approved',
                    'processed_by' => auth()->getAdminId(),
                    'processed_at' => date('Y-m-d H:i:s')
                ], 'id = :id', ['id' => $depositId]);
                
                // Get user wallet
                $wallet = dbFetch("SELECT * FROM user_wallets WHERE user_id = :id", ['id' => $deposit['user_id']]);
                
                // Calculate bonus
                $bonusAmount = 0;
                $depositBonus = getSetting('deposit_bonus', DEPOSIT_BONUS_PERCENT);
                if ($depositBonus > 0) {
                    $bonusAmount = ($deposit['amount'] * $depositBonus) / 100;
                }
                
                // Credit balance
                dbQuery(
                    "UPDATE user_wallets SET 
                        balance = balance + :amount,
                        bonus_balance = bonus_balance + :bonus,
                        total_deposit = total_deposit + :total
                     WHERE user_id = :user_id",
                    [
                        'amount' => $deposit['amount'],
                        'bonus' => $bonusAmount,
                        'total' => $deposit['amount'],
                        'user_id' => $deposit['user_id']
                    ]
                );
                
                // Update deposit with bonus
                if ($bonusAmount > 0) {
                    dbUpdate('deposits', [
                        'bonus_applied' => $bonusAmount,
                        'bonus_percent' => $depositBonus
                    ], 'id = :id', ['id' => $depositId]);
                }
                
                // Get updated wallet
                $newWallet = dbFetch("SELECT * FROM user_wallets WHERE user_id = :id", ['id' => $deposit['user_id']]);
                
                // Create transaction record
                dbInsert('transactions', [
                    'transaction_id' => generateTransactionId('DEP'),
                    'user_id' => $deposit['user_id'],
                    'type' => 'deposit',
                    'amount' => $deposit['amount'],
                    'balance_before' => $wallet['balance'],
                    'balance_after' => $newWallet['balance'],
                    'reference_type' => 'deposit',
                    'reference_id' => $deposit['id'],
                    'description' => "Deposit via {$deposit['payment_method']}"
                ]);
                
                // Create bonus transaction if applicable
                if ($bonusAmount > 0) {
                    dbInsert('transactions', [
                        'transaction_id' => generateTransactionId('BON'),
                        'user_id' => $deposit['user_id'],
                        'type' => 'bonus',
                        'amount' => $bonusAmount,
                        'balance_before' => $newWallet['balance'] - $bonusAmount,
                        'balance_after' => $newWallet['balance'],
                        'reference_type' => 'deposit',
                        'reference_id' => $deposit['id'],
                        'description' => "Deposit bonus ({$depositBonus}%)"
                    ]);
                    
                    dbInsert('bonuses', [
                        'user_id' => $deposit['user_id'],
                        'type' => 'deposit',
                        'amount' => $bonusAmount,
                        'reference_id' => $deposit['id']
                    ]);
                }
                
                // Send notification
                dbInsert('notifications', [
                    'user_id' => $deposit['user_id'],
                    'type' => 'deposit',
                    'title' => 'Deposit Approved',
                    'message' => "Your deposit of " . formatCurrency($deposit['amount']) . " has been approved and credited to your account." . ($bonusAmount > 0 ? " You also received a bonus of " . formatCurrency($bonusAmount) . "!" : "")
                ]);
                
                dbCommit();
                
                logActivity('admin', auth()->getAdminId(), 'deposit_approve', "Approved deposit #{$depositId} for " . formatCurrency($deposit['amount']));
                jsonSuccess('Deposit approved successfully');
                
            } catch (Exception $e) {
                dbRollback();
                error_log("Deposit Approval Error: " . $e->getMessage());
                jsonError('Failed to approve deposit');
            }
            break;
            
        case 'reject':
            $reason = post('reason', 'Rejected by admin');
            
            dbUpdate('deposits', [
                'status' => 'rejected',
                'rejection_reason' => $reason,
                'processed_by' => auth()->getAdminId(),
                'processed_at' => date('Y-m-d H:i:s')
            ], 'id = :id', ['id' => $depositId]);
            
            // Send notification
            dbInsert('notifications', [
                'user_id' => $deposit['user_id'],
                'type' => 'deposit',
                'title' => 'Deposit Rejected',
                'message' => "Your deposit of " . formatCurrency($deposit['amount']) . " has been rejected. Reason: {$reason}"
            ]);
            
            logActivity('admin', auth()->getAdminId(), 'deposit_reject', "Rejected deposit #{$depositId}");
            jsonSuccess('Deposit rejected');
            break;
            
        default:
            jsonError('Invalid action');
    }
}

// Get filters
$status = get('status', '');
$method = get('method', '');
$dateFrom = get('date_from', '');
$dateTo = get('date_to', '');
$page = max(1, (int)get('page', 1));
$perPage = 25;

// Build query
$where = "1=1";
$params = [];

if ($status) {
    $where .= " AND d.status = :status";
    $params['status'] = $status;
}

if ($method) {
    $where .= " AND d.payment_method = :method";
    $params['method'] = $method;
}

if ($dateFrom) {
    $where .= " AND DATE(d.created_at) >= :date_from";
    $params['date_from'] = $dateFrom;
}

if ($dateTo) {
    $where .= " AND DATE(d.created_at) <= :date_to";
    $params['date_to'] = $dateTo;
}

$total = dbFetch("SELECT COUNT(*) as count FROM deposits d WHERE {$where}", $params)['count'];
$pagination = paginate($total, $perPage, $page, 'deposits.php');

$deposits = dbFetchAll(
    "SELECT d.*, u.email, u.first_name, u.last_name, u.user_id as user_code,
            COALESCE(d.auto_verified, 0) as auto_verified,
            d.utr_number, d.ip_address, d.device_info
     FROM deposits d 
     LEFT JOIN users u ON d.user_id = u.id 
     WHERE {$where}
     ORDER BY d.created_at DESC
     LIMIT {$pagination['limit']} OFFSET {$pagination['offset']}",
    $params
);

// Get auto-verified stats
$autoVerifiedCount = dbFetch("SELECT COUNT(*) as cnt FROM deposits WHERE auto_verified = 1");
$autoVerifiedCount = (int)($autoVerifiedCount['cnt'] ?? 0);

// Get summary
$summary = dbFetch(
    "SELECT 
        COUNT(*) as total,
        SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
        SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) as approved,
        SUM(CASE WHEN status = 'approved' THEN amount ELSE 0 END) as total_approved,
        SUM(CASE WHEN status = 'pending' THEN amount ELSE 0 END) as total_pending
     FROM deposits d WHERE {$where}",
    $params
);
?>

<style>
.deposit-stats {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    gap: 1rem;
    margin-bottom: 1.5rem;
}

@media (max-width: 992px) {
    .deposit-stats { grid-template-columns: repeat(2, 1fr); }
}

.receipt-preview {
    max-width: 100px;
    max-height: 60px;
    object-fit: cover;
    border-radius: var(--radius-sm);
    cursor: pointer;
}

.receipt-modal img {
    max-width: 100%;
    max-height: 70vh;
}
</style>

<!-- Summary Stats -->
<div class="deposit-stats">
    <div class="stat-card">
        <div class="stat-icon yellow">
            <i class="fas fa-clock"></i>
        </div>
        <div class="stat-value"><?= number_format($summary['pending'] ?? 0) ?></div>
        <div class="stat-label">Pending Deposits</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon green">
            <i class="fas fa-check"></i>
        </div>
        <div class="stat-value"><?= number_format($summary['approved'] ?? 0) ?></div>
        <div class="stat-label">Approved Deposits</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon blue">
            <i class="fas fa-rupee-sign"></i>
        </div>
        <div class="stat-value"><?= formatCurrency($summary['total_approved'] ?? 0) ?></div>
        <div class="stat-label">Total Approved</div>
    </div>
    <div class="stat-card">
        <div class="stat-icon purple">
            <i class="fas fa-hourglass-half"></i>
        </div>
        <div class="stat-value"><?= formatCurrency($summary['total_pending'] ?? 0) ?></div>
        <div class="stat-label">Pending Amount</div>
    </div>
</div>

<!-- Filters -->
<div class="card mb-4">
    <div class="card-body">
        <form class="d-flex gap-2 flex-wrap" method="GET">
            <select name="status" class="form-control form-select" style="width: auto;">
                <option value="">All Status</option>
                <option value="pending" <?= $status === 'pending' ? 'selected' : '' ?>>Pending</option>
                <option value="approved" <?= $status === 'approved' ? 'selected' : '' ?>>Approved</option>
                <option value="rejected" <?= $status === 'rejected' ? 'selected' : '' ?>>Rejected</option>
            </select>
            
            <select name="method" class="form-control form-select" style="width: auto;">
                <option value="">All Methods</option>
                <option value="upi" <?= $method === 'upi' ? 'selected' : '' ?>>UPI</option>
                <option value="bank_transfer" <?= $method === 'bank_transfer' ? 'selected' : '' ?>>Bank Transfer</option>
                <option value="crypto" <?= $method === 'crypto' ? 'selected' : '' ?>>Crypto</option>
            </select>
            
            <input type="date" name="date_from" class="form-control" value="<?= $dateFrom ?>" style="width: auto;">
            <input type="date" name="date_to" class="form-control" value="<?= $dateTo ?>" style="width: auto;">
            
            <button type="submit" class="btn btn-primary">
                <i class="fas fa-search"></i> Filter
            </button>
            <a href="deposits.php" class="btn btn-secondary">
                <i class="fas fa-times"></i> Clear
            </a>
        </form>
    </div>
</div>

<!-- Deposits Table -->
<div class="card">
    <div class="card-header">
        <h3 class="card-title">Deposits (<?= number_format($total) ?>)</h3>
    </div>
    <div class="card-body p-0">
        <div class="table-responsive">
            <table class="table">
                <thead>
                    <tr>
                        <th>Deposit ID</th>
                        <th>User</th>
                        <th>Amount</th>
                        <th>Method</th>
                        <th>UTR / Txn ID</th>
                        <th>Receipt</th>
                        <th>Status</th>
                        <th>Verified</th>
                        <th>Date</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($deposits as $deposit): ?>
                    <tr>
                        <td>
                            <div class="font-mono font-semibold"><?= $deposit['deposit_id'] ?></div>
                        </td>
                        <td>
                            <div><?= htmlspecialchars($deposit['first_name'] ?? 'N/A') ?></div>
                            <div class="text-muted" style="font-size: 0.75rem;"><?= $deposit['user_code'] ?></div>
                        </td>
                        <td>
                            <div class="font-mono font-semibold text-green"><?= formatCurrency($deposit['amount']) ?></div>
                            <?php if ($deposit['bonus_applied'] > 0): ?>
                            <div class="text-yellow" style="font-size: 0.75rem;">
                                +<?= formatCurrency($deposit['bonus_applied']) ?> bonus
                            </div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <span class="badge badge-info"><?= ucfirst(str_replace('_', ' ', $deposit['payment_method'])) ?></span>
                        </td>
                        <td>
                            <?php if (!empty($deposit['utr_number'])): ?>
                            <div class="font-mono" style="font-size: 0.8rem;"><?= htmlspecialchars($deposit['utr_number']) ?></div>
                            <?php elseif ($deposit['transaction_id']): ?>
                            <div class="font-mono" style="font-size: 0.8rem;"><?= htmlspecialchars($deposit['transaction_id']) ?></div>
                            <?php else: ?>
                            <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($deposit['receipt_image']): ?>
                            <img src="<?= SITE_URL ?>/uploads/receipts/<?= $deposit['receipt_image'] ?>" 
                                 class="receipt-preview" 
                                 onclick="viewReceipt('<?= SITE_URL ?>/uploads/receipts/<?= $deposit['receipt_image'] ?>')">
                            <?php else: ?>
                            <span class="text-muted">No receipt</span>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php
                            $statusClasses = ['approved' => 'success', 'rejected' => 'danger', 'pending' => 'warning'];
                            $statusClass = $statusClasses[$deposit['status']] ?? 'secondary';
                            ?>
                            <span class="badge badge-<?= $statusClass ?>"><?= ucfirst($deposit['status']) ?></span>
                            <?php if ($deposit['rejection_reason']): ?>
                            <div class="text-muted" style="font-size: 0.7rem;" title="<?= htmlspecialchars($deposit['rejection_reason']) ?>">
                                <?= truncate($deposit['rejection_reason'], 30) ?>
                            </div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if (!empty($deposit['auto_verified']) && $deposit['auto_verified']): ?>
                                <span class="badge badge-info" style="background:rgba(59,130,246,.15);color:var(--accent-blue)">⚡ Auto</span>
                            <?php elseif ($deposit['status'] === 'approved'): ?>
                                <span class="badge badge-success">Manual</span>
                            <?php else: ?>
                                <span class="text-muted">-</span>
                            <?php endif; ?>
                            <?php if (!empty($deposit['ip_address'])): ?>
                                <div class="text-muted" style="font-size:.65rem" title="<?= htmlspecialchars($deposit['device_info'] ?? '') ?>"><?= htmlspecialchars($deposit['ip_address']) ?></div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <div><?= formatDateTime($deposit['created_at'], 'd M Y') ?></div>
                            <div class="text-muted" style="font-size: 0.75rem;"><?= formatDateTime($deposit['created_at'], 'H:i:s') ?></div>
                        </td>
                        <td>
                            <?php if ($deposit['status'] === 'pending'): ?>
                            <div class="d-flex gap-1">
                                <button class="btn btn-sm btn-success" onclick="approveDeposit(<?= $deposit['id'] ?>)">
                                    <i class="fas fa-check"></i>
                                </button>
                                <button class="btn btn-sm btn-danger" onclick="rejectDeposit(<?= $deposit['id'] ?>)">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                            <?php else: ?>
                            <span class="text-muted">-</span>
                            <?php endif; ?>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                    <?php if (empty($deposits)): ?>
                    <tr>
                        <td colspan="10" class="text-center text-muted py-4">No deposits found</td>
                    </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php if ($total > $perPage): ?>
    <div class="card-footer">
        <?= $pagination['html'] ?>
    </div>
    <?php endif; ?>
</div>

<!-- Receipt Modal -->
<div class="modal-overlay" id="receiptModal">
    <div class="modal receipt-modal">
        <div class="modal-header">
            <h3 class="modal-title">Payment Receipt</h3>
            <button class="modal-close" onclick="closeModal('receiptModal')">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="modal-body text-center">
            <img id="receiptImage" src="" alt="Receipt">
        </div>
    </div>
</div>

<script>
function openModal(id) {
    document.getElementById(id).classList.add('active');
}

function closeModal(id) {
    document.getElementById(id).classList.remove('active');
}

function viewReceipt(url) {
    document.getElementById('receiptImage').src = url;
    openModal('receiptModal');
}

function approveDeposit(depositId) {
    if (confirm('Are you sure you want to approve this deposit? The amount will be credited to user\'s account.')) {
        ajaxRequest('deposits.php', {
            action: 'approve',
            deposit_id: depositId,
            csrf_token: '<?= generateCsrfToken() ?>'
        }, function(response) {
            if (response.success) {
                showToast(response.message);
                location.reload();
            } else {
                showToast(response.error, 'danger');
            }
        });
    }
}

function rejectDeposit(depositId) {
    const reason = prompt('Enter reason for rejection:');
    if (reason !== null) {
        ajaxRequest('deposits.php', {
            action: 'reject',
            deposit_id: depositId,
            reason: reason,
            csrf_token: '<?= generateCsrfToken() ?>'
        }, function(response) {
            if (response.success) {
                showToast(response.message);
                location.reload();
            } else {
                showToast(response.error, 'danger');
            }
        });
    }
}
</script>

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