<?php
/**
 * KYC Document Upload Handler
 */
$pageTitle = 'KYC Submit';
require_once 'includes/header.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: profile.php');
    exit;
}

$error = '';
$success = '';

try {
    // Validate document type
    $documentType = $_POST['document_type'] ?? '';
    $documentNumber = trim($_POST['document_number'] ?? '');
    $allowedTypes = ['aadhar', 'pan', 'passport', 'driving_license', 'voter_id'];
    
    if (!in_array($documentType, $allowedTypes)) {
        throw new Exception('Invalid document type selected.');
    }
    
    if (empty($documentNumber)) {
        throw new Exception('Document number is required.');
    }
    
    // Check if user is already verified
    if (($user['kyc_status'] ?? '') === 'verified') {
        throw new Exception('Your KYC is already verified.');
    }
    
    if (($user['kyc_status'] ?? '') === 'submitted') {
        throw new Exception('Your documents are already under review.');
    }
    
    // Handle file uploads
    $uploadDir = $_SERVER['DOCUMENT_ROOT'] . '/binary-options/uploads/kyc/';
    if (!is_dir($uploadDir)) {
        mkdir($uploadDir, 0755, true);
    }
    
    // Front image (required)
    if (empty($_FILES['front_image']['name']) || $_FILES['front_image']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('Front side photo is required.');
    }
    
    // Selfie image (required)
    if (empty($_FILES['selfie_image']['name']) || $_FILES['selfie_image']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception('Selfie with document is required.');
    }
    
    // Validate file types
    $allowedExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
    $maxFileSize = 5 * 1024 * 1024; // 5MB
    
    $filesToUpload = ['front_image', 'selfie_image'];
    if (!empty($_FILES['back_image']['name']) && $_FILES['back_image']['error'] === UPLOAD_ERR_OK) {
        $filesToUpload[] = 'back_image';
    }
    
    $uploadedFiles = [];
    
    foreach ($filesToUpload as $fileKey) {
        $file = $_FILES[$fileKey];
        $ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
        
        if (!in_array($ext, $allowedExtensions)) {
            throw new Exception("Invalid file type for $fileKey. Allowed: " . implode(', ', $allowedExtensions));
        }
        
        if ($file['size'] > $maxFileSize) {
            throw new Exception("File $fileKey is too large. Maximum size is 5MB.");
        }
        
        $fileName = 'kyc_' . $user['id'] . '_' . $fileKey . '_' . time() . '.' . $ext;
        $filePath = $uploadDir . $fileName;
        
        if (!move_uploaded_file($file['tmp_name'], $filePath)) {
            throw new Exception("Failed to upload $fileKey. Please try again.");
        }
        
        $uploadedFiles[$fileKey] = $fileName;
    }
    
    // Delete old KYC records for this user if re-submitting
    dbDelete('user_kyc', 'user_id = :uid', ['uid' => $user['id']]);
    
    // Insert into user_kyc table
    $kycData = [
        'user_id' => $user['id'],
        'document_type' => $documentType,
        'document_number' => $documentNumber,
        'document_front' => $uploadedFiles['front_image'],
        'document_back' => $uploadedFiles['back_image'] ?? null,
        'selfie' => $uploadedFiles['selfie_image'],
        'status' => 'pending'
    ];
    
    dbInsert('user_kyc', $kycData);
    
    // Update user kyc_status to submitted
    dbUpdate('users', ['kyc_status' => 'submitted'], 'id = :uid', ['uid' => $user['id']]);
    
    $success = 'Your KYC documents have been submitted successfully! Verification usually takes 24-48 hours.';
    
} catch (Exception $e) {
    $error = $e->getMessage();
}
?>

<div class="card">
    <div class="card-body text-center py-5">
        <?php if ($error): ?>
            <i class="fas fa-times-circle text-red" style="font-size: 4rem;"></i>
            <h3 style="margin: 1rem 0;">Submission Failed</h3>
            <p class="text-muted"><?= htmlspecialchars($error) ?></p>
            <a href="profile.php" class="btn btn-primary" style="margin-top: 1rem;">
                <i class="fas fa-arrow-left"></i> Go Back to Profile
            </a>
        <?php else: ?>
            <i class="fas fa-check-circle text-green" style="font-size: 4rem;"></i>
            <h3 style="margin: 1rem 0;">Documents Submitted!</h3>
            <p class="text-muted"><?= htmlspecialchars($success) ?></p>
            <a href="profile.php" class="btn btn-primary" style="margin-top: 1rem;">
                <i class="fas fa-arrow-left"></i> Go Back to Profile
            </a>
        <?php endif; ?>
    </div>
</div>

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