<?php
session_start();
include 'config.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, kyc_status FROM users WHERE id='$user_id'");
$userData = mysqli_fetch_assoc($userQuery);
$first_name = $userData['first_name'];
$last_name = $userData['last_name'];
$email = $userData['email'];
$current_kyc_status = $userData['kyc_status'];

// Check if both documents are uploaded
$documents_sql = "SELECT COUNT(*) as count, 
                  GROUP_CONCAT(CONCAT(document_type, ' (', document_number, ')') SEPARATOR ', ') as document_list,
                  GROUP_CONCAT(document_type SEPARATOR ', ') as document_types
                  FROM kyc_documents 
                  WHERE user_id = '$user_id' 
                  AND verification_status = 'pending'";
$documents_result = mysqli_query($conn, $documents_sql);
$documents = mysqli_fetch_assoc($documents_result);

if ($documents['count'] < 2) {
    echo '<script>showToast("Error!", "Please upload both identity and address documents first.", "danger");</script>';
    exit;
}

// Get document details for notification
$doc_details_sql = "SELECT document_type, document_number, document_name, uploaded_at 
                    FROM kyc_documents 
                    WHERE user_id = '$user_id' 
                    AND verification_status = 'pending' 
                    ORDER BY document_type";
$doc_details_result = mysqli_query($conn, $doc_details_sql);
$document_details = [];
while ($row = mysqli_fetch_assoc($doc_details_result)) {
    $document_details[] = $row;
}

// Mark documents as submitted
$update_sql = "UPDATE kyc_documents 
               SET verification_status = 'submitted', 
                   submitted_at = NOW()
               WHERE user_id = '$user_id' 
               AND verification_status = 'pending'";
