<?php
/**
 * Admin - UPI Payment Management
 * View pending payments and manually confirm them
 */

// Load required files for processing
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../config/database.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/Auth.php';

// Check admin auth
if (!auth()->isAdmin()) {
    header('Location: login.php');
    exit;
}

$message = '';
$messageType = '';

// Handle actions BEFORE including header
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $paymentId = (int)($_POST['payment_id'] ?? 0);
    
    if ($action === 'confirm' && $paymentId) {
        $utr = trim($_POST['utr'] ?? '');
        
        $payment = dbFetch("SELECT * FROM upi_payments WHERE id = :id", ['id' => $paymentId]);
        
        if ($payment && $payment['status'] === 'pending') {
            try {
                dbBeginTransaction();
                
                $userId = $payment['user_id'];
                $amount = (float)$payment['amount'];
                
                // Update payment status
                dbUpdate('upi_payments', [
                    'status' => 'completed',
                    'utr_number' => $utr,
                    'completed_at' => date('Y-m-d H:i:s'),
                    'confirmed_by' => $_SESSION['user_id'] ?? auth()->getAdminId()
                ], 'id = :id', ['id' => $paymentId]);
                
                // Get current balance from user_wallets table (users table has no balance column)
                $walletInfo = dbFetch("SELECT balance FROM user_wallets WHERE user_id = :uid", ['uid' => $userId]);
                $currentBalance = (float)($walletInfo['balance'] ?? 0);
                $newBalance = $currentBalance + $amount;
                
                // Check if wallet exists
                $wallet = dbFetch("SELECT * FROM user_wallets WHERE user_id = :uid", ['uid' => $userId]);
                if ($wallet) {
                    dbQuery(
                        "UPDATE user_wallets SET balance = balance + :amt1, total_deposit = COALESCE(total_deposit, 0) + :amt2 WHERE user_id = :uid",
                        ['amt1' => $amount, 'amt2' => $amount, 'uid' => $userId]
                    );
                } else {
                    // Create wallet if not exists
                    dbInsert('user_wallets', [
                        'user_id' => $userId,
                        'balance' => $amount,
                        'total_deposit' => $amount
                    ]);
                }
                
                // Apply bonus if enabled
                $bonusEnabled = getSetting('deposit_bonus_enabled', '0') === '1';
                $bonusMinAmount = (float)getSetting('deposit_bonus_min_amount', 0);
                $bonusAmount = 0;
                
                if ($bonusEnabled && $amount >= $bonusMinAmount) {
                    // Find applicable bonus tier
                    $bonusTier = dbFetch(
                        "SELECT * FROM deposit_bonus_tiers WHERE min_amount <= :amt AND status = 'active' ORDER BY min_amount DESC LIMIT 1",
                        ['amt' => $amount]
                    );
                    
                    if ($bonusTier && $bonusTier['bonus_percent'] > 0) {
                        $bonusPercent = (float)$bonusTier['bonus_percent'];
                        $bonusMaxBonus = (float)getSetting('deposit_bonus_max_bonus', 0);
                        $bonusAmount = $amount * ($bonusPercent / 100);
                        
                        // Apply max bonus cap
                        if ($bonusMaxBonus > 0 && $bonusAmount > $bonusMaxBonus) {
                            $bonusAmount = $bonusMaxBonus;
                        }
                        
                        // Add bonus to wallet
                        dbQuery(
                            "UPDATE user_wallets SET bonus_balance = COALESCE(bonus_balance, 0) + :bonus WHERE user_id = :uid",
                            ['bonus' => $bonusAmount, 'uid' => $userId]
                        );
                        
                        // Set turnover requirement based on (deposit + bonus)
                        $turnoverMultiplier = (float)getSetting('bonus_turnover_multiplier', 30);
                        $turnoverRequired = ($amount + $bonusAmount) * $turnoverMultiplier;
                        dbQuery(
                            "UPDATE users SET turnover_required = COALESCE(turnover_required, 0) + :tr WHERE id = :uid",
                            ['tr' => $turnoverRequired, 'uid' => $userId]
                        );
                        
                        // Set CFD withdrawal threshold
                        $cfdMultiplier = (float)getSetting('cfd_balance_multiplier', 3);
                        $cfdThreshold = ($amount + $bonusAmount) * $cfdMultiplier;
                        dbQuery(
                            "UPDATE users SET cfd_withdraw_threshold = COALESCE(cfd_withdraw_threshold, 0) + :ct WHERE id = :uid",
                            ['ct' => $cfdThreshold, 'uid' => $userId]
                        );
                        
                        // Record bonus transaction
                        dbInsert('transactions', [
                            'transaction_id' => 'BNS' . strtoupper(substr(md5(uniqid()), 0, 10)),
                            'user_id' => $userId,
                            'type' => 'bonus',
                            'amount' => $bonusAmount,
                            'balance_before' => $newBalance,
                            'balance_after' => $newBalance + $bonusAmount,
                            'description' => 'Deposit Bonus ' . $bonusPercent . '% (Tier: ' . $bonusTier['tier_type'] . ')',
                            'status' => 'completed'
                        ]);
                    }
                }
                
                // Create deposit record
                dbInsert('deposits', [
                    'deposit_id' => 'DEP' . strtoupper(substr(md5(uniqid()), 0, 10)),
                    'user_id' => $userId,
                    'amount' => $amount,
                    'payment_method' => 'upi',
                    'transaction_id' => $utr,
                    'status' => 'approved',
                    'processed_by' => $_SESSION['user_id'] ?? auth()->getAdminId(),
                    'processed_at' => date('Y-m-d H:i:s')
                ]);
                
                // Create transaction
                dbInsert('transactions', [
                    'user_id' => $userId,
                    'type' => 'deposit',
                    'amount' => $amount,
                    'balance_after' => $newBalance,
                    'description' => 'UPI Deposit confirmed by Admin',
                    'reference_id' => $payment['payment_ref'],
                    'status' => 'completed'
                ]);
                
                dbCommit();
                
                $bonusMsg = $bonusAmount > 0 ? " + ₹" . number_format($bonusAmount, 2) . " bonus" : "";
                $message = "Payment confirmed! ₹" . number_format($amount, 2) . $bonusMsg . " credited to user. New balance: ₹" . number_format($newBalance, 2);
                $messageType = 'success';
                
            } catch (Exception $e) {
                dbRollback();
                $message = "Error: " . $e->getMessage();
                $messageType = 'error';
            }
        } else {
            $message = "Payment not found or already processed.";
            $messageType = 'error';
        }
    } elseif ($action === 'reject' && $paymentId) {
        $reason = trim($_POST['reason'] ?? 'Payment rejected by admin');
        
        dbUpdate('upi_payments', [
            'status' => 'failed',
            'rejection_reason' => $reason,
            'completed_at' => date('Y-m-d H:i:s'),
            'confirmed_by' => $_SESSION['user_id'] ?? auth()->getAdminId()
        ], 'id = :id', ['id' => $paymentId]);
        
        $message = "Payment rejected.";
        $messageType = 'success';
    }
}

