<?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, verification_submitted, verification_completed FROM users WHERE id='$user_id'");
$userData = mysqli_fetch_assoc($userQuery);
$first_name = $userData['first_name'];
$last_name = $userData['last_name'];
$email = $userData['email'];
$previous_status = $userData['verification_submitted'] ? 'Submitted' : 'Not Submitted';
$previous_completion = $userData['verification_completed'] ? 'Completed' : 'Pending';

// Get KYC document info before archive
$kycQuery = mysqli_query($conn, "SELECT COUNT(*) as doc_count, GROUP_CONCAT(document_type) as doc_types FROM kyc_documents WHERE user_id = '$user_id' AND verification_status != 'archived'");
$kycData = mysqli_fetch_assoc($kycQuery);
$doc_count = $kycData['doc_count'];
$doc_types = $kycData['doc_types'] ? explode(',', $kycData['doc_types']) : [];

// Get IP address and device info
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$device = get_device_type($user_agent);

// Archive existing documents
$archive_sql = "UPDATE kyc_documents 
                SET verification_status = 'archived'
                WHERE user_id = '$user_id'";
if (mysqli_query($conn, $archive_sql)) {
    $affected_rows = mysqli_affected_rows($conn);
    
    // Reset user verification status
    mysqli_query($conn, "UPDATE users SET verification_submitted = 0, verification_completed = 0 WHERE id = '$user_id'");
    
    // Record KYC restart in audit log
    $audit_description = "KYC verification restarted. Archived $affected_rows documents. Previous status: $previous_status";
    mysqli_query($conn, 
        "INSERT INTO audit_logs 
        (user_id, action_type, description, ip_address, user_agent, created_at) 
        VALUES 
        ('$user_id', 'kyc_restart', '$audit_description', '$user_ip', '$user_agent', NOW())");
    
    // NOTIFICATION: KYC Verification Restarted (USER)
    $mail_subject = "KYC Verification Restarted - Action Required";
    $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 process has been restarted.</strong><br>
                            You need to upload new documents to complete your verification.
                        </p>

                        <!-- Restart Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Action:</strong> KYC Verification Restarted<br>
                                <strong>Restart Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Previous Status:</strong> " . $previous_status . " (" . $previous_completion . ")<br>
                                <strong>Archived Documents:</strong> " . $affected_rows . " documents<br>
                                <strong>Document Types Archived:</strong> " . (!empty($doc_types) ? implode(', ', array_unique($doc_types)) : 'None') . "<br>
                                <strong>Restarted From IP:</strong> " . $user_ip . "<br>
                                <strong>Device:</strong> " . $device . "<br>
                                <strong>Current Verification Status:</strong> <span style='color: #ffc107; font-weight: bold;'>NOT SUBMITTED</span>
                            </div>
                        </div>

                        <!-- Why Restart Happened -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>ℹ️ Reason for Restart</h4>
                            <p style='color: #856404;'>
                                KYC verification was restarted because:<br>
                                1. Previous documents were incomplete or unclear<br>
                                2. You requested to upload different documents<br>
                                3. Documents needed to be updated<br>
                                4. Verification requirements have changed
                            </p>
                        </div>

                        <!-- What You Need to Do -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>📋 Action Required</h3>
                            <p style='color: #6c757d;'>To complete your verification, please:</p>
                            <ol style='color: #6c757d;'>
                                <li>Prepare clear, valid documents</li>
                                <li>Upload required documents in KYC section</li>
                                <li>Ensure documents are not expired</li>
                                <li>Submit for verification review</li>
                                <li>Wait 24-48 hours for processing</li>
                            </ol>
                        </div>

                        <!-- Required Documents -->
                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0056b3;'>📄 Required Documents</h4>
                            <p style='color: #0056b3;'>
                                <strong>Identity Verification (Choose one):</strong><br>
                                • Passport<br>
                                • National ID card<br>
                                • Driver's license<br><br>
                                
                                <strong>Address Verification (Choose one):</strong><br>
                                • Utility bill (last 3 months)<br>
                                • Bank statement (last 3 months)<br>
                                • Government-issued address proof
                            </p>
                        </div>

                        <!-- Document Guidelines -->
                        <div style='background: #d4edda; border: 1px solid #c3e6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #155724;'>✅ Document Guidelines</h4>
                            <ul style='color: #155724;'>
                                <li>All documents must be in color</li>
                                <li>All four corners must be visible</li>
                                <li>Text must be clear and readable</li>
                                <li>No glare or reflections</li>
                                <li>File size under 5MB per document</li>
                                <li>Accepted formats: JPG, PNG, PDF</li>
                            </ul>
                        </div>

                        <!-- What Happens Next -->
                        <div style='background: #f8f9fa; border: 1px solid #e9ecef; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #6c757d;'>⏱️ Processing Timeline</h4>
                            <p style='color: #6c757d;'>
                                <strong>After submission:</strong><br>
                                • Review: 24-48 hours<br>
                                • Approval notification: Email & dashboard<br>
                                • Full access: Immediately after approval<br>
                                • Delays: If documents need clarification
                            </p>
                        </div>

                        <!-- Action Buttons -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/kyc-verification.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;'>
                                Upload Documents Now
                            </a>
                            <a href='" . $myUrl . "/help/kyc-requirements.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 KYC Requirements
                            </a>
                        </div>

                        <!-- Important Notes -->
                        <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #721c24;'>⚠️ Important Notes</h4>
                            <ul style='color: #721c24;'>
                                <li><strong>Without KYC verification, withdrawal limits apply</strong></li>
                                <li>You cannot trade with maximum limits until verified</li>
                                <li>Archived documents are securely stored for 7 years</li>
                                <li>Multiple failed submissions may delay verification</li>
                            </ul>
                        </div>

                        <!-- Support Section -->
                        <div class='support-section'>
                            <p class='support-text'>Need help with KYC 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: KYC Restarted (ADMIN)
    $admin_mail_subject = "KYC Verification Restarted - User ID: " . $user_id;
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>KYC Verification Restarted</h2>
                            
                            <p class='message'>
                                A user has restarted their KYC verification process.
                            </p>

                            <!-- User & KYC 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>Action:</strong> KYC Verification Restarted<br>
                                    <strong>Restart Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>User IP Address:</strong> " . $user_ip . "<br>
                                    <strong>Device:</strong> " . $device . "<br>
                                    <strong>Previous Status:</strong> " . $previous_status . " (" . $previous_completion . ")<br>
                                    <strong>Documents Archived:</strong> " . $affected_rows . " documents<br>
                                    <strong>Document Types:</strong> " . (!empty($doc_types) ? implode(', ', array_unique($doc_types)) : 'None') . "<br>
                                    <strong>New Status:</strong> <span style='color: #ffc107; font-weight: bold;'>Not Submitted</span>
                                </div>
                            </div>

                            <!-- User History -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>User Verification History</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>Previous KYC Attempts:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(DISTINCT DATE(created_at)) as attempts FROM kyc_documents WHERE user_id='$user_id'"))['attempts'] ?? 1) . "<br>
                                    <strong>Total Documents Uploaded:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as total FROM kyc_documents WHERE user_id='$user_id'"))['total'] ?? 0) . "<br>
                                    <strong>Last Submission:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT MAX(created_at) as last_submit FROM kyc_documents WHERE user_id='$user_id' AND verification_status != 'archived'"))['last_submit'] ?? 'Never') . "
                                </p>
                            </div>

                            <!-- Possible Reasons -->
                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0056b3;'>🤔 Possible Reasons for Restart</h4>
                                <ul style='color: #0056b3;'>
                                    <li>Previous documents rejected/expired</li>
                                    <li>User wants to upload better quality documents</li>
                                    <li>Changed personal information (name, address)</li>
                                    <li>Document requirements changed</li>
                                    <li>User confusion about requirements</li>
                                </ul>
                            </div>

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

                            <!-- Notes -->
                            <div class='support-section'>
                                <p class='support-text'>User will need to submit new documents for verification.</p>
                                <p class='support-text'>Monitor for multiple restarts which may indicate issues.</p>
                            </div>
                        </div>";

    // Send admin notification
    require_once("../proccess/admin_mailer.php");

    echo '<script>showToast("Success!", "Verification restarted. You can now upload new documents.", "success");</script>';
    echo '<script>setTimeout(() => location.reload(), 1500);</script>';
} else {
    echo '<script>showToast("Error!", "Database error: ' . mysqli_error($conn) . '", "danger");</script>';
}

// Helper function
function get_device_type($user_agent) {
    if (stripos($user_agent, 'Mobile') !== false) {
        return 'Mobile';
    } elseif (stripos($user_agent, 'Tablet') !== false) {
        return 'Tablet';
    } else {
        return 'Desktop';
    }
}
?>