<?php
/**
 * ============================================================================
 * buyer/verification.php
 * Buyer Verification Submission Page
 * For wholesalers, processors, and exporters to submit verification documents
 * ============================================================================
 */

require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/BuyerSystem.php';

// Check login
if (!isLoggedIn()) {
    header('Location: ' . APP_URL . '/auth/login.php');
    exit();
}

// Check user type
if (getUserType() !== 'buyer') {
    header('Location: ' . APP_URL . '/dashboard/');
    exit();
}

// Initialize
use App\Database;
$database = Database::getInstance();
$db = $database->getConnection();
$currentUserId = getUserId();
$currentUserName = getUserName();
$buyerSystem = new BuyerSystem($database, $currentUserId);

// Check if profile is complete
if (!$buyerSystem->hasCompleteProfile()) {
    header('Location: ' . APP_URL . '/buyer/complete-profile.php');
    exit();
}

// Get buyer profile
$profile = $buyerSystem->getProfile();
$buyerType = $buyerSystem->getBuyerType();

// Check if this buyer type requires verification
$requiresVerification = in_array($buyerType, ['wholesaler', 'processor', 'exporter']);

if (!$requiresVerification) {
    // This buyer type doesn't need verification
    header('Location: ' . APP_URL . '/buyer/dashboard.php');
    exit();
}

// If already verified, redirect to dashboard
if ($buyerSystem->isVerified()) {
    header('Location: ' . APP_URL . '/buyer/dashboard.php');
    exit();
}

// Check for existing verification request
$sql = "SELECT * FROM user_approvals WHERE user_id = ? AND user_type = 'buyer' ORDER BY created_at DESC LIMIT 1";
$stmt = $db->prepare($sql);
$stmt->execute([$currentUserId]);
$existingVerification = $stmt->fetch(PDO::FETCH_ASSOC);