// Now include header for HTML page
$pageTitle = 'UPI Payments';
require_once 'includes/header.php';

// Get filter
$filter = $_GET['status'] ?? 'pending';

// Get payments
$whereClause = $filter !== 'all' ? "WHERE p.status = '{$filter}'" : "";
$payments = dbFetchAll(
    "SELECT p.*, u.email, u.first_name, u.last_name, u.phone,
            COALESCE(p.auto_verified, 0) as auto_verified,
            p.ip_address, p.device_info, p.verification_notes
     FROM upi_payments p 
     LEFT JOIN users u ON p.user_id = u.id 
     {$whereClause}
     ORDER BY p.created_at DESC 
     LIMIT 100"
);

// Stats
$stats = [
    'pending' => dbFetch("SELECT COUNT(*) as c, COALESCE(SUM(amount), 0) as t FROM upi_payments WHERE status = 'pending'"),
    'completed' => dbFetch("SELECT COUNT(*) as c, COALESCE(SUM(amount), 0) as t FROM upi_payments WHERE status = 'completed' AND DATE(completed_at) = CURDATE()"),
    'failed' => dbFetch("SELECT COUNT(*) as c FROM upi_payments WHERE status = 'failed' AND DATE(created_at) = CURDATE()")
];
?>

<style>
.payment-card { background: var(--bg-card); border: 1px solid var(--border-color); border-radius: 12px; padding: 1.25rem; margin-bottom: 1rem; }
.payment-header { display: flex; justify-content: space-between; align-items: start; margin-bottom: 1rem; }
.payment-amount { font-size: 1.5rem; font-weight: 700; color: var(--accent-green); font-family: var(--font-mono); }
.payment-meta { display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr)); gap: 1rem; font-size: 0.85rem; }
.meta-item { color: var(--text-muted); }
.meta-item strong { color: var(--text-primary); display: block; }
.payment-actions { display: flex; gap: 0.5rem; margin-top: 1rem; padding-top: 1rem; border-top: 1px solid var(--border-color); }
.confirm-form { display: flex; gap: 0.5rem; flex-wrap: wrap; align-items: center; }
.confirm-form input { padding: 0.5rem; border-radius: 6px; border: 1px solid var(--border-color); background: var(--bg-primary); color: var(--text-primary); }
</style>

<div class="content-header">
    <h1><i class="fas fa-mobile-alt"></i> UPI Payments</h1>
    <a href="upi-settings.php" class="btn btn-secondary"><i class="fas fa-cog"></i> UPI Settings</a>
</div>

<?php if ($message): ?>
<div class="alert alert-<?= $messageType ?>"><?= $message ?></div>
<?php endif; ?>

