<?php
require_once 'config.php';
require_once 'classes/Security.php';
require_once 'classes/Trading.php';
require_once 'classes/Wallet.php';
require_once 'classes/KYC.php';

Security::requireAuth();

$pageTitle = 'P2P Trading - CryptoExchange Pro | Secure Cryptocurrency Trading Platform';
$pageDescription = 'Trade cryptocurrencies peer-to-peer with escrow protection. Buy and sell Bitcoin, Ethereum, and other cryptocurrencies safely.';

$trading = new Trading();
$wallet = new Wallet();
$kyc = new KYC();

// Check KYC status
$kycCheck = $kyc->canUserTrade($_SESSION['user_id']);

// Get available trades
$selectedCrypto = $_GET['crypto'] ?? null;
$availableTrades = $trading->getAvailableTrades($selectedCrypto, 50);

// Get user's trades
$userTrades = $trading->getUserTrades($_SESSION['user_id']);

// Get user wallets for sell order form
$userWallets = $wallet->getUserWallets($_SESSION['user_id']);

// Get all cryptocurrencies
$db = new Database();
$db->query("SELECT * FROM cryptocurrencies WHERE is_active = 1 ORDER BY symbol");
$cryptocurrencies = $db->resultSet();

include 'includes/header.php';
?>

<main class="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 py-8">
    <div class="container mx-auto px-4">
        <!-- Header -->
        <div class="mb-8">
            <h1 class="text-4xl font-bold text-gray-800 mb-2">
                <i class="fas fa-exchange-alt text-blue-600 mr-3"></i>P2P Trading
            </h1>
            <p class="text-gray-600">Trade cryptocurrencies peer-to-peer with escrow protection</p>
        </div>

        <!-- KYC Warning -->
        <?php if (!$kycCheck['can_trade']): ?>
        <div class="bg-yellow-100 border-l-4 border-yellow-500 p-4 mb-6 rounded-r-lg">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas fa-exclamation-triangle text-yellow-500 text-xl"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm text-yellow-700">
                        <strong>KYC Verification Required:</strong> <?php echo $kycCheck['message']; ?>
                        <a href="kyc.php" class="underline font-medium">Complete verification now</a>
                    </p>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- Trading Interface -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Available Trades -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-xl shadow-xl overflow-hidden">
                    <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b">
                        <div class="flex items-center justify-between">
                            <h2 class="text-xl font-bold text-gray-800">
                                <i class="fas fa-shopping-cart text-green-600 mr-2"></i>Available Trades
                            </h2>
                            <div class="flex items-center space-x-4">
                                <select id="cryptoFilter" class="px-3 py-2 border border-gray-300 rounded-lg text-sm">
                                    <option value="">All Cryptocurrencies</option>
                                    <?php foreach ($cryptocurrencies as $crypto): ?>
                                    <option value="<?php echo $crypto['id']; ?>" <?php echo $selectedCrypto == $crypto['id'] ? 'selected' : ''; ?>>
                                        <?php echo $crypto['symbol']; ?> - <?php echo $crypto['name']; ?>
                                    </option>
                                    <?php endforeach; ?>
                                </select>
                                <button onclick="refreshTrades()" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-lg text-sm transition-colors duration-200">
                                    <i class="fas fa-sync-alt mr-1"></i>Refresh
                                </button>
                            </div>
                        </div>
                    </div>
                    <div class="p-6">
                        <?php if (!empty($availableTrades)): ?>
                        <div class="overflow-x-auto">
                            <table class="w-full" id="tradesTable">
                                <thead>
                                    <tr class="border-b-2 border-gray-200">
                                        <th class="text-left py-3 px-4 font-semibold text-gray-700">Seller</th>
                                        <th class="text-left py-3 px-4 font-semibold text-gray-700">Asset</th>
                                        <th class="text-right py-3 px-4 font-semibold text-gray-700">Amount</th>
                                        <th class="text-right py-3 px-4 font-semibold text-gray-700">Price</th>
                                        <th class="text-right py-3 px-4 font-semibold text-gray-700">Total</th>
                                        <th class="text-left py-3 px-4 font-semibold text-gray-700">Payment</th>
                                        <th class="text-center py-3 px-4 font-semibold text-gray-700">Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($availableTrades as $trade): ?>
                                    <tr class="border-b border-gray-100 hover:bg-gray-50 transition-colors duration-200">
                                        <td class="py-4 px-4">
                                            <div class="flex items-center">
                                                <div class="w-8 h-8 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full flex items-center justify-center text-white font-bold text-sm mr-3">
                                                    <?php echo substr($trade['seller_username'], 0, 1); ?>
                                                </div>
                                                <span class="font-medium text-gray-800"><?php echo $trade['seller_username']; ?></span>
                                            </div>
                                        </td>
                                        <td class="py-4 px-4">
                                            <div class="font-bold text-gray-800"><?php echo $trade['symbol']; ?></div>
                                            <div class="text-sm text-gray-500"><?php echo $trade['name']; ?></div>
                                        </td>
                                        <td class="py-4 px-4 text-right font-mono text-gray-800">
                                            <?php echo number_format($trade['amount'], 8); ?>
                                        </td>
                                        <td class="py-4 px-4 text-right font-bold text-green-600">
                                            $<?php echo number_format($trade['price_per_unit'], 2); ?>
                                        </td>
                                        <td class="py-4 px-4 text-right font-bold text-blue-600">
                                            $<?php echo number_format($trade['total_amount'], 2); ?>
                                        </td>
                                        <td class="py-4 px-4">
                                            <span class="px-3 py-1 bg-blue-100 text-blue-800 rounded-full text-xs font-medium">
                                                <?php echo strtoupper($trade['payment_method']); ?>
                                            </span>
                                        </td>
                                        <td class="py-4 px-4 text-center">
                                            <?php if ($kycCheck['can_trade'] && $trade['seller_id'] != $_SESSION['user_id']): ?>
                                            <button onclick="buyTrade(<?php echo $trade['id']; ?>)" class="bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-lg text-sm font-medium transition-colors duration-200">
                                                <i class="fas fa-shopping-cart mr-1"></i>Buy
                                            </button>
                                            <?php else: ?>
                                            <span class="text-gray-400 text-sm">Unavailable</span>
                                            <?php endif; ?>
                                        </td>
                                    </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        <?php else: ?>
                        <div class="text-center py-12">
                            <i class="fas fa-shopping-cart text-6xl text-gray-300 mb-4"></i>
                            <h3 class="text-xl font-semibold text-gray-600 mb-2">No trades available</h3>
                            <p class="text-gray-500">Be the first to create a sell order!</p>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>

            <!-- Create Sell Order -->
            <div class="lg:col-span-1">
                <div class="bg-white rounded-xl shadow-xl overflow-hidden mb-6">
                    <div class="bg-gradient-to-r from-red-50 to-red-100 px-6 py-4 border-b">
                        <h2 class="text-xl font-bold text-gray-800">
                            <i class="fas fa-plus-circle text-red-600 mr-2"></i>Create Sell Order
                        </h2>
                    </div>
                    <div class="p-6">
                        <?php if ($kycCheck['can_trade']): ?>
                        <form id="sellOrderForm" class="space-y-4">
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Cryptocurrency</label>
                                <select name="crypto_id" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                                    <option value="">Select Cryptocurrency</option>
                                    <?php foreach ($userWallets as $w): ?>
                                    <?php if ($w['balance'] > 0): ?>
                                    <option value="<?php echo $w['crypto_id']; ?>" data-balance="<?php echo $w['balance']; ?>">
                                        <?php echo $w['symbol']; ?> (Balance: <?php echo number_format($w['balance'], 8); ?>)
                                    </option>
                                    <?php endif; ?>
                                    <?php endforeach; ?>
                                </select>
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Amount</label>
                                <input type="number" name="amount" step="0.00000001" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                                <p class="text-xs text-gray-500 mt-1">Available balance will be shown after selecting cryptocurrency</p>
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Price per Unit ($)</label>
                                <input type="number" name="price_per_unit" step="0.01" min="0" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Payment Method</label>
                                <select name="payment_method" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" required>
                                    <option value="">Select Payment Method</option>
                                    <option value="bank_transfer">Bank Transfer</option>
                                    <option value="paypal">PayPal</option>
                                    <option value="skrill">Skrill</option>
                                    <option value="wise">Wise</option>
                                    <option value="cash_deposit">Cash Deposit</option>
                                    <option value="crypto">Cryptocurrency</option>
                                </select>
                            </div>

                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Payment Details</label>
                                <textarea name="payment_details" rows="3" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-transparent" placeholder="Enter your payment details (account number, email, etc.)" required></textarea>
                            </div>

                            <div class="bg-gray-50 p-4 rounded-lg">
                                <div class="text-sm text-gray-600">
                                    <div class="flex justify-between mb-1">
                                        <span>Total Value:</span>
                                        <span id="totalValue">$0.00</span>
                                    </div>
                                    <div class="flex justify-between mb-1">
                                        <span>Trading Fee:</span>
                                        <span id="tradingFee">$0.00</span>
                                    </div>
                                    <div class="flex justify-between font-semibold text-gray-800">
                                        <span>You'll Receive:</span>
                                        <span id="youReceive">$0.00</span>
                                    </div>
                                </div>
                            </div>

                            <button type="submit" class="w-full bg-red-500 hover:bg-red-600 text-white py-3 px-4 rounded-lg font-semibold transition-colors duration-200">
                                <i class="fas fa-plus-circle mr-2"></i>Create Sell Order
                            </button>
                        </form>
                        <?php else: ?>
                        <div class="text-center py-8">
                            <i class="fas fa-id-card text-4xl text-gray-300 mb-4"></i>
                            <h3 class="text-lg font-semibold text-gray-600 mb-2">KYC Verification Required</h3>
                            <p class="text-gray-500 mb-4">Complete your KYC verification to start trading</p>
                            <a href="kyc.php" class="bg-blue-500 hover:bg-blue-600 text-white px-6 py-2 rounded-lg font-medium transition-colors duration-200">
                                Verify Now
                            </a>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Live Prices Widget -->
                <div class="bg-white rounded-xl shadow-xl overflow-hidden">
                    <div class="bg-gradient-to-r from-green-50 to-green-100 px-6 py-4 border-b">
                        <h2 class="text-xl font-bold text-gray-800">
                            <i class="fas fa-chart-line text-green-600 mr-2"></i>Live Prices
                        </h2>
                    </div>
                    <div class="p-6">
                        <div class="space-y-3">
                            <?php foreach ($cryptocurrencies as $crypto): ?>
                            <div class="flex items-center justify-between p-3 bg-gray-50 rounded-lg">
                                <div class="flex items-center">
                                    <div class="w-8 h-8 bg-gradient-to-r from-blue-500 to-purple-600 rounded-full flex items-center justify-center text-white font-bold text-sm mr-3">
                                        <?php echo substr($crypto['symbol'], 0, 1); ?>
                                    </div>
                                    <div>
                                        <div class="font-bold text-gray-800"><?php echo $crypto['symbol']; ?></div>
                                        <div class="text-xs text-gray-500"><?php echo $crypto['name']; ?></div>
                                    </div>
                                </div>
                                <div class="text-right">
                                    <div class="font-bold text-green-600" id="price-<?php echo $crypto['symbol']; ?>">
                                        $<?php echo number_format($crypto['current_price'], 8); ?>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- User's Trades -->
        <?php if (!empty($userTrades)): ?>
        <div class="mt-8">
            <div class="bg-white rounded-xl shadow-xl overflow-hidden">
                <div class="bg-gradient-to-r from-gray-50 to-gray-100 px-6 py-4 border-b">
                    <h2 class="text-xl font-bold text-gray-800">
                        <i class="fas fa-history text-blue-600 mr-2"></i>My Trades
                    </h2>
                </div>
                <div class="p-6">
                    <div class="overflow-x-auto">
                        <table class="w-full">
                            <thead>
                                <tr class="border-b-2 border-gray-200">
                                    <th class="text-left py-3 px-4 font-semibold text-gray-700">Trade ID</th>
                                    <th class="text-left py-3 px-4 font-semibold text-gray-700">Type</th>
                                    <th class="text-left py-3 px-4 font-semibold text-gray-700">Asset</th>
                                    <th class="text-right py-3 px-4 font-semibold text-gray-700">Amount</th>
                                    <th class="text-right py-3 px-4 font-semibold text-gray-700">Price</th>
                                    <th class="text-center py-3 px-4 font-semibold text-gray-700">Status</th>
                                    <th class="text-left py-3 px-4 font-semibold text-gray-700">Created</th>
                                    <th class="text-center py-3 px-4 font-semibold text-gray-700">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($userTrades as $trade): ?>
                                <tr class="border-b border-gray-100 hover:bg-gray-50 transition-colors duration-200">
                                    <td class="py-4 px-4 font-mono text-blue-600">#<?php echo $trade['id']; ?></td>
                                    <td class="py-4 px-4">
                                        <span class="px-3 py-1 rounded-full text-xs font-medium <?php echo $trade['seller_id'] == $_SESSION['user_id'] ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'; ?>">
                                            <?php echo $trade['seller_id'] == $_SESSION['user_id'] ? 'SELL' : 'BUY'; ?>
                                        </span>
                                    </td>
                                    <td class="py-4 px-4 font-medium text-gray-800"><?php echo $trade['symbol']; ?></td>
                                    <td class="py-4 px-4 text-right font-mono text-gray-800"><?php echo number_format($trade['amount'], 8); ?></td>
                                    <td class="py-4 px-4 text-right font-bold text-green-600">$<?php echo number_format($trade['price_per_unit'], 2); ?></td>
                                    <td class="py-4 px-4 text-center">
                                        <?php
                                        $statusClasses = [
                                            'open' => 'bg-blue-100 text-blue-800',
                                            'matched' => 'bg-purple-100 text-purple-800',
                                            'in_escrow' => 'bg-yellow-100 text-yellow-800',
                                            'payment_pending' => 'bg-orange-100 text-orange-800',
                                            'completed' => 'bg-green-100 text-green-800',
                                            'cancelled' => 'bg-gray-100 text-gray-800',
                                            'disputed' => 'bg-red-100 text-red-800'
                                        ];
                                        ?>
                                        <span class="px-3 py-1 rounded-full text-xs font-medium <?php echo $statusClasses[$trade['status']] ?? 'bg-gray-100 text-gray-800'; ?>">
                                            <?php echo strtoupper(str_replace('_', ' ', $trade['status'])); ?>
                                        </span>
                                    </td>
                                    <td class="py-4 px-4 text-sm text-gray-600"><?php echo date('M j, H:i', strtotime($trade['created_at'])); ?></td>
                                    <td class="py-4 px-4 text-center">
                                        <a href="trade-details.php?id=<?php echo $trade['id']; ?>" class="bg-blue-500 hover:bg-blue-600 text-white px-3 py-1 rounded text-sm font-medium transition-colors duration-200">
                                            <i class="fas fa-eye mr-1"></i>View
                                        </a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>
    </div>