// If verification is pending, redirect to pending page
if ($existingVerification && $existingVerification['approval_status'] === 'pending') {
    header('Location: ' . APP_URL . '/buyer/verification-pending.php');
    exit();
}

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        $db->beginTransaction();
        
        // Validate required fields based on buyer type
        $errors = [];
        
        // Business registration is required for all premium buyer types
        if (empty($_POST['business_registration']) && empty($profile['business_registration'])) {
            $errors[] = 'Business registration number is required';
        }
        
        // Tax ID validation
        if (empty($_POST['tax_id']) && empty($profile['tax_id'])) {
            $errors[] = 'Tax Identification Number (TIN) is required for verification';
        }
        
        // Define upload directory - using the standard assets/uploads structure
        $uploadBaseDir = __DIR__ . '/../assets/uploads/';
        $uploadDir = $uploadBaseDir . 'verification/';
        
        // Create directories if they don't exist
        if (!file_exists($uploadBaseDir)) {
            mkdir($uploadBaseDir, 0755, true);
        }
        if (!file_exists($uploadDir)) {
            mkdir($uploadDir, 0755, true);
        }
        
        // Check for uploaded documents
        $uploadedDocs = [];
        
        // Allowed file types
        $allowedTypes = ['pdf', 'jpg', 'jpeg', 'png'];
        $maxFileSize = 5 * 1024 * 1024; // 5MB
        
        // Handle business registration certificate
        if (isset($_FILES['business_cert']) && $_FILES['business_cert']['error'] === UPLOAD_ERR_OK) {
            $fileInfo = pathinfo($_FILES['business_cert']['name']);
            $extension = strtolower($fileInfo['extension']);
            
            if (!in_array($extension, $allowedTypes)) {
                $errors[] = 'Business certificate must be PDF or image file (JPG, PNG)';
            } elseif ($_FILES['business_cert']['size'] > $maxFileSize) {
                $errors[] = 'Business certificate file size must be less than 5MB';
            } else {
                $fileName = 'business_cert_' . $currentUserId . '_' . time() . '.' . $extension;
                $filePath = $uploadDir . $fileName;
                
                if (move_uploaded_file($_FILES['business_cert']['tmp_name'], $filePath)) {
                    $uploadedDocs['business_certificate'] = 'assets/uploads/verification/' . $fileName;
                } else {
                    $errors[] = 'Failed to upload business certificate';
                }
            }
        } else {
            $errors[] = 'Business registration certificate is required';
        }
        
        // Handle tax certificate
        if (isset($_FILES['tax_cert']) && $_FILES['tax_cert']['error'] === UPLOAD_ERR_OK) {
            $fileInfo = pathinfo($_FILES['tax_cert']['name']);
            $extension = strtolower($fileInfo['extension']);
            
            if (!in_array($extension, $allowedTypes)) {
                $errors[] = 'Tax certificate must be PDF or image file (JPG, PNG)';
            } elseif ($_FILES['tax_cert']['size'] > $maxFileSize) {
                $errors[] = 'Tax certificate file size must be less than 5MB';
            } else {
                $fileName = 'tax_cert_' . $currentUserId . '_' . time() . '.' . $extension;
                $filePath = $uploadDir . $fileName;
                
                if (move_uploaded_file($_FILES['tax_cert']['tmp_name'], $filePath)) {
                    $uploadedDocs['tax_certificate'] = 'assets/uploads/verification/' . $fileName;
                } else {
                    $errors[] = 'Failed to upload tax certificate';
                }
            }
        } else {
            $errors[] = 'Tax certificate is required';
        }
        
        // Handle trade license (required for exporters)
        if ($buyerType === 'exporter') {
            if (isset($_FILES['trade_license']) && $_FILES['trade_license']['error'] === UPLOAD_ERR_OK) {
                $fileInfo = pathinfo($_FILES['trade_license']['name']);
                $extension = strtolower($fileInfo['extension']);
                
                if (!in_array($extension, $allowedTypes)) {
                    $errors[] = 'Trade license must be PDF or image file (JPG, PNG)';
                } elseif ($_FILES['trade_license']['size'] > $maxFileSize) {
                    $errors[] = 'Trade license file size must be less than 5MB';
                } else {
                    $fileName = 'trade_license_' . $currentUserId . '_' . time() . '.' . $extension;
                    $filePath = $uploadDir . $fileName;
                    
                    if (move_uploaded_file($_FILES['trade_license']['tmp_name'], $filePath)) {
                        $uploadedDocs['trade_license'] = 'assets/uploads/verification/' . $fileName;
                    } else {
                        $errors[] = 'Failed to upload trade license';
                    }
                }
            } else {
                $errors[] = 'Trade license is required for exporters';
            }
        }
        
        // Handle additional documents (optional)
        if (isset($_FILES['additional_docs']) && $_FILES['additional_docs']['error'] === UPLOAD_ERR_OK) {
            $fileInfo = pathinfo($_FILES['additional_docs']['name']);
            $extension = strtolower($fileInfo['extension']);
            
            if (in_array($extension, $allowedTypes)) {
                if ($_FILES['additional_docs']['size'] <= $maxFileSize) {
                    $fileName = 'additional_' . $currentUserId . '_' . time() . '.' . $extension;
                    $filePath = $uploadDir . $fileName;
                    
                    if (move_uploaded_file($_FILES['additional_docs']['tmp_name'], $filePath)) {
                        $uploadedDocs['additional_documents'] = 'assets/uploads/verification/' . $fileName;
                    }
                }
            }
        }
        
        if (!empty($errors)) {
            throw new Exception(implode('<br>', $errors));
        }
        
        // Get business registration and tax ID from POST or existing profile
        $businessReg = !empty($_POST['business_registration']) ? trim($_POST['business_registration']) : $profile['business_registration'];
        $taxId = !empty($_POST['tax_id']) ? trim($_POST['tax_id']) : $profile['tax_id'];
        
        // Update buyer profile with business info if provided
        if (!empty($_POST['business_registration']) || !empty($_POST['tax_id'])) {
            $sql = "UPDATE buyer_profiles SET 
                        business_registration = ?,
                        tax_id = ?,
                        updated_at = NOW()
                    WHERE user_id = ?";
            $stmt = $db->prepare($sql);
            $stmt->execute([
                $businessReg,
                $taxId,
                $currentUserId
            ]);
        }
        
        // Create or update verification request in user_approvals
        if ($existingVerification) {
            // Update existing verification request
            $sql = "UPDATE user_approvals SET
                        approval_status = 'pending',
                        business_name = ?,
                        business_registration = ?,
                        tax_id = ?,
                        supporting_documents = ?,
                        rejection_reason = NULL,
                        updated_at = NOW()
                    WHERE id = ?";
            
            $stmt = $db->prepare($sql);
            $stmt->execute([
                $profile['business_name'],
                $businessReg,
                $taxId,
                json_encode($uploadedDocs),
                $existingVerification['id']
            ]);
        } else {
            // Create new verification request
            $sql = "INSERT INTO user_approvals (
                        user_id, user_type, approval_status,
                        business_name, business_registration, tax_id,
                        supporting_documents, created_at
                    ) VALUES (?, 'buyer', 'pending', ?, ?, ?, ?, NOW())";
            
            $stmt = $db->prepare($sql);
            $stmt->execute([
                $currentUserId,
                $profile['business_name'],
                $businessReg,
                $taxId,
                json_encode($uploadedDocs)
            ]);
        }
        
        // Update buyer profile timestamp
        $sql = "UPDATE buyer_profiles SET updated_at = NOW() WHERE user_id = ?";
        $stmt = $db->prepare($sql);
        $stmt->execute([$currentUserId]);
        
        // Create notification for admins
        $sql = "INSERT INTO notifications (user_id, title, message, type, icon, link)
                SELECT id, 'New Buyer Verification Request',
                       CONCAT('New verification request from ', ?, ' (', ?, ')'),
                       'warning', 'shield-check', '/admin/approvals.php'
                FROM users WHERE user_type = 'admin'";
        $stmt = $db->prepare($sql);
        $stmt->execute([$currentUserName, $buyerType]);
        
        $db->commit();
        
        // Set success message
        $_SESSION['flash_message'] = 'Verification documents submitted successfully! We will review your application within 1-2 business days.';
        $_SESSION['flash_type'] = 'success';
        
        // Redirect to verification pending page
        header('Location: ' . APP_URL . '/buyer/verification-pending.php');
        exit();
        
    } catch (Exception $e) {
        $db->rollBack();
        
        // Clean up uploaded files if transaction failed
        if (!empty($uploadedDocs)) {
            foreach ($uploadedDocs as $filePath) {
                $fullPath = __DIR__ . '/../' . $filePath;
                if (file_exists($fullPath)) {
                    unlink($fullPath);
                }
            }
        }
        
        $error = $e->getMessage();
    }
}

