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

$user_id = $_SESSION['user_id'];
if (!$user_id) {
    echo '<script>showToast("Error!", "Please login first.", "danger");</script>';
    exit;
}

// Get user details for notification
$userQuery = mysqli_query($conn, "SELECT first_name, last_name, email, verification_level FROM users WHERE id='$user_id'");
$userData = mysqli_fetch_assoc($userQuery);
$first_name = $userData['first_name'];
$email = $userData['email'];
$current_verification_level = $userData['verification_level'] ?? 'unverified';

// Get IP address for security notification
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];

// Check if document already submitted
$check_sql = "SELECT * FROM kyc_documents WHERE user_id = '$user_id' 
              AND verification_status IN ('pending', 'verified')";
$check_result = mysqli_query($conn, $check_sql);
if (mysqli_num_rows($check_result) > 0) {
    echo '<script>showToast("Error!", "You already have a pending or verified document.", "danger");</script>';
    exit;
}

// Validate inputs
$document_type = mysqli_real_escape_string($conn, $_POST['document_type']);
$document_number = mysqli_real_escape_string($conn, $_POST['document_number']);

if (!$document_type || !$document_number) {
    echo '<script>showToast("Error!", "Please provide document type and number.", "danger");</script>';
    exit;
}

// Handle file upload
if (!isset($_FILES['document_file']) || $_FILES['document_file']['error'] != 0) {
    echo '<script>showToast("Error!", "Please upload a document file.", "danger");</script>';
    exit;
}

$file = $_FILES['document_file'];
$allowed_types = ['image/jpeg', 'image/jpg', 'image/png', 'application/pdf'];
$max_size = 10 * 1024 * 1024; // 10MB

if (!in_array($file['type'], $allowed_types)) {
    echo '<script>showToast("Error!", "Invalid file type. Only JPG, PNG, PDF allowed.", "danger");</script>';
    exit;
}

if ($file['size'] > $max_size) {
    echo '<script>showToast("Error!", "File too large. Maximum 10MB allowed.", "danger");</script>';
    exit;
}

// Create upload directory
$upload_dir = 'uploads/kyc/' . $user_id . '/';
if (!file_exists($upload_dir)) {
    mkdir($upload_dir, 0777, true);
}

// Generate unique filename
$file_ext = strtolower(pathinfo($file['name'], PATHINFO_EXTENSION));
$filename = 'id_' . time() . '_' . uniqid() . '.' . $file_ext;
$filepath = $upload_dir . $filename;

// Move uploaded file
if (!move_uploaded_file($file['tmp_name'], $filepath)) {
    echo '<script>showToast("Error!", "Failed to upload file. Please try again.", "danger");</script>';
    exit;
}

// Insert into database
$insert_sql = "INSERT INTO kyc_documents 
              (user_id, document_type, document_number, document_path, upload_date, verification_status) 
              VALUES 
              ('$user_id', '$document_type', '$document_number', '$filepath', NOW(), 'pending')";

