<?php
ob_start();
require_once dirname(__DIR__) . '/config/config.php';
require_once dirname(__DIR__) . '/classes/OxaPayAPI.php';
require_once dirname(__DIR__) . '/classes/PaymentChecker.php';
requireLogin();

$auth = new Auth();
$pdo = getDBConnection();
$userModel = new User();

// Check if OxaPay is configured
$oxapay = new OxaPayAPI();
$oxapayEnabled = $oxapay->isConfigured();

// Check and credit pending payments automatically
$credited = false;
if ($oxapayEnabled) {
    $credited = checkPendingCryptoPayments($_SESSION['user_id']);
}

// Refresh balance (after potential credits)
$currentBalance = $auth->refreshBalance($_SESSION['user_id']);

$error = '';
$success = '';
$paymentUrl = null;

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST' && verifyCSRFToken($_POST['csrf_token'] ?? '')) {
    $action = $_POST['action'] ?? '';
    
    if ($action === 'create_payment') {
        $amount = floatval($_POST['amount'] ?? 0);
        
        // Validate
        if ($amount < 5) {
            $error = 'Minimum deposit is $5';
        } elseif ($amount > 10000) {
            $error = 'Maximum deposit is $10,000';
        } else {
            // Generate unique order ID
            $orderId = 'WVR-' . $_SESSION['user_id'] . '-' . time() . '-' . rand(1000, 9999);
            
            // Callback URL
            $callbackUrl = SITE_URL . '/api/oxapay-webhook.php';
            $returnUrl = SITE_URL . '/user/add-funds?status=check';
            
            // Create invoice
            $result = $oxapay->createInvoice($amount, $orderId, $callbackUrl, $returnUrl);
            
            if (isset($result['result']) && $result['result'] == 100) {
                $paymentUrl = $result['payLink'] ?? '';
                $trackId = $result['trackId'] ?? '';
                
                // Save fund request
                try {
                    $stmt = $pdo->prepare("INSERT INTO fund_requests (user_id, amount, payment_method, payment_reference, payment_uuid, status, created_at) VALUES (?, ?, 'crypto', ?, ?, 'pending', NOW())");
                    $stmt->execute([
                        $_SESSION['user_id'],
                        $amount,
                        $orderId,
                        $trackId
                    ]);
                } catch (Exception $e) {
                    error_log('Fund request insert error: ' . $e->getMessage());
                }
                
                // Redirect to OxaPay payment page
                if ($paymentUrl) {
                    ob_end_clean();
                    header('Location: ' . $paymentUrl);
                    exit;
                }
                
                $success = 'Invoice created! Redirecting to payment...';
            } else {
                $error = $result['message'] ?? 'Failed to create invoice. Please try again.';
                error_log('OxaPay Error: ' . json_encode($result));
            }
        }
    }
    
    // Manual check button
    if ($action === 'check_status') {
        $success = 'Payment statuses checked and updated!';
    }
}

// Check for return status
$returnStatus = $_GET['status'] ?? '';
if ($returnStatus === 'success' || $returnStatus === 'check') {
    $success = 'Payment status updated! If paid, your balance has been credited.';
}

