<?php 
session_start();
include 'config.php';
include 'includes/head.php';

// TEMP: use logged-in user later
$_SESSION['user_id'] = 1;
$userID = $_SESSION['user_id'];
$user_id = $userID;

// Get user info
$sql = "SELECT u.*, c.name as country_name, c.iso as country_code 
        FROM users u 
        LEFT JOIN country c ON u.country_id = c.id 
        WHERE u.id = '$userID'";
$result = mysqli_query($conn, $sql);
$user = mysqli_fetch_assoc($result);

$userName = $user['username'];
$userEmail = $user['email'];
$userFirstName = $user['first_name'];
$userLastName = $user['last_name'];
$country_name = $user['country_name'] ?: 'United States';
$country_code = $user['country_code'] ?: 'US';
$userAddress = $user['address'];

// Get current KYC status
$kyc_sql = "SELECT * FROM kyc_documents WHERE user_id = '$user_id' ORDER BY upload_date DESC LIMIT 1";
$kyc_result = mysqli_query($conn, $kyc_sql);
$kyc_status = 'not_started';
$document_type = '';
$verification_note = '';

if ($kyc_result && mysqli_num_rows($kyc_result) > 0) {
    $kyc = mysqli_fetch_assoc($kyc_result);
    $kyc_status = $kyc['verification_status'];
    $document_type = $kyc['document_type'];
    $verification_note = $kyc['verification_note'] ?: '';
}

// Country-specific ID documents
$allowed_documents = [];
switch ($country_name) {
    case 'United States':
        $allowed_documents = [
            ['value' => 'passport', 'label' => 'US Passport', 'icon' => 'fi fi-rr-passport'],
            ['value' => 'drivers_license', 'label' => "Driver's License", 'icon' => 'fi fi-rr-id-card'],
            ['value' => 'state_id', 'label' => 'State ID', 'icon' => 'fi fi-rr-id-card-clip-alt']
        ];
        break;
    case 'United Kingdom':
        $allowed_documents = [
            ['value' => 'passport', 'label' => 'UK Passport', 'icon' => 'fi fi-rr-passport'],
            ['value' => 'drivers_license', 'label' => "UK Driving License", 'icon' => 'fi fi-rr-id-card'],
            ['value' => 'biometric_card', 'label' => 'Biometric Card', 'icon' => 'fi fi-rr-id-card-clip-alt']
        ];
        break;
    case 'Canada':
        $allowed_documents = [
            ['value' => 'passport', 'label' => 'Canadian Passport', 'icon' => 'fi fi-rr-passport'],
            ['value' => 'drivers_license', 'label' => "Driver's License", 'icon' => 'fi fi-rr-id-card'],
            ['value' => 'health_card', 'label' => 'Health Card', 'icon' => 'fi fi-rr-id-card-clip-alt']
        ];
        break;
    case 'Australia':
        $allowed_documents = [
            ['value' => 'passport', 'label' => 'Australian Passport', 'icon' => 'fi fi-rr-passport'],
            ['value' => 'drivers_license', 'label' => "Driver's License", 'icon' => 'fi fi-rr-id-card'],
            ['value' => 'proof_of_age', 'label' => 'Proof of Age', 'icon' => 'fi fi-rr-id-card-clip-alt']
        ];
        break;
    case 'South Africa':
        $allowed_documents = [
            ['value' => 'passport', 'label' => 'SA Passport', 'icon' => 'fi fi-rr-passport'],
            ['value' => 'id_book', 'label' => 'ID Book', 'icon' => 'fi fi-rr-id-card'],
            ['value' => 'smart_id', 'label' => 'Smart ID', 'icon' => 'fi fi-rr-id-card-clip-alt']
        ];
        break;
    case 'Nigeria':
        $allowed_documents = [
            ['value' => 'nin', 'label' => 'NIN Slip', 'icon' => 'fi fi-rr-id-card'],
            ['value' => 'passport', 'label' => 'Nigerian Passport', 'icon' => 'fi fi-rr-passport'],
            ['value' => 'drivers_license', 'label' => "Driver's License", 'icon' => 'fi fi-rr-id-card']
        ];
        break;
    case 'India':
        $allowed_documents = [
            ['value' => 'aadhaar', 'label' => 'Aadhaar Card', 'icon' => 'fi fi-rr-id-card-clip-alt'],
            ['value' => 'pan', 'label' => 'PAN Card', 'icon' => 'fi fi-rr-id-card'],
            ['value' => 'passport', 'label' => 'Indian Passport', 'icon' => 'fi fi-rr-passport']
        ];
        break;
    default:
        $allowed_documents = [
            ['value' => 'passport', 'label' => 'International Passport', 'icon' => 'fi fi-rr-passport'],
            ['value' => 'national_id', 'label' => 'National ID', 'icon' => 'fi fi-rr-id-card'],
            ['value' => 'drivers_license', 'label' => "Driver's License", 'icon' => 'fi fi-rr-id-card']
        ];
}