$pageTitle = 'Buyer Verification';
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $pageTitle; ?> - AIMS</title>
    
    <!-- Bootstrap 5.3 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Bootstrap Icons -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css" rel="stylesheet">
    
    <style>
        :root {
            --primary-color: #3b82f6;
            --primary-dark: #2563eb;
            --success-color: #10b981;
            --warning-color: #f59e0b;
        }
        
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        }
        
        .verification-container {
            max-width: 900px;
            margin: 40px auto;
            padding: 0 20px;
        }
        
        .verification-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0,0,0,0.3);
            overflow: hidden;
        }
        
        .verification-header {
            background: linear-gradient(135deg, var(--warning-color) 0%, #dc2626 100%);
            color: white;
            padding: 2rem;
            text-align: center;
        }
        
        .verification-header h2 {
            font-size: 1.8rem;
            font-weight: bold;
            margin-bottom: 0.5rem;
        }
        
        .verification-header .badge {
            font-size: 0.875rem;
            padding: 0.5rem 1rem;
            background: rgba(255,255,255,0.2);
        }
        
        .verification-body {
            padding: 2.5rem;
        }
        
        .info-banner {
            background: linear-gradient(135deg, #eff6ff 0%, #dbeafe 100%);
            border-left: 4px solid var(--primary-color);
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 2rem;
        }
        
        .info-banner i {
            color: var(--primary-color);
            font-size: 1.5rem;
        }
        
        .info-banner h5 {
            color: #1e40af;
            font-weight: 600;
            margin-bottom: 0.5rem;
        }
        
        .requirements-list {
            list-style: none;
            padding: 0;
        }
        
        .requirements-list li {
            padding: 0.75rem 0;
            border-bottom: 1px solid #e5e7eb;
            display: flex;
            align-items: flex-start;
            gap: 0.75rem;
        }
        
        .requirements-list li:last-child {
            border-bottom: none;
        }
        
        .requirements-list i {
            color: var(--success-color);
            font-size: 1.25rem;
            margin-top: 2px;
        }
        
        .section-title {
            font-size: 1.25rem;
            font-weight: bold;
            margin-bottom: 1.5rem;
            color: #1f2937;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        
        .section-title i {
            color: var(--primary-color);
        }
        
        .form-label {
            font-weight: 600;
            color: #374151;
            margin-bottom: 0.5rem;
        }
        
        .form-control, .form-select {
            border-radius: 10px;
            border: 2px solid #e5e7eb;
            padding: 0.75rem 1rem;
            transition: all 0.3s ease;
        }
        
        .form-control:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.2rem rgba(59, 130, 246, 0.25);
        }
        
        .upload-area {
            border: 2px dashed #d1d5db;
            border-radius: 12px;
            padding: 2rem;
            text-align: center;
            transition: all 0.3s ease;
            cursor: pointer;
            background: #f9fafb;
        }
        
        .upload-area:hover {
            border-color: var(--primary-color);
            background: #eff6ff;
        }
        
        .upload-area.dragover {
            border-color: var(--primary-color);
            background: #dbeafe;
        }
        
        .upload-area i {
            font-size: 3rem;
            color: #9ca3af;
            margin-bottom: 1rem;
        }
        
        .file-input {
            display: none;
        }
        
        .file-preview {
            display: none;
            margin-top: 1rem;
            padding: 1rem;
            background: #f0fdf4;
            border: 1px solid #86efac;
            border-radius: 8px;
        }
        
        .file-preview.active {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        
        .file-preview i {
            color: var(--success-color);
        }
        
        .btn-primary {
            background: linear-gradient(135deg, var(--primary-color) 0%, var(--primary-dark) 100%);
            border: none;
            padding: 0.75rem 2rem;
            border-radius: 10px;
            font-weight: 600;
            transition: all 0.3s ease;
        }
        
        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(59, 130, 246, 0.3);
        }
        
        .required-indicator {
            color: #ef4444;
            margin-left: 2px;
        }
        
        .document-card {
            background: white;
            border: 2px solid #e5e7eb;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            transition: all 0.3s ease;
        }
        
        .document-card:hover {
            border-color: var(--primary-color);
            box-shadow: 0 5px 15px rgba(59, 130, 246, 0.1);
        }
        
        .document-card h6 {
            font-weight: 600;
            color: #1f2937;
            margin-bottom: 0.5rem;
        }
        
        .document-card p {
            font-size: 0.875rem;
            color: #6b7280;
            margin-bottom: 1rem;
        }
    </style>
</head>
<body>
    <div class="verification-container">
        <!-- Header Logo -->
        <div class="text-center mb-4">
            <a href="<?php echo APP_URL; ?>/" class="text-white text-decoration-none">
                <h3 class="fw-bold mb-0"><i class="bi bi-shield-check me-2"></i>AIMS Verification</h3>
            </a>
        </div>
        
        <div class="verification-card">
            <!-- Header -->
            <div class="verification-header">
                <h2><i class="bi bi-patch-check me-2"></i>Buyer Verification Required</h2>
                <p class="mb-0">Complete verification to unlock all premium features</p>
                <span class="badge mt-2"><?php echo strtoupper($buyerType); ?> ACCOUNT</span>
            </div>
            
            <!-- Body -->
            <div class="verification-body">
                <!-- Error Display -->
                <?php if (isset($error)): ?>
                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                    <i class="bi bi-exclamation-triangle me-2"></i><?php echo $error; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
                <?php endif; ?>
                
                <!-- Info Banner -->
                <div class="info-banner">
                    <div class="d-flex gap-3">
                        <i class="bi bi-info-circle"></i>
                        <div>
                            <h5>Why Verification is Required</h5>
                            <p class="mb-0">As a <strong><?php echo ucfirst($buyerType); ?></strong>, you'll be handling large volume transactions and contracts. Verification ensures trust and security for all parties involved.</p>
                        </div>
                    </div>
                </div>
                
                <!-- Requirements Section -->
                <div class="section-title">
                    <i class="bi bi-clipboard-check"></i>
                    Verification Requirements
                </div>
                
                <ul class="requirements-list mb-4">
                    <li>
                        <i class="bi bi-check-circle-fill"></i>
                        <div>
                            <strong>Valid Business Registration Certificate</strong>
                            <small class="d-block text-muted">Official registration document from Uganda Registration Services Bureau (URSB)</small>
                        </div>
                    </li>
                    <li>
                        <i class="bi bi-check-circle-fill"></i>
                        <div>
                            <strong>Tax Identification Number (TIN) Certificate</strong>
                            <small class="d-block text-muted">Current TIN certificate from Uganda Revenue Authority (URA)</small>
                        </div>
                    </li>
                    <?php if ($buyerType === 'exporter'): ?>
                    <li>
                        <i class="bi bi-check-circle-fill"></i>
                        <div>
                            <strong>Export Trade License</strong>
                            <small class="d-block text-muted">Valid export license from relevant authority</small>
                        </div>
                    </li>
                    <?php endif; ?>
                    <li>
                        <i class="bi bi-check-circle-fill"></i>
                        <div>
                            <strong>Additional Supporting Documents (Optional)</strong>
                            <small class="d-block text-muted">Quality certifications, warehouse documentation, or other relevant licenses</small>
                        </div>
                    </li>
                </ul>
                
                <!-- Verification Form -->
                <form method="POST" enctype="multipart/form-data" id="verificationForm">
                    <div class="section-title mt-5">
                        <i class="bi bi-upload"></i>
                        Upload Verification Documents
                    </div>
                    
                    <!-- Business Registration Info -->
                    <div class="row g-3 mb-4">
                        <div class="col-md-6">
                            <label class="form-label">Business Registration Number <span class="required-indicator">*</span></label>
                            <input type="text" class="form-control" name="business_registration" 
                                   value="<?php echo htmlspecialchars($profile['business_registration'] ?? ''); ?>" 
                                   placeholder="e.g., 12345678" required>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">Tax ID (TIN) <span class="required-indicator">*</span></label>
                            <input type="text" class="form-control" name="tax_id" 
                                   value="<?php echo htmlspecialchars($profile['tax_id'] ?? ''); ?>" 
                                   placeholder="e.g., 1000123456" required>
                        </div>
                    </div>
                    
                    <!-- Document Uploads -->
                    <div class="document-card">
                        <h6><i class="bi bi-file-earmark-pdf me-2"></i>Business Registration Certificate <span class="required-indicator">*</span></h6>
                        <p>Upload your official business registration certificate (PDF, JPG, or PNG - Max 5MB)</p>
                        
                        <div class="upload-area" onclick="document.getElementById('business_cert').click()">
                            <i class="bi bi-cloud-upload"></i>
                            <p class="mb-0"><strong>Click to upload</strong> or drag and drop</p>
                            <small class="text-muted">PDF, JPG, PNG up to 5MB</small>
                        </div>
                        <input type="file" id="business_cert" name="business_cert" class="file-input" accept=".pdf,.jpg,.jpeg,.png" required>
                        <div class="file-preview" id="business_cert_preview">
                            <div>
                                <i class="bi bi-file-earmark-check me-2"></i>
                                <span class="file-name"></span>
                            </div>
                            <button type="button" class="btn btn-sm btn-outline-danger" onclick="clearFile('business_cert')">
                                <i class="bi bi-x"></i>
                            </button>
                        </div>
                    </div>
                    
                    <div class="document-card">
                        <h6><i class="bi bi-file-earmark-pdf me-2"></i>TIN Certificate <span class="required-indicator">*</span></h6>
                        <p>Upload your Tax Identification Number certificate from URA</p>
                        
                        <div class="upload-area" onclick="document.getElementById('tax_cert').click()">
                            <i class="bi bi-cloud-upload"></i>
                            <p class="mb-0"><strong>Click to upload</strong> or drag and drop</p>
                            <small class="text-muted">PDF, JPG, PNG up to 5MB</small>
                        </div>
                        <input type="file" id="tax_cert" name="tax_cert" class="file-input" accept=".pdf,.jpg,.jpeg,.png" required>
                        <div class="file-preview" id="tax_cert_preview">
                            <div>
                                <i class="bi bi-file-earmark-check me-2"></i>
                                <span class="file-name"></span>
                            </div>
                            <button type="button" class="btn btn-sm btn-outline-danger" onclick="clearFile('tax_cert')">
                                <i class="bi bi-x"></i>
                            </button>
                        </div>
                    </div>
                    
                    <?php if ($buyerType === 'exporter'): ?>
                    <div class="document-card">
                        <h6><i class="bi bi-file-earmark-pdf me-2"></i>Export Trade License <span class="required-indicator">*</span></h6>
                        <p>Upload your valid export trade license</p>
                        
                        <div class="upload-area" onclick="document.getElementById('trade_license').click()">
                            <i class="bi bi-cloud-upload"></i>
                            <p class="mb-0"><strong>Click to upload</strong> or drag and drop</p>
                            <small class="text-muted">PDF, JPG, PNG up to 5MB</small>
                        </div>
                        <input type="file" id="trade_license" name="trade_license" class="file-input" accept=".pdf,.jpg,.jpeg,.png" required>
                        <div class="file-preview" id="trade_license_preview">
                            <div>
                                <i class="bi bi-file-earmark-check me-2"></i>
                                <span class="file-name"></span>
                            </div>
                            <button type="button" class="btn btn-sm btn-outline-danger" onclick="clearFile('trade_license')">
                                <i class="bi bi-x"></i>
                            </button>
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <div class="document-card">
                        <h6><i class="bi bi-file-earmark-plus me-2"></i>Additional Documents (Optional)</h6>
                        <p>Upload any additional supporting documents (certifications, licenses, etc.)</p>
                        
                        <div class="upload-area" onclick="document.getElementById('additional_docs').click()">
                            <i class="bi bi-cloud-upload"></i>
                            <p class="mb-0"><strong>Click to upload</strong> or drag and drop</p>
                            <small class="text-muted">PDF, JPG, PNG up to 5MB</small>
                        </div>
                        <input type="file" id="additional_docs" name="additional_docs" class="file-input" accept=".pdf,.jpg,.jpeg,.png">
                        <div class="file-preview" id="additional_docs_preview">
                            <div>
                                <i class="bi bi-file-earmark-check me-2"></i>
                                <span class="file-name"></span>
                            </div>
                            <button type="button" class="btn btn-sm btn-outline-danger" onclick="clearFile('additional_docs')">
                                <i class="bi bi-x"></i>
                            </button>
                        </div>
                    </div>
                    
                    <!-- Submit Button -->
                    <div class="d-flex justify-content-between align-items-center mt-4">
                        <a href="<?php echo APP_URL; ?>/buyer/dashboard.php" class="btn btn-outline-secondary">
                            <i class="bi bi-arrow-left me-2"></i> Skip for Now
                        </a>
                        <button type="submit" class="btn btn-primary">
                            <i class="bi bi-send me-2"></i> Submit for Verification
                        </button>
                    </div>
                </form>
            </div>
        </div>
        
        <!-- Help Section -->
        <div class="text-center mt-4">
            <p class="text-white mb-2">
                <i class="bi bi-question-circle me-2"></i>Need help with verification?
            </p>
            <a href="mailto:support@aims.ug" class="text-white">
                <i class="bi bi-envelope me-2"></i>Contact Support
            </a>
        </div>
    </div>
    
    <!-- jQuery -->
    <script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
    
    <!-- Bootstrap Bundle -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // File upload handling
        document.querySelectorAll('.file-input').forEach(input => {
            input.addEventListener('change', function(e) {
                const file = e.target.files[0];
                if (file) {
                    // Check file size (5MB max)
                    if (file.size > 5 * 1024 * 1024) {
                        alert('File size must be less than 5MB');
                        e.target.value = '';
                        return;
                    }
                    
                    // Show preview
                    const previewId = e.target.id + '_preview';
                    const preview = document.getElementById(previewId);
                    preview.querySelector('.file-name').textContent = file.name;
                    preview.classList.add('active');
                }
            });
        });
        
        // Clear file function
        function clearFile(inputId) {
            document.getElementById(inputId).value = '';
            document.getElementById(inputId + '_preview').classList.remove('active');
        }
        
        // Drag and drop handling
        document.querySelectorAll('.upload-area').forEach(area => {
            area.addEventListener('dragover', function(e) {
                e.preventDefault();
                this.classList.add('dragover');
            });
            
            area.addEventListener('dragleave', function(e) {
                e.preventDefault();
                this.classList.remove('dragover');
            });
            
            area.addEventListener('drop', function(e) {
                e.preventDefault();
                this.classList.remove('dragover');
                
                const input = this.parentElement.querySelector('.file-input');
                input.files = e.dataTransfer.files;
                
                // Trigger change event
                const event = new Event('change', { bubbles: true });
                input.dispatchEvent(event);
            });
        });
        
        // Form validation
        $('#verificationForm').submit(function(e) {
            const requiredFiles = ['business_cert', 'tax_cert'];
            <?php if ($buyerType === 'exporter'): ?>
            requiredFiles.push('trade_license');
            <?php endif; ?>
            
            let valid = true;
            requiredFiles.forEach(fileId => {
                const input = document.getElementById(fileId);
                if (!input.files || input.files.length === 0) {
                    alert('Please upload all required documents');
                    valid = false;
                    return false;
                }
            });
            
            if (!valid) {
                e.preventDefault();
                return false;
            }
            
            // Show loading state
            $(this).find('button[type="submit"]').html('<i class="spinner-border spinner-border-sm me-2"></i> Submitting...').prop('disabled', true);
        });
    </script>
</body>
</html>