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

Security::requireAuth();

$tradeId = $_GET['id'] ?? null;
if (!$tradeId) {
    header('Location: trading.php');
    exit;
}

$trading = new Trading();
$trade = $trading->getTradeById($tradeId);

if (!$trade) {
    header('Location: trading.php');
    exit;
}

// Check if user is involved in this trade
if ($trade['seller_id'] != $_SESSION['user_id'] && $trade['buyer_id'] != $_SESSION['user_id']) {
    header('Location: trading.php');
    exit;
}

$pageTitle = 'Trade Details #' . $tradeId . ' - CryptoExchange Pro';
$pageDescription = 'View and manage your cryptocurrency trade with secure escrow protection and real-time status updates.';

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

// Handle trade actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!Security::validateCSRFToken($_POST['csrf_token'])) {
        $message = 'Invalid security token. Please try again.';
        $messageType = 'error';
    } else {
        $action = $_POST['action'];
        
        switch ($action) {
            case 'mark_payment_sent':
                $result = $trading->markPaymentSent($tradeId, $_SESSION['user_id']);
                break;
            case 'confirm_payment':
                $result = $trading->confirmPaymentReceived($tradeId, $_SESSION['user_id']);
                break;
            case 'cancel_trade':
                $result = $trading->cancelTrade($tradeId, $_SESSION['user_id'], $_POST['reason'] ?? 'User cancelled');
                break;
            default:
                $result = ['success' => false, 'message' => 'Invalid action'];
        }
        
        $message = $result['message'];
        $messageType = $result['success'] ? 'success' : 'error';
        
        if ($result['success']) {
            // Refresh trade data
            $trade = $trading->getTradeById($tradeId);
        }
    }
}