// Address documents (only utility bills)
$address_documents = [
    ['value' => 'utility_bill', 'label' => 'Utility Bill', 'icon' => 'fi fi-rr-bolt', 
     'description' => 'Electricity, water, gas, or internet bill (last 3 months)'],
    ['value' => 'bank_statement', 'label' => 'Bank Statement', 'icon' => 'fi fi-rr-bank',
     'description' => 'Bank statement showing your address (last 3 months)']
];

// Check current documents
$has_identity = false;
$has_address = false;
if ($kyc_status !== 'not_started') {
    $check_sql = "SELECT document_type FROM kyc_documents WHERE user_id = '$user_id'";
    $check_result = mysqli_query($conn, $check_sql);
    while ($doc = mysqli_fetch_assoc($check_result)) {
        if (in_array($doc['document_type'], array_column($allowed_documents, 'value'))) {
            $has_identity = true;
        }
        if (in_array($doc['document_type'], array_column($address_documents, 'value'))) {
            $has_address = true;
        }
    }
}

// Determine current step
$current_step = 1;
if ($has_identity) $current_step = 2;
if ($has_identity && $has_address) $current_step = 3;
if ($kyc_status === 'verified') $current_step = 4;
if ($kyc_status === 'rejected') $current_step = 5;
?>

<!DOCTYPE html>
<html lang="en" data-bs-theme="<?php echo isset($_COOKIE['theme']) ? $_COOKIE['theme'] : 'light'; ?>">
<head>
    <style>
        .kyc-progress { margin-bottom: 30px; }
        .step-indicator {
            display: flex;
            justify-content: space-between;
            position: relative;
        }
        .step-indicator:before {
            content: '';
            position: absolute;
            top: 50%;
            left: 0;
            right: 0;
            height: 2px;
            background: var(--bs-border-color);
            z-index: 1;
        }
        .step {
            position: relative;
            z-index: 2;
            text-align: center;
            width: 100px;
        }
        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: var(--bs-tertiary-bg);
            border: 2px solid var(--bs-border-color);
            display: flex;
            align-items: center;
            justify-content: center;
            margin: 0 auto 10px;
            font-weight: 600;
            color: var(--bs-secondary-color);
        }
        .step.active .step-number {
            background: var(--bs-primary);
            border-color: var(--bs-primary);
            color: white;
        }
        .step.completed .step-number {
            background: var(--bs-success);
            border-color: var(--bs-success);
            color: white;
        }
        .step.rejected .step-number {
            background: var(--bs-danger);
            border-color: var(--bs-danger);
            color: white;
        }
        .step-label {
            font-size: 0.875rem;
            color: var(--bs-secondary-color);
        }
        .step.active .step-label {
            color: var(--bs-primary);
            font-weight: 600;
        }
        .document-option {
            border: 2px solid var(--bs-border-color);
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 10px;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .document-option:hover {
            border-color: var(--bs-primary);
            background: var(--bs-tertiary-bg);
        }
        .document-option.selected {
            border-color: var(--bs-primary);
            background: var(--bs-primary-bg-subtle);
        }
        .document-icon {
            font-size: 24px;
            color: var(--bs-primary);
            margin-right: 15px;
        }
        .file-upload-area {
            border: 2px dashed var(--bs-border-color);
            border-radius: 10px;
            padding: 40px 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
        }
        .file-upload-area:hover {
            border-color: var(--bs-primary);
            background: var(--bs-tertiary-bg);
        }
        .file-preview {
            display: flex;
            align-items: center;
            padding: 10px;
            background: var(--bs-tertiary-bg);
            border-radius: 8px;
            margin-top: 10px;
        }
        .file-preview img {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 4px;
            margin-right: 15px;
        }
        .verification-status {
            padding: 20px;
            border-radius: 10px;
            text-align: center;
        }
        .status-verified {
            background: var(--bs-success-bg-subtle);
            border: 2px solid var(--bs-success);
        }
        .status-pending {
            background: var(--bs-warning-bg-subtle);
            border: 2px solid var(--bs-warning);
        }
        .status-rejected {
            background: var(--bs-danger-bg-subtle);
            border: 2px solid var(--bs-danger);
        }
        .country-badge {
            background: var(--bs-primary);
            color: white;
            padding: 5px 15px;
            border-radius: 20px;
            font-size: 0.875rem;
            font-weight: 600;
        }
        .document-requirements {
            background: var(--bs-tertiary-bg);
            border-radius: 8px;
            padding: 15px;
            margin-top: 20px;
        }
        .requirement-list {
            padding-left: 20px;
            margin-bottom: 0;
        }
        .requirement-list li {
            margin-bottom: 8px;
            color: var(--bs-secondary-color);
        }
        .preview-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.8);
            z-index: 9999;
            display: none;
            align-items: center;
            justify-content: center;
        }
        .preview-container {
            max-width: 90%;
            max-height: 90%;
            background: white;
            border-radius: 10px;
            overflow: hidden;
        }
        .error-message {
            color: var(--bs-danger);
            font-size: 0.875rem;
            margin-top: 5px;
            display: none;
        }
    </style>
