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

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

$current_password = $_POST['current'];
$new_password = $_POST['new'];

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

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

// Verify current password
$sql = "SELECT password FROM users WHERE id = '$user_id'";
$result = mysqli_query($conn, $sql);
$user = mysqli_fetch_assoc($result);

if (!password_verify($current_password, $user['password'])) {
    // Log failed password change attempt
    $failed_log = "Failed password change attempt - Incorrect current password";
    mysqli_query($conn, 
        "INSERT INTO security_logs 
        (user_id, action, ip_address, user_agent, status, details, created_at)
        VALUES 
        ('$user_id', 'password_change_failed', '$user_ip', '$user_agent', 'failed', '$failed_log', NOW())");
    
    echo json_encode(['success' => false, 'message' => 'Current password is incorrect']);
    exit;
}

// Validate new password
if (strlen($new_password) < 8) {
    echo json_encode(['success' => false, 'message' => 'New password must be at least 8 characters']);
    exit;
}

// Check if new password is same as old
if (password_verify($new_password, $user['password'])) {
    echo json_encode(['success' => false, 'message' => 'New password cannot be same as current password']);
    exit;
}

// Hash new password
$hashed_password = password_hash($new_password, PASSWORD_DEFAULT);

// Update password
$update_sql = "UPDATE users SET password = '$hashed_password', updated_at = NOW() WHERE id = '$user_id'";

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

                        <!-- Security Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Security Action:</strong> Password Change<br>
                                <strong>Date & Time:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Account Email:</strong> " . htmlspecialchars($email) . "<br>
                                <strong>Account User:</strong> " . $first_name . " " . $last_name . "<br>
                                <strong>Changed From IP:</strong> " . $user_ip . "<br>
                                <strong>Device:</strong> " . $device . " (" . $browser . ")<br>
                                <strong>Location:</strong> " . get_location_from_ip($user_ip) . "<br>
                                <strong>Password Strength:</strong> " . (strlen($new_password) >= 12 ? 'Strong' : 'Good') . "
                            </div>
                        </div>

                        <!-- Security Alert Box -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>⚠️ Important Security Information</h4>
                            <p style='color: #856404;'>
                                <strong>If you did NOT make this change:</strong><br>
                                1. Your account may have been compromised<br>
                                2. Use the 'Forgot Password' feature immediately<br>
                                3. Contact our security team
                            </p>
                        </div>

                        <!-- What This Means -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>What This Means</h3>
                            <ul style='color: #6c757d;'>
                                <li>Your old password no longer works</li>
                                <li>You'll need to use new password for all logins</li>
                                <li>All active sessions have been terminated (except this one)</li>
                                <li>Two-factor authentication remains active if enabled</li>
                            </ul>
                        </div>

                        <!-- Recommended Actions -->
                        <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #0056b3;'>🛡️ Recommended Security Actions</h4>
                            <ul style='color: #0056b3;'>
                                <li><strong>Enable Two-Factor Authentication</strong> for extra security</li>
                                <li><strong>Review recent login activity</strong> for suspicious access</li>
                                <li><strong>Update password recovery email</strong> if needed</li>
                                <li><strong>Use a password manager</strong> to store passwords securely</li>
                            </ul>
                        </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-logs.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 Activity Logs
                            </a>
                        </div>

                        <!-- Critical Security Warning -->
                        <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #721c24;'>🚨 CRITICAL: If You Didn't Change Your Password</h4>
                            <p style='color: #721c24;'>
                                Someone else may have access to your account!<br>
                                <strong>Immediate actions required:</strong><br>
                                1. <a href='" . $myUrl . "/forgot-password.php' style='color: #721c24; text-decoration: underline; font-weight: bold;'>Reset your password NOW</a><br>
                                2. <a href='" . $myUrl . "/support.php?urgent=security' style='color: #721c24; text-decoration: underline; font-weight: bold;'>Contact Security Team</a><br>
                                3. Check for unauthorized transactions
                            </p>
                        </div>

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

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

    // NOTIFICATION: Password Changed (ADMIN - Security Alert)
    $admin_mail_subject = "SECURITY ALERT: Password Changed - User ID: " . $user_id;
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>🚨 Password Change Security Alert</h2>
                            
                            <p class='message'>
                                A user has changed their password. This is a high-security notification.
                            </p>

                            <!-- User & Security Details -->
                            <div class='details-section'>
                                <div class='detail-box'>
                                    <strong>Alert Type:</strong> Password Change<br>
                                    <strong>User ID:</strong> " . $user_id . "<br>
                                    <strong>User Name:</strong> " . $first_name . " " . $last_name . "<br>
                                    <strong>User Email:</strong> " . htmlspecialchars($email) . "<br>
                                    <strong>Change Date:</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>Password Strength:</strong> " . (strlen($new_password) >= 12 ? 'Strong' : 'Good') . "<br>
                                    <strong>Change Method:</strong> Manual (Account Settings)
                                </div>
                            </div>

                            <!-- Risk Assessment -->
                            <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #856404;'>⚠️ Risk Assessment</h4>
                                <p style='color: #856404;'>
                                    <strong>Risk Level:</strong> <span style='color: #ffc107; font-weight: bold;'>MEDIUM</span><br>
                                    Password changes require immediate attention<br>
                                    <strong>Check for:</strong><br>
                                    • Multiple failed attempts before success<br>
                                    • Unusual location or device<br>
                                    • Recent security incidents
                                </p>
                            </div>

                            <!-- User Security Profile -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>User Security Profile</h3>
                                <p style='color: #6c757d;'>
                                    <strong>2FA Enabled:</strong> " . (isset($userData['two_factor_enabled']) && $userData['two_factor_enabled'] == 1 ? '✅ Yes' : '❌ No') . "<br>
                                    <strong>Last Password Change:</strong> " . (isset($userData['password_changed_at']) ? 
                                        date('F j, Y', strtotime($userData['password_changed_at'])) : 'First time') . "<br>
                                    <strong>Account Age:</strong> " . (isset($userData['created_at']) ? 
                                        round((time() - strtotime($userData['created_at'])) / (60 * 60 * 24)) . ' days' : 'N/A') . "<br>
                                    <strong>Recent Login:</strong> " . (isset($userData['last_login']) ? 
                                        round((time() - strtotime($userData['last_login'])) / 3600) . ' hours ago' : 'N/A') . "<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>

                            <!-- 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: #dc3545; color: white; text-decoration: none; border-radius: 6px; font-weight: 600; margin: 5px;'>
                                    Security Logs
                                </a>
                                <a href='" . $myUrl . "/admin/sessions.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;'>
                                    Active Sessions
                                </a>
                            </div>

                            <!-- Security Checklist -->
                            <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #721c24;'>🔍 Security Checklist</h4>
                                <ul style='color: #721c24;'>
                                    <li>Verify IP address matches usual locations</li>
                                    <li>Check for suspicious login patterns</li>
                                    <li>Review recent account activity</li>
                                    <li>Monitor for unauthorized transactions</li>
                                    <li>Consider temporary account hold if suspicious</li>
                                </ul>
                            </div>

                            <!-- Support Section -->
                            <div class='support-section'>
                                <p class='support-text'>This is an automated security alert.</p>
                                <p class='support-text'>Review user activity for suspicious patterns.</p>
                            </div>
                        </div>";

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

    // Also send notifications to secondary emails if verified
    $secondary_emails = mysqli_query($conn, 
        "SELECT email FROM user_secondary_emails WHERE user_id='$user_id' AND verified=1");
    
    while ($secondary = mysqli_fetch_assoc($secondary_emails)) {
        $secondary_email = $secondary['email'];
        
        // Secondary email notification (simplified)
        $mail_subject = "Security Alert: Password Changed on Your Account";
        $mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Security Alert</h2>
                            <p class='message'>
                                The password for " . $sitename . " account associated with this email has been changed.<br>
                                <strong>Account:</strong> " . $first_name . " " . $last_name . "<br>
                                <strong>Change Time:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Primary Email:</strong> " . htmlspecialchars($email) . "
                            </p>
                            <div class='support-section'>
                                <p class='support-text'>If this wasn't you, please contact security immediately.</p>
                                <a href='" . $myUrl . "/support.php?urgent=security' class='support-link'>Contact Security</a>
                            </div>
                        </div>";
        
        $user_email = $secondary_email;
        $first_name = "User";
        require_once("../proccess/mail_sender.php");
    }
    
    echo json_encode(['success' => true, 'message' => 'Password changed successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Database error: ' . mysqli_error($conn)]);
}

// Helper functions
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) {
    if ($ip == '127.0.0.1' || $ip == '::1') {
        return 'Localhost';
    }
    return 'IP: ' . $ip;
}
?>