$isSeller = $trade['seller_id'] == $_SESSION['user_id'];
$isBuyer = $trade['buyer_id'] == $_SESSION['user_id'];

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">
            <div class="flex items-center justify-between">
                <div>
                    <h1 class="text-4xl font-bold text-gray-800 mb-2">
                        <i class="fas fa-exchange-alt text-blue-600 mr-3"></i>Trade Details
                    </h1>
                    <p class="text-gray-600">Trade ID: #<?php echo $tradeId; ?></p>
                </div>
                <a href="trading.php" class="bg-gray-500 hover:bg-gray-600 text-white px-6 py-3 rounded-lg font-semibold transition-colors duration-200">
                    <i class="fas fa-arrow-left mr-2"></i>Back to Trading
                </a>
            </div>
        </div>

        <!-- Alert Messages -->
        <?php if ($message): ?>
        <div class="mb-6 p-4 rounded-lg <?php echo $messageType === 'success' ? 'bg-green-100 border border-green-400 text-green-700' : 'bg-red-100 border border-red-400 text-red-700'; ?>">
            <div class="flex">
                <div class="flex-shrink-0">
                    <i class="fas <?php echo $messageType === 'success' ? 'fa-check-circle' : 'fa-exclamation-triangle'; ?> text-xl"></i>
                </div>
                <div class="ml-3">
                    <p class="text-sm font-medium"><?php echo $message; ?></p>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
            <!-- Trade Information -->
            <div class="lg:col-span-2">
                <div class="bg-white rounded-xl shadow-xl overflow-hidden mb-8">
                    <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-info-circle text-blue-600 mr-2"></i>Trade Information
                        </h2>
                    </div>
                    <div class="p-6">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-500">Cryptocurrency</label>
                                    <div class="flex items-center mt-1">
                                        <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['symbol'], 0, 1); ?>
                                        </div>
                                        <div>
                                            <div class="font-bold text-gray-800"><?php echo $trade['symbol']; ?></div>
                                            <div class="text-sm text-gray-500"><?php echo $trade['name']; ?></div>
                                        </div>
                                    </div>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-500">Amount</label>
                                    <p class="text-lg font-bold text-gray-800"><?php echo number_format($trade['amount'], 8); ?> <?php echo $trade['symbol']; ?></p>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-500">Price per Unit</label>
                                    <p class="text-lg font-bold text-green-600">$<?php echo number_format($trade['price_per_unit'], 2); ?></p>
                                </div>
                            </div>
                            
                            <div class="space-y-4">
                                <div>
                                    <label class="block text-sm font-medium text-gray-500">Total Amount</label>
                                    <p class="text-lg font-bold text-blue-600">$<?php echo number_format($trade['total_amount'], 2); ?></p>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-500">Trading Fee</label>
                                    <p class="text-lg font-bold text-yellow-600">$<?php echo number_format($trade['trading_fee'], 2); ?></p>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-500">Status</label>
                                    <?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="inline-block px-4 py-2 rounded-full text-sm font-medium <?php echo $statusClasses[$trade['status']] ?? 'bg-gray-100 text-gray-800'; ?>">
                                        <?php echo strtoupper(str_replace('_', ' ', $trade['status'])); ?>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Payment Information -->
                <div class="bg-white rounded-xl shadow-xl overflow-hidden mb-8">
                    <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-credit-card text-green-600 mr-2"></i>Payment Information
                        </h2>
                    </div>
                    <div class="p-6">
                        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                            <div>
                                <label class="block text-sm font-medium text-gray-500">Payment Method</label>
                                <p class="text-lg font-bold text-gray-800 capitalize"><?php echo str_replace('_', ' ', $trade['payment_method']); ?></p>
                            </div>
                            <div>
                                <label class="block text-sm font-medium text-gray-500">Payment Details</label>
                                <div class="bg-gray-50 p-3 rounded-lg mt-1">
                                    <p class="text-sm text-gray-700 whitespace-pre-wrap"><?php echo $trade['payment_details']; ?></p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Trade Timeline -->
                <div class="bg-white rounded-xl shadow-xl overflow-hidden">
                    <div class="bg-gradient-to-r from-purple-50 to-purple-100 px-6 py-4 border-b">
                        <h2 class="text-xl font-bold text-gray-800">
                            <i class="fas fa-history text-purple-600 mr-2"></i>Trade Timeline
                        </h2>
                    </div>
                    <div class="p-6">
                        <div class="space-y-4">
                            <div class="flex items-center">
                                <div class="w-4 h-4 bg-green-500 rounded-full mr-4"></div>
                                <div>
                                    <p class="font-medium text-gray-800">Trade Created</p>
                                    <p class="text-sm text-gray-600"><?php echo date('M j, Y H:i:s', strtotime($trade['created_at'])); ?></p>
                                </div>
                            </div>
                            
                            <?php if ($trade['buyer_id']): ?>
                            <div class="flex items-center">
                                <div class="w-4 h-4 bg-green-500 rounded-full mr-4"></div>
                                <div>
                                    <p class="font-medium text-gray-800">Trade Matched</p>
                                    <p class="text-sm text-gray-600">Buyer: <?php echo $trade['buyer_username']; ?></p>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (in_array($trade['status'], ['in_escrow', 'payment_pending', 'completed'])): ?>
                            <div class="flex items-center">
                                <div class="w-4 h-4 bg-green-500 rounded-full mr-4"></div>
                                <div>
                                    <p class="font-medium text-gray-800">Funds Locked in Escrow</p>
                                    <p class="text-sm text-gray-600">Escrow Address: <?php echo $trade['escrow_address']; ?></p>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (in_array($trade['status'], ['payment_pending', 'completed'])): ?>
                            <div class="flex items-center">
                                <div class="w-4 h-4 bg-green-500 rounded-full mr-4"></div>
                                <div>
                                    <p class="font-medium text-gray-800">Payment Sent</p>
                                    <p class="text-sm text-gray-600">Buyer marked payment as sent</p>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if ($trade['status'] === 'completed'): ?>
                            <div class="flex items-center">
                                <div class="w-4 h-4 bg-green-500 rounded-full mr-4"></div>
                                <div>
                                    <p class="font-medium text-gray-800">Trade Completed</p>
                                    <p class="text-sm text-gray-600"><?php echo date('M j, Y H:i:s', strtotime($trade['completed_at'])); ?></p>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if ($trade['status'] === 'cancelled'): ?>
                            <div class="flex items-center">
                                <div class="w-4 h-4 bg-red-500 rounded-full mr-4"></div>
                                <div>
                                    <p class="font-medium text-gray-800">Trade Cancelled</p>
                                    <p class="text-sm text-gray-600">Trade was cancelled</p>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Actions Panel -->
            <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-gray-50 to-gray-100 px-6 py-4 border-b">
                        <h2 class="text-xl font-bold text-gray-800">
                            <i class="fas fa-cogs text-blue-600 mr-2"></i>Actions
                        </h2>
                    </div>
                    <div class="p-6">
                        <?php if ($trade['status'] === 'in_escrow' && $isBuyer): ?>
                        <div class="mb-6">
                            <h3 class="font-semibold text-gray-800 mb-3">Step 1: Send Payment</h3>
                            <p class="text-sm text-gray-600 mb-4">Send payment using the details provided by the seller. Once sent, mark payment as sent below.</p>
                            <form method="POST">
                                <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
                                <input type="hidden" name="action" value="mark_payment_sent">
                                <button type="submit" class="w-full bg-blue-500 hover:bg-blue-600 text-white py-3 px-4 rounded-lg font-semibold transition-colors duration-200">
                                    <i class="fas fa-paper-plane mr-2"></i>Mark Payment as Sent
                                </button>
                            </form>
                        </div>
                        <?php endif; ?>

                        <?php if ($trade['status'] === 'payment_pending' && $isSeller): ?>
                        <div class="mb-6">
                            <h3 class="font-semibold text-gray-800 mb-3">Step 2: Confirm Payment</h3>
                            <p class="text-sm text-gray-600 mb-4">Check your payment method and confirm that you have received the payment from the buyer.</p>
                            <form method="POST">
                                <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
                                <input type="hidden" name="action" value="confirm_payment">
                                <button type="submit" class="w-full bg-green-500 hover:bg-green-600 text-white py-3 px-4 rounded-lg font-semibold transition-colors duration-200">
                                    <i class="fas fa-check-circle mr-2"></i>Confirm Payment Received
                                </button>
                            </form>
                        </div>
                        <?php endif; ?>

                        <?php if ($trade['status'] === 'payment_pending' && $isBuyer): ?>
                        <div class="mb-6">
                            <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4">
                                <div class="flex">
                                    <div class="flex-shrink-0">
                                        <i class="fas fa-clock text-yellow-600"></i>
                                    </div>
                                    <div class="ml-3">
                                        <h4 class="text-sm font-medium text-yellow-800">Waiting for Seller</h4>
                                        <p class="text-sm text-yellow-700 mt-1">The seller needs to confirm that they have received your payment.</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if ($trade['status'] === 'completed'): ?>
                        <div class="mb-6">
                            <div class="bg-green-50 border border-green-200 rounded-lg p-4">
                                <div class="flex">
                                    <div class="flex-shrink-0">
                                        <i class="fas fa-check-circle text-green-600"></i>
                                    </div>
                                    <div class="ml-3">
                                        <h4 class="text-sm font-medium text-green-800">Trade Completed</h4>
                                        <p class="text-sm text-green-700 mt-1">This trade has been successfully completed. The cryptocurrency has been transferred.</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <?php endif; ?>

                        <?php if (!in_array($trade['status'], ['completed', 'cancelled'])): ?>
                        <div class="border-t pt-6">
                            <h3 class="font-semibold text-gray-800 mb-3">Cancel Trade</h3>
                            <form method="POST" onsubmit="return confirm('Are you sure you want to cancel this trade?')">
                                <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
                                <input type="hidden" name="action" value="cancel_trade">
                                <div class="mb-3">
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Reason (Optional)</label>
                                    <textarea name="reason" rows="2" class="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-red-500 focus:border-transparent text-sm" placeholder="Enter cancellation reason..."></textarea>
                                </div>
                                <button type="submit" class="w-full bg-red-500 hover:bg-red-600 text-white py-2 px-4 rounded-lg font-medium transition-colors duration-200">
                                    <i class="fas fa-times mr-2"></i>Cancel Trade
                                </button>
                            </form>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Trade Participants -->
                <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-users text-blue-600 mr-2"></i>Participants
                        </h2>
                    </div>
                    <div class="p-6">
                        <div class="space-y-4">
                            <div class="flex items-center justify-between p-3 bg-red-50 rounded-lg">
                                <div class="flex items-center">
                                    <div class="w-10 h-10 bg-gradient-to-r from-red-500 to-red-600 rounded-full flex items-center justify-center text-white font-bold mr-3">
                                        <?php echo substr($trade['seller_username'], 0, 1); ?>
                                    </div>
                                    <div>
                                        <div class="font-bold text-gray-800"><?php echo $trade['seller_username']; ?></div>
                                        <div class="text-sm text-gray-500">Seller</div>
                                    </div>
                                </div>
                                <?php if ($isSeller): ?>
                                <span class="px-3 py-1 bg-red-100 text-red-800 rounded-full text-xs font-medium">You</span>
                                <?php endif; ?>
                            </div>
                            
                            <?php if ($trade['buyer_username']): ?>
                            <div class="flex items-center justify-between p-3 bg-green-50 rounded-lg">
                                <div class="flex items-center">
                                    <div class="w-10 h-10 bg-gradient-to-r from-green-500 to-green-600 rounded-full flex items-center justify-center text-white font-bold mr-3">
                                        <?php echo substr($trade['buyer_username'], 0, 1); ?>
                                    </div>
                                    <div>
                                        <div class="font-bold text-gray-800"><?php echo $trade['buyer_username']; ?></div>
                                        <div class="text-sm text-gray-500">Buyer</div>
                                    </div>
                                </div>
                                <?php if ($isBuyer): ?>
                                <span class="px-3 py-1 bg-green-100 text-green-800 rounded-full text-xs font-medium">You</span>
                                <?php endif; ?>
                            </div>
                            <?php else: ?>
                            <div class="p-3 bg-gray-50 rounded-lg text-center">
                                <p class="text-gray-500 text-sm">Waiting for buyer...</p>
                            </div>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

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