// Get recent fund requests
$stmt = $pdo->prepare("SELECT * FROM fund_requests WHERE user_id = ? AND payment_method = 'crypto' ORDER BY created_at DESC LIMIT 10");
$stmt->execute([$_SESSION['user_id']]);
$recentRequests = $stmt->fetchAll();
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Funds - <?php echo SITE_NAME; ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, sans-serif; background: #0A1628; color: #fff; min-height: 100vh; padding-bottom: 80px; }
        
        .header { background: #0F2744; padding: 1rem; display: flex; justify-content: space-between; align-items: center; position: sticky; top: 0; z-index: 100; }
        .header-back { background: none; border: none; color: #fff; font-size: 1.25rem; cursor: pointer; text-decoration: none; }
        .header-title { font-weight: 600; }
        .header-balance { background: #F5A623; color: #0A1628; padding: 0.5rem 1rem; border-radius: 20px; font-weight: 600; }
        
        .content { padding: 1.5rem; max-width: 500px; margin: 0 auto; }
        
        .alert { padding: 1rem; border-radius: 10px; margin-bottom: 1rem; display: flex; align-items: center; gap: 0.75rem; }
        .alert-success { background: rgba(16,185,129,0.15); border: 1px solid rgba(16,185,129,0.3); color: #10B981; }
        .alert-danger { background: rgba(239,68,68,0.15); border: 1px solid rgba(239,68,68,0.3); color: #EF4444; }
        .alert-info { background: rgba(59,130,246,0.15); border: 1px solid rgba(59,130,246,0.3); color: #3B82F6; }
        
        .card { background: #0F2744; border-radius: 16px; padding: 1.5rem; margin-bottom: 1rem; border: 1px solid #1E3A5F; }
        .card-title { font-size: 1.1rem; font-weight: 600; margin-bottom: 1rem; color: #F5A623; display: flex; align-items: center; gap: 0.5rem; }
        
        .crypto-badge { display: flex; align-items: center; gap: 0.75rem; padding: 1rem; background: #0A1628; border-radius: 12px; margin-bottom: 1.5rem; }
        .crypto-badge i { font-size: 2rem; color: #F5A623; }
        .crypto-badge .info h4 { font-size: 1rem; margin-bottom: 0.25rem; }
        .crypto-badge .info p { font-size: 0.8rem; color: #9CA3AF; }
        
        .form-group { margin-bottom: 1.25rem; }
        .form-label { display: block; margin-bottom: 0.5rem; color: #E5E7EB; font-size: 0.9rem; }
        .form-control { width: 100%; padding: 1rem; background: #0A1628; border: 1px solid #1E3A5F; border-radius: 10px; color: #fff; font-size: 1rem; }
        .form-control:focus { outline: none; border-color: #F5A623; }
        
        .amount-presets { display: grid; grid-template-columns: repeat(4, 1fr); gap: 0.5rem; margin-top: 0.75rem; }
        .preset-btn { background: #1E3A5F; border: none; padding: 0.5rem; border-radius: 8px; color: #fff; cursor: pointer; font-size: 0.85rem; transition: all 0.2s; }
        .preset-btn:hover { background: #F5A623; color: #0A1628; }
        
        .btn { display: block; width: 100%; padding: 1rem; border: none; border-radius: 12px; font-size: 1rem; font-weight: 600; cursor: pointer; text-align: center; transition: all 0.2s; }
        .btn-gold { background: #F5A623; color: #0A1628; }
        .btn-gold:hover { background: #D4880B; }
        .btn-blue { background: #3B82F6; color: #fff; margin-top: 0.5rem; }
        .btn-blue:hover { background: #2563EB; }
        .btn:disabled { opacity: 0.5; cursor: not-allowed; }
        
        .features { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem; margin-top: 1rem; }
        .feature { display: flex; align-items: center; gap: 0.5rem; font-size: 0.85rem; color: #9CA3AF; }
        .feature i { color: #10B981; }
        
        .recent-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 0.75rem; }
        .recent-title { font-size: 0.9rem; color: #9CA3AF; }
        .refresh-btn { background: none; border: none; color: #F5A623; cursor: pointer; font-size: 0.85rem; }
        .refresh-btn:hover { text-decoration: underline; }
        
        .recent-item { display: flex; justify-content: space-between; align-items: center; padding: 0.75rem; background: #0A1628; border-radius: 8px; margin-bottom: 0.5rem; }
        .recent-item .amount { font-weight: 600; color: #F5A623; }
        .recent-item .date { font-size: 0.75rem; color: #9CA3AF; }
        .recent-item .status { font-size: 0.75rem; padding: 0.25rem 0.5rem; border-radius: 4px; }
        .status-pending { background: rgba(245,166,35,0.2); color: #F5A623; }
        .status-approved { background: rgba(16,185,129,0.2); color: #10B981; }
        .status-rejected { background: rgba(239,68,68,0.2); color: #EF4444; }
        .status-expired { background: rgba(107,114,128,0.2); color: #9CA3AF; }
        .status-failed { background: rgba(239,68,68,0.2); color: #EF4444; }
        
        .bottom-nav { position: fixed; bottom: 0; left: 0; right: 0; background: #0F2744; display: flex; justify-content: space-around; padding: 0.75rem 0; border-top: 1px solid #1E3A5F; z-index: 100; }
        .bottom-nav a { display: flex; flex-direction: column; align-items: center; text-decoration: none; color: #9CA3AF; font-size: 0.7rem; gap: 0.25rem; padding: 0.5rem; }
        .bottom-nav a i { font-size: 1.25rem; }
        .bottom-nav a.active { color: #F5A623; }
        
        .pending-note { font-size: 0.8rem; color: #9CA3AF; margin-top: 1rem; padding: 0.75rem; background: rgba(59,130,246,0.1); border-radius: 8px; }
        .pending-note i { color: #3B82F6; margin-right: 0.5rem; }
    </style>
    <link rel="stylesheet" href="/assets/css/premium-dark.css">
</head>
<body>
    <header class="header">
        <a href="dashboard" class="header-back"><i class="fas fa-arrow-left"></i></a>
        <span class="header-title">Add Funds</span>
        <div class="header-balance"><?php echo formatCurrency($currentBalance); ?></div>
    </header>
    
    <main class="content">
        <?php if ($error): ?>
            <div class="alert alert-danger"><i class="fas fa-exclamation-circle"></i> <?php echo htmlspecialchars($error); ?></div>
        <?php endif; ?>
        
        <?php if ($success): ?>
            <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo htmlspecialchars($success); ?></div>
        <?php endif; ?>
        
        <?php if ($oxapayEnabled): ?>
            <div class="card">
                <h3 class="card-title"><i class="fas fa-coins"></i> Deposit with Crypto</h3>
                
                <div class="crypto-badge">
                    <i class="fab fa-bitcoin"></i>
                    <div class="info">
                        <h4>Bitcoin, USDT & More</h4>
                        <p>Pay with 50+ cryptocurrencies via OxaPay</p>
                    </div>
                </div>
                
                <form method="POST" id="cryptoForm">
                    <?php echo csrfTokenField(); ?>
                    <input type="hidden" name="action" value="create_payment">
                    
                    <div class="form-group">
                        <label class="form-label">Amount (USD)</label>
                        <input type="number" name="amount" id="amount" class="form-control" placeholder="Enter amount" min="5" max="10000" step="0.01" required>
                        <div class="amount-presets">
                            <button type="button" class="preset-btn" onclick="setAmount(10)">$10</button>
                            <button type="button" class="preset-btn" onclick="setAmount(25)">$25</button>
                            <button type="button" class="preset-btn" onclick="setAmount(50)">$50</button>
                            <button type="button" class="preset-btn" onclick="setAmount(100)">$100</button>
                        </div>
                    </div>
                    
                    <button type="submit" class="btn btn-gold">
                        <i class="fas fa-bolt"></i> Pay with Crypto
                    </button>
                    
                    <div class="features">
                        <div class="feature"><i class="fas fa-check"></i> Instant processing</div>
                        <div class="feature"><i class="fas fa-check"></i> 50+ cryptocurrencies</div>
                        <div class="feature"><i class="fas fa-check"></i> Secure payments</div>
                        <div class="feature"><i class="fas fa-check"></i> Auto credit</div>
                    </div>
                </form>
            </div>
            
        <?php else: ?>
            <div class="card">
                <h3 class="card-title"><i class="fas fa-exclamation-triangle"></i> Crypto Payments Unavailable</h3>
                <p style="color: #9CA3AF;">Crypto payment gateway is not configured. Please contact support.</p>
            </div>
        <?php endif; ?>
        
        <?php if (!empty($recentRequests)): ?>
        <div class="card">
            <div class="recent-header">
                <span class="recent-title">Recent Deposits</span>
                <form method="POST" style="display: inline;">
                    <?php echo csrfTokenField(); ?>
                    <input type="hidden" name="action" value="check_status">
                    <button type="submit" class="refresh-btn"><i class="fas fa-sync-alt"></i> Refresh Status</button>
                </form>
            </div>
            
            <?php 
            $hasPending = false;
            foreach ($recentRequests as $req): 
                if ($req['status'] === 'pending') $hasPending = true;
            ?>
            <div class="recent-item">
                <div>
                    <div class="amount"><?php echo formatCurrency($req['amount']); ?></div>
                    <div class="date"><?php echo date('M j, g:i A', strtotime($req['created_at'])); ?></div>
                </div>
                <span class="status status-<?php echo $req['status']; ?>">
                    <?php echo ucfirst($req['status']); ?>
                </span>
            </div>
            <?php endforeach; ?>
            
            <?php if ($hasPending): ?>
            <div class="pending-note">
                <i class="fas fa-info-circle"></i>
                Pending payments are checked automatically when you visit this page. Click "Refresh Status" to check again.
            </div>
            <?php endif; ?>
        </div>
        <?php endif; ?>
    </main>
    
    <nav class="bottom-nav">
        <a href="dashboard"><i class="fas fa-home"></i> Home</a>
        <a href="sms"><i class="fas fa-sms"></i> SMS</a>
        <a href="smm"><i class="fas fa-rocket"></i> SMM</a>
        <a href="orders"><i class="fas fa-history"></i> Orders</a>
        <a href="profile"><i class="fas fa-user"></i> Profile</a>
    </nav>
    
    <script>
    function setAmount(val) {
        document.getElementById('amount').value = val;
    }
    </script>
</body>
</html>