if (mysqli_query($conn, $insert_sql)) {
    $kyc_id = mysqli_insert_id($conn);
    
    // Update user verification status
    mysqli_query($conn, "UPDATE users SET verification_submitted = 1 WHERE id = '$user_id'");
    
    // NOTIFICATION: KYC Document Submitted (USER)
    $mail_subject = "KYC Document Submitted Successfully";
    $mail_message = "<!-- Content Section -->
                    <div class='email-content'>
                        <h2 class='greeting'>Hello <span class='user-name'>" . $first_name . "</span>,</h2>
                        
                        <p class='message'>
                            ✅ <strong>Your KYC document has been submitted successfully!</strong><br>
                            Thank you for helping us verify your identity and enhance your account security.
                        </p>

                        <!-- Submission Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Submission Reference:</strong> KYC-" . $kyc_id . "<br>
                                <strong>Document Type:</strong> " . htmlspecialchars(ucfirst(str_replace('_', ' ', $document_type))) . "<br>
                                <strong>Document Number:</strong> " . htmlspecialchars($document_number) . " (masked for security)<br>
                                <strong>Submission Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Current Verification Level:</strong> <span style='color: #ffc107; font-weight: bold;'>" . ucfirst($current_verification_level) . "</span><br>
                                <strong>Target Verification Level:</strong> <span style='color: #28a745; font-weight: bold;'>Verified</span><br>
                                <strong>Submitted From IP:</strong> " . $user_ip . "<br>
                                <strong>File Type:</strong> " . strtoupper($file_ext) . "
                            </div>
                        </div>

                        <!-- What Happens Next -->
                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0056b3;'>📋 Verification Process Timeline</h4>
                            <p style='color: #0056b3;'>
                                <strong>Step 1:</strong> Document received (✓ Completed)<br>
                                <strong>Step 2:</strong> Initial review (1-2 business days)<br>
                                <strong>Step 3:</strong> Manual verification (3-5 business days)<br>
                                <strong>Step 4:</strong> Account upgrade notification<br>
                                <strong>Step 5:</strong> Enhanced limits activated
                            </p>
                        </div>

                        <!-- Benefits of Verification -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>🎯 Benefits You'll Unlock</h3>
                            <p style='color: #6c757d;'>Once verified, you'll gain:</p>
                            <ul style='color: #6c757d;'>
                                <li><strong>Higher withdrawal limits</strong> (up to $10,000 daily)</li>
                                <li><strong>Priority customer support</strong> with faster response times</li>
                                <li><strong>Increased trading limits</strong> for bot subscriptions</li>
                                <li><strong>Access to premium trading features</strong></li>
                                <li><strong>Enhanced account security</strong> with verified status</li>
                                <li><strong>Faster deposit processing</strong> times</li>
                            </ul>
                        </div>

                        <!-- Important Information -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>ℹ️ Important Information</h4>
                            <ul style='color: #856404;'>
                                <li>Your documents are stored securely with bank-level encryption</li>
                                <li>We never share your documents with third parties</li>
                                <li>Verification typically takes 3-5 business days</li>
                                <li>You'll receive email updates throughout the process</li>
                                <li>You can check verification status in your dashboard</li>
                            </ul>
                        </div>

                        <!-- Security Assurance -->
                        <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #155724;'>🔒 Security & Privacy Assurance</h4>
                            <p style='color: #155724;'>
                                <strong>Your security is our priority:</strong><br>
                                • All documents are encrypted and securely stored<br>
                                • Access is restricted to authorized personnel only<br>
                                • Documents are automatically deleted after 90 days of verification<br>
                                • We comply with international data protection regulations
                            </p>
                        </div>

                        <!-- Action Buttons -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/verification-status.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #2F2CD8; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                Check Verification Status
                            </a>
                            <a href='" . $myUrl . "/limits.php' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #6c757d; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                View Account Limits
                            </a>
                        </div>

                        <!-- Support Section -->
                        <div class='support-section'>
                            <p class='support-text'>Need help with verification?</p>
                            <a href='" . $myUrl . "/support.php?category=verification' class='support-link'>Contact Verification Support</a>
                        </div>
                    </div>";

    // Send user notification
    require_once("../proccess/mail_sender.php");

    // NOTIFICATION: New KYC Submission (ADMIN)
    $admin_mail_subject = "New KYC Document Submitted - User ID: " . $user_id;
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>New KYC Document Submitted</h2>
                            
                            <p class='message'>
                                A user has submitted a new KYC document for identity verification.
                            </p>

                            <!-- Submission Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>KYC ID:</strong> KYC-" . $kyc_id . "<br>
                                    <strong>User ID:</strong> " . $user_id . "<br>
                                    <strong>User Name:</strong> " . $first_name . " " . $userData['last_name'] . "<br>
                                    <strong>User Email:</strong> " . $email . "<br>
                                    <strong>Document Type:</strong> " . htmlspecialchars(ucfirst(str_replace('_', ' ', $document_type))) . "<br>
                                    <strong>Document Number:</strong> " . htmlspecialchars($document_number) . "<br>
                                    <strong>Submission Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>Current Verification Level:</strong> " . ucfirst($current_verification_level) . "<br>
                                    <strong>User IP Address:</strong> " . $user_ip . "<br>
                                    <strong>File Path:</strong> " . htmlspecialchars($filepath) . "<br>
                                    <strong>File Size:</strong> " . format_file_size($file['size']) . "<br>
                                    <strong>File Type:</strong> " . $file['type'] . "
                                </div>
                            </div>

                            <!-- User Account Information -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>User Account Details</h3>
                                <p style='color: #6c757d;'>
                                    <strong>Account Created:</strong> " . (isset($userData['created_at']) ? date('F j, Y', strtotime($userData['created_at'])) : 'N/A') . "<br>
                                    <strong>Account Status:</strong> " . (isset($userData['account_status']) ? ucfirst($userData['account_status']) : 'Active') . "<br>
                                    <strong>Total Deposits:</strong> $" . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT SUM(amount) as total FROM deposits WHERE user_id='$user_id' AND status='completed'"))['total'] ?? 0) . "<br>
                                    <strong>Total Withdrawals:</strong> $" . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT SUM(amount) as total FROM withdrawals WHERE user_id='$user_id' AND status='completed'"))['total'] ?? 0) . "<br>
                                    <strong>Active Bots:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as count FROM user_bot_subscriptions WHERE user_id='$user_id' AND status='active'"))['count'] ?? 0) . "
                                </p>
                            </div>

                            <!-- Verification Requirements -->
                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0056b3;'>📋 Verification Checklist</h4>
                                <p style='color: #0056b3;'>
                                    <strong>Required for Level 2 Verification:</strong><br>
                                    • Valid government-issued ID ✓<br>
                                    • Clear photo of document ✓<br>
                                    • Document number visible ✓<br>
                                    • Expiration date visible (if applicable)<br>
                                    • User photo matching document
                                </p>
                            </div>

                            <!-- Admin Actions -->
                            <div style='text-align: center; margin: 30px 0;'>
                                <a href='" . $myUrl . "/admin/kyc/review.php?id=" . $kyc_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #198754; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    Review Document
                                </a>
                                <a href='" . $myUrl . "/admin/users.php?id=" . $user_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #0dcaf0; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    View User Profile
                                </a>
                                <a href='" . $myUrl . "/admin/kyc/documents.php?user_id=" . $user_id . "' class='verification-button' style='display: inline-block; padding: 12px 30px; background: #6f42c1; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    View All Documents
                                </a>
                            </div>

                            <!-- SLA Information -->
                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #856404;'>⏰ Verification SLA</h4>
                                <p style='color: #856404;'>
                                    <strong>Priority:</strong> Standard<br>
                                    <strong>Target Review Time:</strong> 48 hours<br>
                                    <strong>Maximum Review Time:</strong> 5 business days<br>
                                    <strong>Submitted:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>Target Completion:</strong> " . date('F j, Y', strtotime('+5 weekdays')) . "
                                </p>
                            </div>

                            <!-- Support Section -->
                            <div class='support-section'>
                                <p class='support-text'>Document requires verification within SLA.</p>
                                <p class='support-text'>User awaiting account limit upgrades.</p>
                            </div>
                        </div>";

    // Send admin notification
    require_once("../proccess/admin_mailer.php");
    
    echo '<script>showToast("Success!", "Identity document uploaded successfully!", "success");</script>';
    echo '<script>setTimeout(() => location.reload(), 1500);</script>';
} else {
    // Delete uploaded file if DB insert failed
    unlink($filepath);
    echo '<script>showToast("Error!", "Database error: ' . mysqli_error($conn) . '", "danger");</script>';
}

// Helper function to format file size
function format_file_size($bytes) {
    if ($bytes >= 1073741824) {
        return number_format($bytes / 1073741824, 2) . ' GB';
    } elseif ($bytes >= 1048576) {
        return number_format($bytes / 1048576, 2) . ' MB';
    } elseif ($bytes >= 1024) {
        return number_format($bytes / 1024, 2) . ' KB';
    } else {
        return $bytes . ' bytes';
    }
}
?>