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

Security::requireAuth();

$pageTitle = 'KYC Verification - CryptoExchange Pro | Identity Verification';
$pageDescription = 'Complete your KYC verification to unlock higher trading limits and enhanced security features on our cryptocurrency exchange platform.';

$kyc = new KYC();
$userDocuments = $kyc->getUserDocuments($_SESSION['user_id']);

// Get user info
$db = new Database();
$db->query("SELECT * FROM users WHERE id = :user_id");
$db->bind(':user_id', $_SESSION['user_id']);
$user = $db->single();

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

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!Security::validateCSRFToken($_POST['csrf_token'])) {
        $message = 'Invalid security token. Please try again.';
        $messageType = 'error';
    } else {
        $result = $kyc->submitDocument(
            $_SESSION['user_id'],
            $_POST['document_type'],
            $_POST['document_number'],
            $_FILES['document_file']
        );
        
        $message = $result['message'];
        $messageType = $result['success'] ? 'success' : 'error';
        
        if ($result['success']) {
            // Refresh documents
            $userDocuments = $kyc->getUserDocuments($_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">
            <h1 class="text-4xl font-bold text-gray-800 mb-2">
                <i class="fas fa-id-card text-blue-600 mr-3"></i>KYC Verification
            </h1>
            <p class="text-gray-600">Complete your identity verification to unlock higher trading limits</p>
        </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">
            <!-- KYC Status -->
            <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-user-check text-green-600 mr-2"></i>Verification Status
                        </h2>
                    </div>
                    <div class="p-6">
                        <div class="text-center mb-6">
                            <?php
                            $statusColors = [
                                'pending' => 'text-yellow-600 bg-yellow-100',
                                'verified' => 'text-green-600 bg-green-100',
                                'rejected' => 'text-red-600 bg-red-100'
                            ];
                            $statusIcons = [
                                'pending' => 'fa-clock',
                                'verified' => 'fa-check-circle',
                                'rejected' => 'fa-times-circle'
                            ];
                            ?>
                            <div class="w-20 h-20 mx-auto mb-4 rounded-full flex items-center justify-center <?php echo $statusColors[$user['kyc_status']]; ?>">
                                <i class="fas <?php echo $statusIcons[$user['kyc_status']]; ?> text-3xl"></i>
                            </div>
                            <h3 class="text-xl font-bold text-gray-800 mb-2">
                                <?php echo strtoupper($user['kyc_status']); ?>
                            </h3>
                            <p class="text-gray-600">KYC Level: <?php echo $user['kyc_level']; ?></p>
                        </div>

                        <!-- Trading Limits -->
                        <div class="bg-gray-50 rounded-lg p-4">
                            <h4 class="font-semibold text-gray-800 mb-3">Trading Limits</h4>
                            <div class="space-y-2 text-sm">
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Level 0:</span>
                                    <span class="font-medium">$0/day</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Level 1:</span>
                                    <span class="font-medium <?php echo $user['kyc_level'] >= 1 ? 'text-green-600' : 'text-gray-400'; ?>">$1,000/day</span>
                                </div>
                                <div class="flex justify-between">
                                    <span class="text-gray-600">Level 2:</span>
                                    <span class="font-medium <?php echo $user['kyc_level'] >= 2 ? 'text-green-600' : 'text-gray-400'; ?>">$10,000/day</span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Required Documents -->
                <div class="bg-white rounded-xl shadow-xl overflow-hidden">
                    <div class="bg-gradient-to-r from-blue-50 to-blue-100 px-6 py-4 border-b">
                        <h2 class="text-xl font-bold text-gray-800">
                            <i class="fas fa-file-alt text-blue-600 mr-2"></i>Required Documents
                        </h2>
                    </div>
                    <div class="p-6">
                        <div class="space-y-4">
                            <div class="border-l-4 border-blue-500 pl-4">
                                <h4 class="font-semibold text-gray-800">Level 1 - Identity</h4>
                                <p class="text-sm text-gray-600">One of the following:</p>
                                <ul class="text-sm text-gray-600 mt-1 space-y-1">
                                    <li>• Passport</li>
                                    <li>• Driver's License</li>
                                    <li>• National ID Card</li>
                                </ul>
                            </div>
                            <div class="border-l-4 border-green-500 pl-4">
                                <h4 class="font-semibold text-gray-800">Level 2 - Address</h4>
                                <p class="text-sm text-gray-600">One of the following:</p>
                                <ul class="text-sm text-gray-600 mt-1 space-y-1">
                                    <li>• Utility Bill</li>
                                    <li>• Bank Statement</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Document Upload & Management -->
            <div class="lg:col-span-2">
                <!-- Upload Form -->
                <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-upload text-blue-600 mr-2"></i>Upload Document
                        </h2>
                    </div>
                    <div class="p-6">
                        <form method="POST" enctype="multipart/form-data" class="space-y-6">
                            <input type="hidden" name="csrf_token" value="<?php echo Security::generateCSRFToken(); ?>">
                            
                            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Document Type</label>
                                    <select name="document_type" 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 Document Type</option>
                                        <option value="passport">Passport</option>
                                        <option value="driver_license">Driver's License</option>
                                        <option value="national_id">National ID Card</option>
                                        <option value="utility_bill">Utility Bill</option>
                                        <option value="bank_statement">Bank Statement</option>
                                    </select>
                                </div>
                                
                                <div>
                                    <label class="block text-sm font-medium text-gray-700 mb-2">Document Number</label>
                                    <input type="text" name="document_number" 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 document number">
                                </div>
                            </div>
                            
                            <div>
                                <label class="block text-sm font-medium text-gray-700 mb-2">Document File</label>
                                <div class="border-2 border-dashed border-gray-300 rounded-lg p-6 text-center hover:border-blue-400 transition-colors duration-200">
                                    <input type="file" name="document_file" accept=".jpg,.jpeg,.png,.pdf" class="hidden" id="fileInput" required>
                                    <label for="fileInput" class="cursor-pointer">
                                        <i class="fas fa-cloud-upload-alt text-4xl text-gray-400 mb-4"></i>
                                        <p class="text-gray-600 mb-2">Click to upload or drag and drop</p>
                                        <p class="text-sm text-gray-500">JPG, PNG, or PDF (max 5MB)</p>
                                    </label>
                                </div>
                            </div>
                            
                            <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-info-circle text-yellow-600"></i>
                                    </div>
                                    <div class="ml-3">
                                        <h4 class="text-sm font-medium text-yellow-800">Important Guidelines</h4>
                                        <ul class="mt-2 text-sm text-yellow-700 space-y-1">
                                            <li>• Ensure document is clear and readable</li>
                                            <li>• All corners of the document must be visible</li>
                                            <li>• Document must be valid and not expired</li>
                                            <li>• File size should not exceed 5MB</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>
                            
                            <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-upload mr-2"></i>Upload Document
                            </button>
                        </form>
                    </div>
                </div>

                <!-- Submitted Documents -->
                <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-file-check text-green-600 mr-2"></i>Submitted Documents
                        </h2>
                    </div>
                    <div class="p-6">
                        <?php if (!empty($userDocuments)): ?>
                        <div class="space-y-4">
                            <?php foreach ($userDocuments as $doc): ?>
                            <div class="border border-gray-200 rounded-lg p-4">
                                <div class="flex items-center justify-between mb-3">
                                    <div>
                                        <h4 class="font-semibold text-gray-800">
                                            <?php echo ucwords(str_replace('_', ' ', $doc['document_type'])); ?>
                                        </h4>
                                        <?php if ($doc['document_number']): ?>
                                        <p class="text-sm text-gray-600">Number: <?php echo $doc['document_number']; ?></p>
                                        <?php endif; ?>
                                    </div>
                                    <div class="text-right">
                                        <?php
                                        $docStatusColors = [
                                            'pending' => 'bg-yellow-100 text-yellow-800',
                                            'approved' => 'bg-green-100 text-green-800',
                                            'rejected' => 'bg-red-100 text-red-800'
                                        ];
                                        ?>
                                        <span class="px-3 py-1 rounded-full text-xs font-medium <?php echo $docStatusColors[$doc['status']]; ?>">
                                            <?php echo strtoupper($doc['status']); ?>
                                        </span>
                                    </div>
                                </div>
                                
                                <div class="flex items-center justify-between text-sm text-gray-600">
                                    <span>Submitted: <?php echo date('M j, Y H:i', strtotime($doc['submitted_at'])); ?></span>
                                    <?php if ($doc['reviewed_at']): ?>
                                    <span>Reviewed: <?php echo date('M j, Y H:i', strtotime($doc['reviewed_at'])); ?></span>
                                    <?php endif; ?>
                                </div>
                                
                                <?php if ($doc['rejection_reason']): ?>
                                <div class="mt-3 p-3 bg-red-50 border border-red-200 rounded-lg">
                                    <p class="text-sm text-red-700">
                                        <strong>Rejection Reason:</strong> <?php echo $doc['rejection_reason']; ?>
                                    </p>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php else: ?>
                        <div class="text-center py-12">
                            <i class="fas fa-file-upload text-6xl text-gray-300 mb-4"></i>
                            <h3 class="text-xl font-semibold text-gray-600 mb-2">No documents submitted</h3>
                            <p class="text-gray-500">Upload your first document to start the verification process</p>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
</main>

<script>
// File upload preview
document.getElementById('fileInput').addEventListener('change', function(e) {
    const file = e.target.files[0];
    if (file) {
        const label = document.querySelector('label[for="fileInput"]');
        label.innerHTML = `
            <i class="fas fa-file text-4xl text-blue-500 mb-4"></i>
            <p class="text-blue-600 mb-2">${file.name}</p>
            <p class="text-sm text-gray-500">Click to change file</p>
        `;
    }
});
</script>

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