</main>

<script>
// Calculate total value and fees
function calculateTotals() {
    const amount = parseFloat(document.querySelector('input[name="amount"]').value) || 0;
    const price = parseFloat(document.querySelector('input[name="price_per_unit"]').value) || 0;
    const total = amount * price;
    const fee = total * 0.0025; // 0.25% fee
    const youReceive = total - fee;
    
    document.getElementById('totalValue').textContent = '$' + total.toFixed(2);
    document.getElementById('tradingFee').textContent = '$' + fee.toFixed(2);
    document.getElementById('youReceive').textContent = '$' + youReceive.toFixed(2);
}

// Add event listeners for calculation
document.querySelector('input[name="amount"]')?.addEventListener('input', calculateTotals);
document.querySelector('input[name="price_per_unit"]')?.addEventListener('input', calculateTotals);

// Handle sell order form submission
document.getElementById('sellOrderForm')?.addEventListener('submit', async function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    formData.append('action', 'create_sell_order');
    
    try {
        const response = await fetch('api/trading.php', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert('Sell order created successfully!');
            location.reload();
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('Error creating sell order');
    }
});

// Buy trade function
async function buyTrade(tradeId) {
    if (!confirm('Are you sure you want to buy this cryptocurrency?')) {
        return;
    }
    
    const formData = new FormData();
    formData.append('action', 'create_buy_order');
    formData.append('trade_id', tradeId);
    
    try {
        const response = await fetch('api/trading.php', {
            method: 'POST',
            body: formData
        });
        
        const result = await response.json();
        
        if (result.success) {
            alert('Buy order created successfully! Redirecting to trade details...');
            window.location.href = 'trade-details.php?id=' + tradeId;
        } else {
            alert('Error: ' + result.message);
        }
    } catch (error) {
        alert('Error creating buy order');
    }
}

// Refresh trades
function refreshTrades() {
    location.reload();
}

// Filter trades by cryptocurrency
document.getElementById('cryptoFilter')?.addEventListener('change', function() {
    const cryptoId = this.value;
    const url = new URL(window.location);
    if (cryptoId) {
        url.searchParams.set('crypto', cryptoId);
    } else {
        url.searchParams.delete('crypto');
    }
    window.location.href = url.toString();
});

// Auto-refresh trades every 30 seconds
setInterval(() => {
    if (document.getElementById('tradesTable')) {
        refreshTrades();
    }
}, 30000);
</script>

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