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

$required = ['current_pin', 'new_pin', 'confirm_new_pin'];
foreach ($required as $field) {
    if (empty($_POST[$field])) {
        echo json_encode(['success' => false, 'message' => "Missing required field: $field"]);
        exit;
    }
}

$current_pin = $_POST['current_pin'];
$new_pin = $_POST['new_pin'];
$confirm_new_pin = $_POST['confirm_new_pin'];

// Validate new PIN
if (!preg_match('/^\d{6}$/', $new_pin)) {
    echo json_encode(['success' => false, 'message' => 'New PIN must be exactly 6 digits']);
    exit;
}

if ($new_pin !== $confirm_new_pin) {
    echo json_encode(['success' => false, 'message' => 'New PINs do not match']);
    exit;
}

// 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'];
$email = $userData['email'];

// 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';

// Get current PIN
$sql = "SELECT withdrawal_pin, updated_at FROM user_security WHERE user_id = '$user_id'";
$result = mysqli_query($conn, $sql);
$security = mysqli_fetch_assoc($result);

if (!$security || empty($security['withdrawal_pin'])) {
    echo json_encode(['success' => false, 'message' => 'No PIN set. Please set a PIN first.']);
    exit;
}

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

// Verify current PIN
if (!password_verify($current_pin, $security['withdrawal_pin'])) {
    // Log failed attempt
    $failed_attempt_sql = "INSERT INTO security_logs 
                          (user_id, action, ip_address, user_agent, status, created_at)
                          VALUES 
                          ('$user_id', 'withdrawal_pin_change_failed', '$user_ip', '$user_agent', 'failed', NOW())";
    mysqli_query($conn, $failed_attempt_sql);
    
    // Check for multiple failed attempts
    $recent_fails_sql = "SELECT COUNT(*) as fail_count FROM security_logs 
                         WHERE user_id='$user_id' AND action LIKE 'withdrawal_pin_change%' 
                         AND status='failed' AND created_at >= DATE_SUB(NOW(), INTERVAL 1 HOUR)";
    $recent_fails_result = mysqli_query($conn, $recent_fails_sql);
    $recent_fails = mysqli_fetch_assoc($recent_fails_result)['fail_count'];
    
    // Send security alert if multiple failed attempts
    if ($recent_fails >= 3) {
        $admin_mail_subject = "Security Alert: Multiple Failed PIN Change Attempts - User ID: " . $user_id;
        $admin_mail_message = "<!-- Content Section -->
                            <div class='email-content'>
                                <h2 class='greeting'>🚨 SECURITY ALERT: Multiple Failed PIN Changes</h2>
                                
                                <p class='message'>
                                    User has attempted to change withdrawal PIN multiple times with incorrect current PIN.
                                </p>

                                <!-- Alert Details -->
                                <div class='details-section'>
                                    <div class='detail-box'>
                                        <strong>User ID:</strong> " . $user_id . "<br>
                                        <strong>User Name:</strong> " . $first_name . " " . $userData['last_name'] . "<br>
                                        <strong>User Email:</strong> " . $email . "<br>
                                        <strong>Failed Attempts (Last Hour):</strong> " . $recent_fails . "<br>
                                        <strong>Current Wallet Balance:</strong> $" . number_format($wallet_balance, 2) . "<br>
                                        <strong>IP Address:</strong> " . $user_ip . "<br>
                                        <strong>Device:</strong> " . $device . " (" . $browser . ")<br>
                                        <strong>Alert Time:</strong> " . date('F j, Y g:i A') . "<br>
                                        <strong>Risk Level:</strong> <span style='color: #dc3545; font-weight: bold;'>HIGH</span>
                                    </div>
                                </div>

                                <!-- Recommended Actions -->
                                <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                    <h4 style='color: #721c24;'>🚨 RECOMMENDED ACTIONS</h4>
                                    <ul style='color: #721c24;'>
                                        <li>Temporarily freeze withdrawals for this account</li>
                                        <li>Contact user to verify identity</li>
                                        <li>Review recent login activity</li>
                                        <li>Check for suspicious IP patterns</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: #dc3545; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                        🔒 Freeze Account
                                    </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>

                                <!-- Support Section -->
                                <div class='support-section'>
                                    <p class='support-text'>This is a HIGH priority security alert!</p>
                                    <a href='" . $myUrl . "/admin/emergency.php' class='support-link'>Emergency Response Protocol</a>
                                </div>
                            </div>";

        require_once("../proccess/admin_mailer.php");
    }
    
    echo json_encode(['success' => false, 'message' => 'Current PIN is incorrect']);
    exit;
}

// Hash new PIN
$hashed_pin = password_hash($new_pin, PASSWORD_DEFAULT);

$update_sql = "UPDATE user_security SET 
               withdrawal_pin = '$hashed_pin',
               updated_at = NOW()
               WHERE user_id = '$user_id'";