if (mysqli_query($conn, $update_sql)) {
    
    // Update user KYC status
    mysqli_query($conn, "UPDATE users SET kyc_status = 'submitted', kyc_submitted_at = NOW() WHERE id = '$user_id'");
    
    // NOTIFICATION: KYC Submitted (USER)
    $mail_subject = "KYC Verification Submitted";
    $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 verification has been successfully submitted!</strong><br>
                            We have received your documents and will review them shortly.
                        </p>

                        <!-- Submission Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Submission Reference:</strong> KYC-" . date('Ymd') . "-" . strtoupper(substr(md5($user_id . time()), 0, 6)) . "<br>
                                <strong>Submitted Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Previous KYC Status:</strong> " . ucfirst($current_kyc_status) . "<br>
                                <strong>New KYC Status:</strong> <span style='color: #ffc107; font-weight: bold;'>SUBMITTED</span><br>
                                <strong>User ID:</strong> " . $user_id . "<br>
                                <strong>Total Documents Submitted:</strong> " . $documents['count'] . "
                            </div>
                        </div>

                        <!-- Document Details -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>📄 Submitted Documents</h3>";
    
    foreach ($document_details as $doc) {
        $mail_message .= "<div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 6px; padding: 15px; margin: 10px 0;'>
                            <strong>" . ucfirst(str_replace('_', ' ', $doc['document_type'])) . ":</strong><br>
                            Document: " . htmlspecialchars($doc['document_name']) . "<br>
                            Number: " . ($doc['document_number'] ? htmlspecialchars($doc['document_number']) : 'N/A') . "<br>
                            Uploaded: " . date('F j, Y g:i A', strtotime($doc['uploaded_at'])) . "
                          </div>";
    }
    
    $mail_message .= "</div>

                        <!-- Verification Timeline -->
                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0056b3;'>⏰ Verification Timeline</h4>
                            <p style='color: #0056b3;'>
                                <strong>Expected Review Time:</strong> 1-3 business days<br>
                                <strong>Current Status:</strong> In Review Queue<br>
                                <strong>Priority:</strong> Standard<br>
                                <strong>Working Hours:</strong> Mon-Fri, 9 AM - 5 PM (GMT)<br>
                                <strong>Estimated Completion:</strong> " . date('F j', strtotime('+3 weekdays')) . "
                            </p>
                        </div>

                        <!-- What Happens Next -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>🔍 Verification Process</h3>
                            <p style='color: #6c757d;'>Our verification team will:</p>
                            <ol style='color: #6c757d;'>
                                <li>Check document authenticity and validity</li>
                                <li>Verify personal information matches</li>
                                <li>Validate document expiration dates</li>
                                <li>Cross-check with databases (where applicable)</li>
                                <li>Mark verification as complete</li>
                            </ol>
                        </div>

                        <!-- While You Wait -->
                        <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #155724;'>📊 While You Wait</h4>
                            <p style='color: #155724;'>
                                You can still:<br>
                                • Browse trading bots and features<br>
                                • Set up your account preferences<br>
                                • Learn about our trading strategies<br>
                                • Deposit funds (some limits may apply)<br>
                                • Complete other profile sections
                            </p>
                        </div>

                        <!-- KYC Benefits -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>✅ Benefits of Verified KYC</h3>
                            <p style='color: #6c757d;'>Once verified, you'll enjoy:</p>
                            <ul style='color: #6c757d;'>
                                <li>Higher withdrawal limits</li>
                                <li>Faster deposit processing</li>
                                <li>Access to premium trading bots</li>
                                <li>Increased security for your account</li>
                                <li>Priority customer support</li>
                                <li>Full platform functionality</li>
                            </ul>
                        </div>

                        <!-- Action Buttons -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/dashboard.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;'>
                                Go to Dashboard
                            </a>
                            <a href='" . $myUrl . "/support.php?category=kyc' 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;'>
                                KYC Support
                            </a>
                        </div>

                        <!-- Important Notes -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>📝 Important Notes</h4>
                            <ul style='color: #856404;'>
                                <li>Do NOT submit additional documents unless requested</li>
                                <li>Keep your contact information up to date</li>
                                <li>We may request additional information if needed</li>
                                <li>You will receive email updates on your verification status</li>
                                <li>Contact support if verification takes longer than 3 days</li>
                            </ul>
                        </div>

                        <!-- Support Section -->
                        <div class='support-section'>
                            <p class='support-text'>Questions about KYC verification?</p>
                            <a href='" . $myUrl . "/support.php?category=kyc' class='support-link'>Contact KYC Support Team</a>
                        </div>
                    </div>";

    // Send user notification
    include("mail_sender.php");

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

                            <!-- User Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>User ID:</strong> " . $user_id . "<br>
                                    <strong>User Name:</strong> " . $first_name . " " . $last_name . "<br>
                                    <strong>User Email:</strong> " . $email . "<br>
                                    <strong>Submission Reference:</strong> KYC-" . date('Ymd') . "-" . strtoupper(substr(md5($user_id . time()), 0, 6)) . "<br>
                                    <strong>Submitted Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>Previous KYC Status:</strong> " . ucfirst($current_kyc_status) . "<br>
                                    <strong>New Status:</strong> <span style='color: #ffc107; font-weight: bold;'>SUBMITTED</span><br>
                                    <strong>Total Documents:</strong> " . $documents['count'] . "<br>
                                    <strong>Document Types:</strong> " . $documents['document_types'] . "
                                </div>
                            </div>

                            <!-- Document Details -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>Submitted Documents</h3>";
    
    foreach ($document_details as $doc) {
        $admin_mail_message .= "<div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 6px; padding: 10px; margin: 8px 0; font-size: 14px;'>
                                  <strong>" . ucfirst($doc['document_type']) . ":</strong> " . htmlspecialchars($doc['document_name']) . 
                                  ($doc['document_number'] ? " (" . htmlspecialchars($doc['document_number']) . ")" : "") . "
                                </div>";
    }
    
    $admin_mail_message .= "</div>

                            <!-- User Account Info -->
                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0056b3;'>👤 User Account Information</h4>
                                <p style='color: #0056b3;'>
                                    <strong>Account Created:</strong> " . (isset($userData['created_at']) ? date('F j, Y', strtotime($userData['created_at'])) : 'N/A') . "<br>
                                    <strong>Email Verified:</strong> " . (isset($userData['email_verified']) && $userData['email_verified'] == 1 ? 'Yes' : 'No') . "<br>
                                    <strong>2FA Enabled:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT two_factor_enabled FROM user_security WHERE user_id='$user_id'"))['two_factor_enabled'] ?? 0 ? 'Yes' : 'No') . "<br>
                                    <strong>Total Deposits:</strong> $" . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT SUM(amount) as total FROM transactions WHERE user_id='$user_id' AND type='deposit' 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 Priority -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>Verification Priority</h3>
                                <p style='color: #6c757d;'>
                                    <strong>Priority Level:</strong> Standard<br>
                                    <strong>Suggested Action:</strong> Review within 24 hours<br>
                                    <strong>Risk Level:</strong> " . 
                                        ((isset($userData['created_at']) && (time() - strtotime($userData['created_at'])) > 30*24*60*60) ? 'LOW' : 'MEDIUM') . "<br>
                                    <strong>Account Age:</strong> " . 
                                        (isset($userData['created_at']) ? round((time() - strtotime($userData['created_at'])) / (60 * 60 * 24)) . ' days' : 'N/A') . "
                                </p>
                            </div>

                            <!-- Admin Actions -->
                            <div style='text-align: center; margin: 30px 0;'>
                                <a href='" . $myUrl . "/admin/kyc-verification.php?user_id=" . $user_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 KYC Documents
                                </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>
                            </div>

                            <!-- Verification SLA -->
                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #856404;'>⏰ SLA Information</h4>
                                <p style='color: #856404;'>
                                    <strong>Standard Review Time:</strong> 1-3 business days<br>
                                    <strong>Current Queue Position:</strong> To be determined<br>
                                    <strong>Assigned To:</strong> Unassigned<br>
                                    <strong>Due Date:</strong> " . date('F j, Y', strtotime('+3 weekdays')) . "
                                </p>
                            </div>

                            <!-- Notes -->
                            <div class='support-section'>
                                <p class='support-text'>Please review this KYC submission promptly.</p>
                                <p class='support-text'>User is awaiting verification to access full features.</p>
                            </div>
                        </div>";

    // Send admin notification
    include("admin_mailer.php");
    
    echo '<script>showToast("Success!", "Verification submitted! We will review within 1-3 business days.", "success");</script>';
    echo '<script>setTimeout(() => location.reload(), 1500);</script>';
} else {
    echo '<script>showToast("Error!", "Database error: ' . mysqli_error($conn) . '", "danger");</script>';
}
?>