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

if (!isset($_SESSION['user_id'])) {
    die(json_encode(['success' => false, 'message' => 'Not authenticated']));
}

$user_id = $_SESSION['user_id'];
$pin = isset($_POST['pin']) ? $conn->real_escape_string($_POST['pin']) : '';

if (empty($pin) || strlen($pin) != 4 || !is_numeric($pin)) {
    die(json_encode(['success' => false, 'message' => 'Invalid PIN']));
}

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

// Get wallet information
$walletQuery = mysqli_query($conn, "SELECT * FROM wallets WHERE user_id='$user_id'");
$walletData = mysqli_fetch_assoc($walletQuery);
$current_balance = isset($walletData['balance']) ? floatval($walletData['balance']) : 0;

// Get IP address for security notification
$user_ip = $_SERVER['REMOTE_ADDR'];
$user_agent = $_SERVER['HTTP_USER_AGENT'];
$browser = get_browser_name($user_agent);
$device = is_mobile_device() ? 'Mobile' : 'Desktop';

// Hash the PIN for security
$hashed_pin = password_hash($pin, PASSWORD_DEFAULT);

$sql = "UPDATE wallets SET wallet_pin = '$hashed_pin', is_pin_set = 1 WHERE user_id = '$user_id'";

if (mysqli_query($conn, $sql)) {
    
    // NOTIFICATION: Wallet PIN Set Successfully (USER)
    $mail_subject = "Wallet Security PIN Set 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 wallet security PIN has been set successfully!</strong><br>
                            Your wallet is now protected with an additional layer of security.
                        </p>

                        <!-- Security Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Security Action:</strong> Wallet PIN Setup<br>
                                <strong>Date & Time:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Current Wallet Balance:</strong> $" . number_format($current_balance, 2) . "<br>
                                <strong>PIN Status:</strong> <span style='color: #28a745; font-weight: bold;'>ACTIVE</span><br>
                                <strong>PIN Type:</strong> 4-digit numeric<br>
                                <strong>Setup Location:</strong> " . $user_ip . "<br>
                                <strong>Device:</strong> " . $device . " (" . $browser . ")
                            </div>
                        </div>

                        <!-- Security Importance -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>🔒 Why Wallet PIN is Important</h4>
                            <ul style='color: #856404;'>
                                <li>Required for all withdrawals and transfers</li>
                                <li>Protects against unauthorized transactions</li>
                                <li>Adds an extra layer of security beyond password</li>
                                <li>Required for sensitive wallet operations</li>
                            </ul>
                        </div>

                        <!-- What Your PIN Protects -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>What Your PIN Protects</h3>
                            <p style='color: #6c757d;'>Your wallet PIN will be required for:</p>
                            <ul style='color: #6c757d;'>
                                <li>Withdrawing funds from your wallet</li>
                                <li>Transferring funds to other users</li>
                                <li>Changing wallet settings</li>
                                <li>Viewing transaction history details</li>
                                <li>Exporting wallet statements</li>
                            </ul>
                        </div>

                        <!-- Important Security Notes -->
                        <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #721c24;'>⚠️ IMPORTANT SECURITY NOTES</h4>
                            <ul style='color: #721c24;'>
                                <li><strong>NEVER share your PIN with anyone</strong></li>
                                <li><strong>" . $sitename . " staff will NEVER ask for your PIN</strong></li>
                                <li>Do not use easy-to-guess PINs (1234, 0000, etc.)</li>
                                <li>Change your PIN regularly for maximum security</li>
                                <li>If you forget your PIN, use the PIN reset process</li>
                            </ul>
                        </div>

                        <!-- Action Buttons -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/wallet.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 Wallet
                            </a>
                            <a href='" . $myUrl . "/security.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;'>
                                Security Settings
                            </a>
                        </div>

                        <!-- Support Section -->
                        <div class='support-section'>
                            <p class='support-text'>If you did not set up this PIN, please contact support immediately!</p>
                            <a href='" . $myUrl . "/support.php?category=security' class='support-link'>Contact Security Team</a>
                        </div>
                    </div>";

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

    // NOTIFICATION: Wallet PIN Set (ADMIN - Security Alert)
    $admin_mail_subject = "Security Alert: Wallet PIN Set - User ID: " . $user_id;
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Security Alert: Wallet PIN Set</h2>
                            
                            <p class='message'>
                                A user has set up their wallet security PIN. This is a standard security notification.
                            </p>

                            <!-- User & Security 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> Wallet PIN Setup<br>
                                    <strong>Date & Time:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>User IP Address:</strong> " . $user_ip . "<br>
                                    <strong>Location:</strong> " . get_location_from_ip($user_ip) . "<br>
                                    <strong>Device:</strong> " . $device . "<br>
                                    <strong>Browser:</strong> " . $browser . "<br>
                                    <strong>Wallet Balance:</strong> $" . number_format($current_balance, 2) . "<br>
                                    <strong>PIN Status:</strong> Active
                                </div>
                            </div>

                            <!-- Security Risk Assessment -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>Security Assessment</h3>
                                <p style='color: #6c757d;'>
                                    <strong>Risk Level:</strong> <span style='color: #28a745;'>LOW</span><br>
                                    <strong>Action Type:</strong> Standard security setup<br>
                                    <strong>User Behavior:</strong> Normal security practice<br>
                                    <strong>Previous PIN Status:</strong> " . (isset($walletData['is_pin_set']) && $walletData['is_pin_set'] == 1 ? 'Already Set' : 'Not Set') . "<br>
                                    <strong>Account Age:</strong> " . (isset($userData['created_at']) ? 
                                        round((time() - strtotime($userData['created_at'])) / (60 * 60 * 24)) . ' days' : 'N/A') . "
                                </p>
                            </div>

                            <!-- Recent Security Activities -->
                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0056b3;'>📋 Recent Security Activities</h4>
                                <p style='color: #0056b3;'>
                                    Last login: " . (isset($userData['last_login']) ? date('F j, Y g:i A', strtotime($userData['last_login'])) : 'N/A') . "<br>
                                    Total successful logins: " . (isset($userData['login_count']) ? $userData['login_count'] : 0) . "<br>
                                    2FA Status: " . (isset($userData['two_factor_enabled']) && $userData['two_factor_enabled'] == 1 ? 'Enabled' : 'Disabled') . "<br>
                                    Email verified: " . (isset($userData['email_verified']) && $userData['email_verified'] == 1 ? 'Yes' : 'No') . "
                                </p>
                            </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/security-logs.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 Security Logs
                                </a>
                            </div>

                            <!-- Security Notes -->
                            <div class='support-section'>
                                <p class='support-text'>This is an automated security notification.</p>
                                <p class='support-text'>No action required unless suspicious activity is detected.</p>
                            </div>
                        </div>";

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

    echo json_encode(['success' => true, 'message' => 'PIN set successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . mysqli_error($conn)]);
}

// Helper functions for device/browser detection
function get_browser_name($user_agent) {
    if (strpos($user_agent, 'Chrome') !== false) return 'Chrome';
    if (strpos($user_agent, 'Firefox') !== false) return 'Firefox';
    if (strpos($user_agent, 'Safari') !== false) return 'Safari';
    if (strpos($user_agent, 'Edge') !== false) return 'Edge';
    if (strpos($user_agent, 'Opera') !== false) return 'Opera';
    return 'Unknown Browser';
}

function is_mobile_device() {
    $mobile_agents = array(
        'Android', 'webOS', 'iPhone', 'iPad', 'iPod', 'BlackBerry', 
        'Windows Phone', 'Mobile', 'Tablet'
    );
    
    foreach ($mobile_agents as $agent) {
        if (stripos($_SERVER['HTTP_USER_AGENT'], $agent) !== false) {
            return true;
        }
    }
    return false;
}

function get_location_from_ip($ip) {
    // Simple IP location - in production, use a proper IP geolocation service
    if ($ip == '127.0.0.1' || $ip == '::1') {
        return 'Localhost';
    }
    
    // You can implement proper IP geolocation here
    // For now, return a generic location
    return 'Location data not available';
}
?>