if (mysqli_query($conn, $update_sql)) {
    
    // Log successful PIN change
    $log_sql = "INSERT INTO security_logs 
                (user_id, action, ip_address, user_agent, status, created_at)
                VALUES 
                ('$user_id', 'withdrawal_pin_changed', '$user_ip', '$user_agent', 'success', NOW())";
    mysqli_query($conn, $log_sql);
    
    // NOTIFICATION: Withdrawal PIN Changed Successfully (USER)
    $mail_subject = "Security Alert: Withdrawal PIN Changed";
    $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 withdrawal PIN has been changed successfully!</strong><br>
                            This is a security confirmation for your records.
                        </p>

                        <!-- Security Change Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Security Action:</strong> Withdrawal PIN Change<br>
                                <strong>Change Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Previous PIN Last Changed:</strong> " . 
                                    (isset($security['updated_at']) ? date('F j, Y', strtotime($security['updated_at'])) : 'First time setup') . "<br>
                                <strong>Wallet Balance:</strong> $" . number_format($wallet_balance, 2) . "<br>
                                <strong>Change Location:</strong> " . $user_ip . "<br>
                                <strong>Device:</strong> " . $device . " (" . $browser . ")<br>
                                <strong>PIN Type:</strong> 6-digit numeric<br>
                                <strong>Change Status:</strong> <span style='color: #28a745; font-weight: bold;'>COMPLETED</span>
                            </div>
                        </div>

                        <!-- Security Impact -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>🔐 What This Means For Your Account</h4>
                            <ul style='color: #856404;'>
                                <li>All future withdrawals will require the new PIN</li>
                                <li>Old PIN is no longer valid for withdrawals</li>
                                <li>Transfers and sensitive actions now use new PIN</li>
                                <li>PIN reset requests will now reference new PIN</li>
                            </ul>
                        </div>

                        <!-- Security Recommendations -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>💡 Security Best Practices</h3>
                            <p style='color: #6c757d;'>To keep your account secure:</p>
                            <ul style='color: #6c757d;'>
                                <li>Never share your PIN with anyone</li>
                                <li>Don't use obvious PINs (123456, birth dates, etc.)</li>
                                <li>Change your PIN every 3-6 months</li>
                                <li>Use different PINs for different services</li>
                                <li>Enable two-factor authentication if not already</li>
                            </ul>
                        </div>

                        <!-- Important Warning -->
                        <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #721c24;'>🚨 CRITICAL SECURITY WARNING</h4>
                            <p style='color: #721c24;'>
                                <strong>If you did NOT change your withdrawal PIN:</strong><br>
                                • Your account may be compromised<br>
                                • <strong>Contact support IMMEDIATELY</strong><br>
                                • Change your account password<br>
                                • Enable two-factor authentication<br>
                                • Review recent account activity
                            </p>
                        </div>

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

                        <!-- Support Section -->
                        <div class='support-section'>
                            <p class='support-text'>If you have any concerns about this change, contact us immediately!</p>
                            <a href='" . $myUrl . "/support.php?category=security&urgent=1' class='support-link'>🚨 Contact Security Team</a>
                        </div>
                    </div>";

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

    // NOTIFICATION: Withdrawal PIN Changed (ADMIN - Security Alert)
    $admin_mail_subject = "Security Notification: Withdrawal PIN Changed - User ID: " . $user_id;
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Security Notification: Withdrawal PIN Change</h2>
                            
                            <p class='message'>
                                A user has successfully changed their withdrawal PIN.
                            </p>

                            <!-- Change Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>User ID:</strong> " . $user_id . "<br>
                                    <strong>User Name:</strong> " . $first_name . " " . $userData['last_name'] . "<br>
                                    <strong>User Email:</strong> " . $email . "<br>
                                    <strong>Action:</strong> Withdrawal PIN Change<br>
                                    <strong>Change Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>IP Address:</strong> " . $user_ip . "<br>
                                    <strong>Device:</strong> " . $device . " (" . $browser . ")<br>
                                    <strong>Wallet Balance:</strong> $" . number_format($wallet_balance, 2) . "<br>
                                    <strong>Previous PIN Age:</strong> " . 
                                        (isset($security['updated_at']) ? 
                                            round((time() - strtotime($security['updated_at'])) / (60 * 60 * 24)) . ' days' : 'First setup') . "<br>
                                    <strong>Account Status:</strong> Active
                                </div>
                            </div>

                            <!-- Security Assessment -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>🔍 Security Assessment</h3>
                                <p style='color: #6c757d;'>
                                    <strong>Risk Level:</strong> <span style='color: #28a745;'>NORMAL</span><br>
                                    <strong>User Behavior:</strong> Proactive security maintenance<br>
                                    <strong>Change Frequency:</strong> " . 
                                        (isset($security['updated_at']) ? 
                                            round((time() - strtotime($security['updated_at'])) / (60 * 60 * 24)) . ' days since last change' : 'First change') . "<br>
                                    <strong>Recent Activity:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as logins FROM login_logs 
                                             WHERE user_id='$user_id' AND created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)"))['logins'] ?? 0) . " logins (7 days)<br>
                                    <strong>2FA Status:</strong> " . 
                                        (isset($userData['two_factor_enabled']) && $userData['two_factor_enabled'] == 1 ? 'Enabled' : 'Disabled') . "
                                </p>
                            </div>

                            <!-- Suspicious Activity Check -->
                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0056b3;'>🕵️ Suspicious Activity Indicators</h4>
                                <p style='color: #0056b3;'>
                                    Check for:<br>
                                    • Unusual login locations<br>
                                    • Multiple failed PIN attempts<br>
                                    • Recent password reset<br>
                                    • High-value withdrawal patterns
                                </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>

                            <!-- Notes -->
                            <div class='support-section'>
                                <p class='support-text'>This is a standard 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' => 'Withdrawal PIN changed 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;
}
?>