<!-- Stats Cards -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon warning"><i class="fas fa-clock"></i></div>
        <div class="stat-info">
            <div class="stat-value"><?= $stats['pending']['c'] ?? 0 ?></div>
            <div class="stat-label">Pending</div>
            <div class="stat-change">₹<?= number_format($stats['pending']['t'] ?? 0, 2) ?></div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon success"><i class="fas fa-check-circle"></i></div>
        <div class="stat-info">
            <div class="stat-value"><?= $stats['completed']['c'] ?? 0 ?></div>
            <div class="stat-label">Today Completed</div>
            <div class="stat-change">₹<?= number_format($stats['completed']['t'] ?? 0, 2) ?></div>
        </div>
    </div>
    <div class="stat-card">
        <div class="stat-icon danger"><i class="fas fa-times-circle"></i></div>
        <div class="stat-info">
            <div class="stat-value"><?= $stats['failed']['c'] ?? 0 ?></div>
            <div class="stat-label">Today Failed</div>
        </div>
    </div>
</div>

<!-- Filter Tabs -->
<div class="card">
    <div class="card-header">
        <div class="tabs">
            <a href="?status=pending" class="tab <?= $filter === 'pending' ? 'active' : '' ?>">Pending</a>
            <a href="?status=completed" class="tab <?= $filter === 'completed' ? 'active' : '' ?>">Completed</a>
            <a href="?status=failed" class="tab <?= $filter === 'failed' ? 'active' : '' ?>">Failed</a>
            <a href="?status=all" class="tab <?= $filter === 'all' ? 'active' : '' ?>">All</a>
        </div>
    </div>
    
    <div class="card-body">
        <?php if (empty($payments)): ?>
            <div class="empty-state">
                <i class="fas fa-inbox"></i>
                <p>No payments found</p>
            </div>
        <?php else: ?>
            <?php foreach ($payments as $payment): ?>
            <div class="payment-card">
                <div class="payment-header">
                    <div class="payment-amount">₹<?= number_format($payment['amount'], 2) ?></div>
                    <span class="badge badge-<?= $payment['status'] === 'completed' ? 'success' : ($payment['status'] === 'pending' ? 'warning' : 'danger') ?>">
                        <?= ucfirst($payment['status']) ?>
                    </span>
                    <?php if (!empty($payment['auto_verified']) && $payment['auto_verified']): ?>
                        <span class="badge badge-info" style="background:rgba(59,130,246,.15);color:#3b82f6;margin-left:4px">⚡ Auto-Verified</span>
                    <?php endif; ?>
                </div>
                
                <div class="payment-meta">
                    <div class="meta-item">
                        <strong><?= htmlspecialchars($payment['first_name'] . ' ' . $payment['last_name']) ?></strong>
                        <?= htmlspecialchars($payment['email']) ?>
                    </div>
                    <div class="meta-item">
                        <strong>Reference</strong>
                        <?= htmlspecialchars($payment['payment_ref']) ?>
                    </div>
                    <div class="meta-item">
                        <strong>Phone</strong>
                        <?= htmlspecialchars($payment['phone'] ?? 'N/A') ?>
                    </div>
                    <div class="meta-item">
                        <strong>Created</strong>
                        <?= date('d M Y, h:i A', strtotime($payment['created_at'])) ?>
                    </div>
                    <?php if ($payment['utr_number']): ?>
                    <div class="meta-item">
                        <strong>UTR Number</strong>
                        <?= htmlspecialchars($payment['utr_number']) ?>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($payment['ip_address'])): ?>
                    <div class="meta-item">
                        <strong>IP Address</strong>
                        <?= htmlspecialchars($payment['ip_address']) ?>
                    </div>
                    <?php endif; ?>
                    <?php if (!empty($payment['verification_notes'])): ?>
                    <div class="meta-item" style="grid-column:1/-1">
                        <strong>Verification Notes</strong>
                        <span style="font-size:.82rem;color:var(--text-muted)"><?= htmlspecialchars($payment['verification_notes']) ?></span>
                    </div>
                    <?php endif; ?>
                </div>
                
                <?php if ($payment['status'] === 'pending'): ?>
                <div class="payment-actions">
                    <form method="POST" class="confirm-form" onsubmit="return confirm('Confirm this payment?')">
                        <input type="hidden" name="action" value="confirm">
                        <input type="hidden" name="payment_id" value="<?= $payment['id'] ?>">
                        <input type="text" name="utr" placeholder="UTR Number (optional)" style="width: 180px;">
                        <button type="submit" class="btn btn-success btn-sm"><i class="fas fa-check"></i> Confirm</button>
                    </form>
                    <form method="POST" style="display: inline;" onsubmit="return confirm('Reject this payment?')">
                        <input type="hidden" name="action" value="reject">
                        <input type="hidden" name="payment_id" value="<?= $payment['id'] ?>">
                        <button type="submit" class="btn btn-danger btn-sm"><i class="fas fa-times"></i> Reject</button>
                    </form>
                </div>
                <?php endif; ?>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
</div>

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