</head>
<body class="dashboard">
    <div id="main-wrapper">
        <?php include('includes/header.php');?>
        <?php include('includes/sidebar.php');?>

        <div class="content-body">
            <div class="container">
                <!-- Page Title -->
                <div class="row mb-4">
                    <div class="col-12">
                        <div class="page-title">
                            <div class="row align-items-center justify-content-between">
                                <div class="col-xl-4">
                                    <div class="page-title-content">
                                        <h3>Account Verification (KYC)</h3>
                                        <p class="mb-2">Complete verification to access all features</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Progress Bar -->
                <div class="row mb-4">
                    <div class="col-12">
                        <div class="kyc-progress">
                            <div class="step-indicator">
                                <div class="step <?php echo $current_step >= 1 ? 'completed' : ''; ?> <?php echo $current_step == 1 ? 'active' : ''; ?>">
                                    <div class="step-number">1</div>
                                    <div class="step-label">Identity</div>
                                </div>
                                <div class="step <?php echo $current_step >= 2 ? 'completed' : ''; ?> <?php echo $current_step == 2 ? 'active' : ''; ?>">
                                    <div class="step-number">2</div>
                                    <div class="step-label">Address</div>
                                </div>
                                <div class="step <?php echo $current_step >= 3 ? 'completed' : ''; ?> <?php echo $current_step == 3 ? 'active' : ''; ?>">
                                    <div class="step-number">3</div>
                                    <div class="step-label">Submit</div>
                                </div>
                                <div class="step <?php echo $current_step >= 4 ? 'completed' : ''; ?> <?php echo $current_step == 4 ? 'active' : ''; ?>">
                                    <div class="step-number">4</div>
                                    <div class="step-label">
                                        <?php echo $kyc_status === 'verified' ? 'Verified' : 'Status'; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <!-- Current Status -->
                <?php if ($kyc_status === 'verified'): ?>
                <div class="row mb-4">
                    <div class="col-12">
                        <div class="verification-status status-verified">
                            <i class="fi fi-rr-badge-check text-success" style="font-size: 3rem; margin-bottom: 15px;"></i>
                            <h4 class="text-success">Account Verified!</h4>
                            <p class="text-muted">Your account has been successfully verified.</p>
                        </div>
                    </div>
                </div>
                <?php elseif ($kyc_status === 'pending'): ?>
                <div class="row mb-4">
                    <div class="col-12">
                        <div class="verification-status status-pending">
                            <i class="fi fi-rr-clock text-warning" style="font-size: 3rem; margin-bottom: 15px;"></i>
                            <h4 class="text-warning">Under Review</h4>
                            <p class="text-muted">Your documents are being reviewed (1-3 business days).</p>
                        </div>
                    </div>
                </div>
                <?php elseif ($kyc_status === 'rejected'): ?>
                <div class="row mb-4">
                    <div class="col-12">
                        <div class="verification-status status-rejected">
                            <i class="fi fi-rr-times-circle text-danger" style="font-size: 3rem; margin-bottom: 15px;"></i>
                            <h4 class="text-danger">Verification Rejected</h4>
                            <p class="text-muted"><?php echo htmlspecialchars($verification_note); ?></p>
                            <button class="btn btn-danger mt-3" onclick="restartVerification()">
                                <i class="fi fi-rr-refresh"></i> Try Again
                            </button>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Step 1: Identity Verification -->
                <?php if ($current_step == 1): ?>
                <div class="row">
                    <div class="col-lg-8">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Step 1: Identity Verification</h4>
                                <p class="mb-0">Verify your identity with a government-issued document</p>
                            </div>
                            <div class="card-body">
                                <div class="mb-4">
                                    <div class="d-flex align-items-center justify-content-between mb-3">
                                        <h6>Country: <span class="country-badge"><?php echo htmlspecialchars($country_name); ?></span></h6>
                                    </div>
                                </div>

                                <form id="identityForm" enctype="multipart/form-data">
                                    <!-- Document Type -->
                                    <div class="mb-4">
                                        <label class="form-label required">Select Document Type</label>
                                        <?php foreach($allowed_documents as $doc): ?>
                                        <div class="document-option" onclick="selectDocument(this, '<?php echo $doc['value']; ?>')">
                                            <div class="d-flex align-items-center">
                                                <div class="document-icon">
                                                    <i class="<?php echo $doc['icon']; ?>"></i>
                                                </div>
                                                <div>
                                                    <h6 class="mb-1"><?php echo htmlspecialchars($doc['label']); ?></h6>
                                                    <p class="mb-0 text-muted">Valid government-issued document</p>
                                                </div>
                                            </div>
                                            <input type="radio" name="document_type" value="<?php echo $doc['value']; ?>" 
                                                   style="display: none;">
                                        </div>
                                        <?php endforeach; ?>
                                        <div id="error_document_type" class="error-message">Please select a document type</div>
                                    </div>

                                    <!-- Document Number -->
                                    <div class="mb-4">
                                        <label class="form-label required">Document Number</label>
                                        <input type="text" class="form-control" name="document_number" 
                                               placeholder="Enter document number" required>
                                        <div id="error_document_number" class="error-message">Please enter document number</div>
                                    </div>

                                    <!-- Document Upload -->
                                    <div class="mb-4">
                                        <label class="form-label required">Upload Document</label>
                                        <div class="file-upload-area" onclick="$('#identityFile').click()">
                                            <i class="fi fi-rr-cloud-upload-alt text-muted" style="font-size: 3rem;"></i>
                                            <h5 class="my-3">Upload your identity document</h5>
                                            <p class="text-muted mb-2">Click to upload</p>
                                            <small class="text-muted">JPG, PNG, or PDF (Max 10MB)</small>
                                        </div>
                                        <input type="file" id="identityFile" name="document_file" 
                                               accept=".jpg,.jpeg,.png,.pdf" style="display: none;" 
                                               onchange="previewFile(this, 'identity')" required>
                                        <div id="identityFileName" class="mt-2 text-muted"></div>
                                        <div id="error_document_file" class="error-message">Please upload a document</div>
                                        
                                        <div id="identityPreview" class="file-preview" style="display: none;">
                                            <img id="identityPreviewImg" src="" alt="Preview">
                                            <div class="flex-grow-1">
                                                <h6 id="identityPreviewName"></h6>
                                                <small id="identityPreviewSize" class="text-muted"></small>
                                            </div>
                                            <button type="button" class="btn btn-outline-secondary btn-sm" 
                                                    onclick="openPreview('identity')">
                                                <i class="fi fi-rr-search"></i> View
                                            </button>
                                        </div>
                                    </div>

                                    <!-- Requirements -->
                                    <div class="document-requirements">
                                        <h6 class="mb-3">Requirements:</h6>
                                        <ul class="requirement-list">
                                            <li>Document must be valid and not expired</li>
                                            <li>All text must be clear and readable</li>
                                            <li>All four corners must be visible</li>
                                            <li>File must be in color (not black & white)</li>
                                            <li>Maximum file size: 10MB</li>
                                            <li>Accepted: JPG, PNG, PDF</li>
                                        </ul>
                                    </div>

                                    <button type="button" class="btn btn-primary btn-lg w-100 mt-3" 
                                            onclick="submitIdentity()">
                                        <i class="fi fi-rr-check"></i> Submit Identity Verification
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">Why Verify?</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <h6><i class="fi fi-rr-shield-check text-success"></i> Enhanced Security</h6>
                                    <p class="text-muted small">Protect your account from unauthorized access.</p>
                                </div>
                                <div class="mb-3">
                                    <h6><i class="fi fi-rr-chart-line-up text-primary"></i> Higher Limits</h6>
                                    <p class="text-muted small">Increased deposit and withdrawal limits.</p>
                                </div>
                                <div class="mb-3">
                                    <h6><i class="fi fi-rr-bolt text-warning"></i> Faster Processing</h6>
                                    <p class="text-muted small">Quick approval for withdrawals and deposits.</p>
                                </div>
                                <div class="alert alert-info mt-3">
                                    <h6><i class="fi fi-rr-lock"></i> Data Security</h6>
                                    <p class="text-muted small mb-0">Your documents are encrypted and stored securely.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Step 2: Address Verification -->
                <?php if ($current_step == 2): ?>
                <div class="row">
                    <div class="col-lg-8">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Step 2: Address Verification</h4>
                                <p class="mb-0">Verify your address with a utility bill or bank statement</p>
                            </div>
                            <div class="card-body">
                                <form id="addressForm" enctype="multipart/form-data">
                                    <!-- Document Type -->
                                    <div class="mb-4">
                                        <label class="form-label required">Select Document Type</label>
                                        <?php foreach($address_documents as $doc): ?>
                                        <div class="document-option" onclick="selectDocument(this, '<?php echo $doc['value']; ?>', 'address')">
                                            <div class="d-flex align-items-center">
                                                <div class="document-icon">
                                                    <i class="<?php echo $doc['icon']; ?>"></i>
                                                </div>
                                                <div>
                                                    <h6 class="mb-1"><?php echo htmlspecialchars($doc['label']); ?></h6>
                                                    <p class="mb-0 text-muted"><?php echo htmlspecialchars($doc['description']); ?></p>
                                                </div>
                                            </div>
                                            <input type="radio" name="address_document_type" value="<?php echo $doc['value']; ?>" 
                                                   style="display: none;">
                                        </div>
                                        <?php endforeach; ?>
                                        <div id="error_address_type" class="error-message">Please select a document type</div>
                                    </div>

                                    <!-- Address Details -->
                                    <div class="mb-4">
                                        <h6>Address Details</h6>
                                        <div class="mb-3">
                                            <label class="form-label">Street Address</label>
                                            <input type="text" class="form-control" name="street_address" 
                                                   value="<?php echo htmlspecialchars($userAddress); ?>" readonly>
                                        </div>
                                        <div class="row">
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">City</label>
                                                <input type="text" class="form-control" name="city" required>
                                            </div>
                                            <div class="col-md-6 mb-3">
                                                <label class="form-label">ZIP/Postal Code</label>
                                                <input type="text" class="form-control" name="postal_code" required>
                                            </div>
                                        </div>
                                        <div class="mb-3">
                                            <label class="form-label">Country</label>
                                            <input type="text" class="form-control" value="<?php echo htmlspecialchars($country_name); ?>" readonly>
                                        </div>
                                    </div>

                                    <!-- Document Upload -->
                                    <div class="mb-4">
                                        <label class="form-label required">Upload Document</label>
                                        <div class="file-upload-area" onclick="$('#addressFile').click()">
                                            <i class="fi fi-rr-cloud-upload-alt text-muted" style="font-size: 3rem;"></i>
                                            <h5 class="my-3">Upload your address proof</h5>
                                            <p class="text-muted mb-2">Click to upload</p>
                                            <small class="text-muted">JPG, PNG, or PDF (Max 10MB)</small>
                                        </div>
                                        <input type="file" id="addressFile" name="address_file" 
                                               accept=".jpg,.jpeg,.png,.pdf" style="display: none;" 
                                               onchange="previewFile(this, 'address')" required>
                                        <div id="addressFileName" class="mt-2 text-muted"></div>
                                        <div id="error_address_file" class="error-message">Please upload a document</div>
                                        
                                        <div id="addressPreview" class="file-preview" style="display: none;">
                                            <img id="addressPreviewImg" src="" alt="Preview">
                                            <div class="flex-grow-1">
                                                <h6 id="addressPreviewName"></h6>
                                                <small id="addressPreviewSize" class="text-muted"></small>
                                            </div>
                                            <button type="button" class="btn btn-outline-secondary btn-sm" 
                                                    onclick="openPreview('address')">
                                                <i class="fi fi-rr-search"></i> View
                                            </button>
                                        </div>
                                    </div>

                                    <!-- Requirements -->
                                    <div class="document-requirements">
                                        <h6 class="mb-3">Requirements:</h6>
                                        <ul class="requirement-list">
                                            <li>Document must be issued within last 3 months</li>
                                            <li>Must show your name and address clearly</li>
                                            <li>Address must match your account address</li>
                                            <li>Document must be from official organization</li>
                                            <li>All text must be readable</li>
                                            <li>No screenshots or edited documents</li>
                                        </ul>
                                    </div>

                                    <button type="button" class="btn btn-primary btn-lg w-100 mt-3" 
                                            onclick="submitAddress()">
                                        <i class="fi fi-rr-check"></i> Submit Address Verification
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">Accepted Documents</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <h6><i class="fi fi-rr-bolt text-primary"></i> Utility Bills</h6>
                                    <p class="text-muted small">Electricity, water, gas, internet bills.</p>
                                </div>
                                <div class="mb-3">
                                    <h6><i class="fi fi-rr-bank text-success"></i> Bank Statements</h6>
                                    <p class="text-muted small">Official bank statements with address.</p>
                                </div>
                                <div class="alert alert-warning mt-3">
                                    <h6><i class="fi fi-rr-exclamation-triangle"></i> Not Accepted</h6>
                                    <p class="text-muted small mb-0">Handwritten documents, screenshots, documents older than 3 months.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>

                <!-- Step 3: Review & Submit -->
                <?php if ($current_step == 3): ?>
                <div class="row">
                    <div class="col-lg-8">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Step 3: Review & Submit</h4>
                                <p class="mb-0">Review your documents before final submission</p>
                            </div>
                            <div class="card-body">
                                <?php
                                // Get uploaded documents
                                $id_sql = "SELECT * FROM kyc_documents WHERE user_id = '$user_id' 
                                          AND document_type IN ('" . implode("','", array_column($allowed_documents, 'value')) . "') 
                                          ORDER BY upload_date DESC LIMIT 1";
                                $id_result = mysqli_query($conn, $id_sql);
                                $identity = mysqli_fetch_assoc($id_result);
                                
                                $addr_sql = "SELECT * FROM kyc_documents WHERE user_id = '$user_id' 
                                            AND document_type IN ('" . implode("','", array_column($address_documents, 'value')) . "') 
                                            ORDER BY upload_date DESC LIMIT 1";
                                $addr_result = mysqli_query($conn, $addr_sql);
                                $address = mysqli_fetch_assoc($addr_result);
                                ?>

                                <!-- Identity Document -->
                                <div class="mb-4">
                                    <h6>Identity Document</h6>
                                    <div class="card">
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-3">
                                                    <img src="<?php echo $identity['document_path']; ?>" 
                                                         alt="ID Document" style="width: 100%; border-radius: 8px;">
                                                </div>
                                                <div class="col-md-9">
                                                    <h6><?php echo strtoupper($identity['document_type']); ?></h6>
                                                    <p class="text-muted">Number: <?php echo $identity['document_number']; ?></p>
                                                    <p class="text-muted small">Uploaded: <?php echo date('M j, Y', strtotime($identity['upload_date'])); ?></p>
                                                    <span class="badge bg-success">✓ Ready for review</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Address Document -->
                                <div class="mb-4">
                                    <h6>Address Document</h6>
                                    <div class="card">
                                        <div class="card-body">
                                            <div class="row">
                                                <div class="col-md-3">
                                                    <img src="<?php echo $address['document_path']; ?>" 
                                                         alt="Address Document" style="width: 100%; border-radius: 8px;">
                                                </div>
                                                <div class="col-md-9">
                                                    <h6><?php echo strtoupper($address['document_type']); ?></h6>
                                                    <p class="text-muted">Address Proof Document</p>
                                                    <p class="text-muted small">Uploaded: <?php echo date('M j, Y', strtotime($address['upload_date'])); ?></p>
                                                    <span class="badge bg-success">✓ Ready for review</span>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>

                                <!-- Agreement -->
                                <div class="mb-4">
                                    <div class="form-check">
                                        <input class="form-check-input" type="checkbox" id="agreeTerms">
                                        <label class="form-check-label" for="agreeTerms">
                                            I certify that all documents are authentic and belong to me.
                                        </label>
                                    </div>
                                    <div id="error_terms" class="error-message">You must agree to the terms</div>
                                </div>

                                <button type="button" class="btn btn-primary btn-lg w-100" onclick="submitVerification()">
                                    <i class="fi fi-rr-paper-plane"></i> Submit for Verification
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="col-lg-4">
                        <div class="card">
                            <div class="card-header">
                                <h5 class="card-title">What Happens Next?</h5>
                            </div>
                            <div class="card-body">
                                <div class="mb-3">
                                    <h6><i class="fi fi-rr-document text-primary"></i> Document Review</h6>
                                    <p class="text-muted small">Our team reviews your documents (1-3 days).</p>
                                </div>
                                <div class="mb-3">
                                    <h6><i class="fi fi-rr-check-circle text-success"></i> Verification Check</h6>
                                    <p class="text-muted small">We verify information matches your account.</p>
                                </div>
                                <div class="mb-3">
                                    <h6><i class="fi fi-rr-envelope text-warning"></i> Status Update</h6>
                                    <p class="text-muted small">You'll receive an email with the result.</p>
                                </div>
                                <div class="alert alert-info mt-3">
                                    <h6><i class="fi fi-rr-clock"></i> Processing Time</h6>
                                    <p class="text-muted small mb-0">Typically 1-3 business days.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </div>
        </div>

        <?php include('includes/footer.php');?>
    </div>

    <!-- Preview Modal -->
    <div class="preview-overlay" id="previewOverlay" onclick="closePreview()">
        <div class="preview-container" onclick="event.stopPropagation()">
            <div class="p-3">
                <img id="previewImage" src="" alt="Preview" style="max-width: 100%; max-height: 80vh;">
            </div>
        </div>
    </div>

    <script src="vendor/jquery/jquery.min.js"></script>
    <script>
    // Document selection
    function selectDocument(element, value, type = 'identity') {
        const container = type === 'identity' ? '#identityForm' : '#addressForm';
        $(container + ' .document-option').removeClass('selected');
        $(element).addClass('selected');
        $(element).find('input[type="radio"]').prop('checked', true);
        $(container + ' .error-message').hide();
    }

    // File preview
    function previewFile(input, type) {
        const file = input.files[0];
        if (!file) return;
        
        const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf'];
        const maxSize = 10 * 1024 * 1024; // 10MB
        
        if (!validTypes.includes(file.type)) {
            showToast('Error!', 'Please upload JPG, PNG, or PDF files only.', 'danger');
            input.value = '';
            return;
        }
        
        if (file.size > maxSize) {
            showToast('Error!', 'File too large. Maximum size is 10MB.', 'danger');
            input.value = '';
            return;
        }
        
        // Show file info
        const fileName = type === 'identity' ? '#identityFileName' : '#addressFileName';
        const preview = type === 'identity' ? '#identityPreview' : '#addressPreview';
        const previewImg = type === 'identity' ? '#identityPreviewImg' : '#addressPreviewImg';
        const previewName = type === 'identity' ? '#identityPreviewName' : '#addressPreviewName';
        const previewSize = type === 'identity' ? '#identityPreviewSize' : '#addressPreviewSize';
        
        $(fileName).html('<span class="text-success">✓</span> ' + file.name + ' (' + (file.size/1024/1024).toFixed(2) + ' MB)');
        $(preview).show();
        
        if (file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function(e) {
                $(previewImg).attr('src', e.target.result);
            };
            reader.readAsDataURL(file);
        } else {
            // PDF placeholder
            $(previewImg).attr('src', 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48cmVjdCB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHJ4PSI0IiBmaWxsPSIjNkI3Mjg4Ii8+PHBhdGggZD0iTTM1IDI1SDE1VjQ1SDQ1VjM1SDM1VjI1WiIgZmlsbD0id2hpdGUiLz48cGF0aCBkPSJNMzUgMjVINDVMMzUgMTVWMjVaIiBmaWxsPSJ3aGl0ZSIvPjwvc3ZnPg==');
        }
        
        $(previewName).text(file.name);
        $(previewSize).text((file.size/1024/1024).toFixed(2) + ' MB');
        $(type === 'identity' ? '#error_document_file' : '#error_address_file').hide();
    }

    function openPreview(type) {
        const fileInput = type === 'identity' ? document.getElementById('identityFile') : document.getElementById('addressFile');
        const file = fileInput.files[0];
        
        if (file && file.type.startsWith('image/')) {
            const reader = new FileReader();
            reader.onload = function(e) {
                document.getElementById('previewImage').src = e.target.result;
                document.getElementById('previewOverlay').style.display = 'flex';
            };
            reader.readAsDataURL(file);
        } else {
            showToast('Info', 'Preview available for image files only.', 'info');
        }
    }

    function closePreview() {
        document.getElementById('previewOverlay').style.display = 'none';
    }

    // Toast notification
    function showToast(title, message, type) {
        const icon = type === 'success' ? '✓' : type === 'error' ? '✗' : type === 'warning' ? '⚠' : 'ℹ';
        const toast = `<div class="toast show position-fixed" style="top:20px;right:20px;z-index:9999;min-width:300px;">
            <div class="toast-header bg-${type} text-white">
                <strong class="me-auto">${icon} ${title}</strong>
                <button type="button" class="btn-close btn-close-white" onclick="$(this).closest('.toast').remove()"></button>
            </div>
            <div class="toast-body">${message}</div>
        </div>`;
        $('body').append(toast);
        setTimeout(() => $('.toast').last().remove(), 5000);
    }

    // Submit Identity
    function submitIdentity() {
        const form = document.getElementById('identityForm');
        const formData = new FormData(form);
        
        // Validate
        let valid = true;
        $('.error-message').hide();
        
        if (!$('input[name="document_type"]:checked').val()) {
            $('#error_document_type').show();
            valid = false;
        }
        
        if (!$('input[name="document_number"]').val().trim()) {
            $('#error_document_number').show();
            valid = false;
        }
        
        if (!$('#identityFile').val()) {
            $('#error_document_file').show();
            valid = false;
        }
        
        if (!valid) {
            showToast('Error!', 'Please fill all required fields.', 'danger');
            return;
        }
        
        // Show loading
        showToast('Processing...', 'Uploading your identity document.', 'info');
        
        $.ajax({
            url: 'process_kyc.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                // Direct PHP response handling
                if (response.includes('success')) {
                    showToast('Success!', 'Identity document uploaded successfully.', 'success');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    // Show error from PHP
                    showToast('Error!', response, 'danger');
                }
            },
            error: function() {
                showToast('Error!', 'Network error. Please try again.', 'danger');
            }
        });
    }

    // Submit Address
    function submitAddress() {
        const form = document.getElementById('addressForm');
        const formData = new FormData(form);
        
        // Validate
        let valid = true;
        $('.error-message').hide();
        
        if (!$('input[name="address_document_type"]:checked').val()) {
            $('#error_address_type').show();
            valid = false;
        }
        
        if (!$('input[name="city"]').val().trim()) {
            showToast('Error!', 'Please enter your city.', 'danger');
            return;
        }
        
        if (!$('input[name="postal_code"]').val().trim()) {
            showToast('Error!', 'Please enter your postal code.', 'danger');
            return;
        }
        
        if (!$('#addressFile').val()) {
            $('#error_address_file').show();
            valid = false;
        }
        
        if (!valid) {
            showToast('Error!', 'Please fill all required fields.', 'danger');
            return;
        }
        
        // Show loading
        showToast('Processing...', 'Uploading your address document.', 'info');
        
        $.ajax({
            url: 'process_address.php',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.includes('success')) {
                    showToast('Success!', 'Address document uploaded successfully.', 'success');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showToast('Error!', response, 'danger');
                }
            },
            error: function() {
                showToast('Error!', 'Network error. Please try again.', 'danger');
            }
        });
    }

    // Submit Verification
    function submitVerification() {
        if (!$('#agreeTerms').is(':checked')) {
            showToast('Error!', 'You must agree to the terms and conditions.', 'danger');
            $('#error_terms').show();
            return;
        }
        
        if (!confirm('Submit your documents for verification? This process takes 1-3 business days.')) {
            return;
        }
        
        showToast('Processing...', 'Submitting your verification request.', 'info');
        
        $.ajax({
            url: 'submit_verification.php',
            type: 'POST',
            success: function(response) {
                if (response.includes('success')) {
                    showToast('Success!', 'Verification submitted successfully! You will receive an email when complete.', 'success');
                    setTimeout(() => location.reload(), 1500);
                } else {
                    showToast('Error!', response, 'danger');
                }
            },
            error: function() {
                showToast('Error!', 'Network error. Please try again.', 'danger');
            }
        });
    }

    function restartVerification() {
        if (!confirm('Start new verification? Your previous documents will be archived.')) {
            return;
        }
        
        $.ajax({
            url: 'restart_verification.php',
            type: 'POST',
            success: function(response) {
                if (response.includes('success')) {
                    location.reload();
                } else {
                    showToast('Error!', response, 'danger');
                }
            }
        });
    }
    </script>
</body>
</html>