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

if (empty($_POST['device_id'])) {
    echo json_encode(['success' => false, 'message' => 'Device ID required']);
    exit;
}

$device_id = intval($_POST['device_id']);

// 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
$removal_ip = $_SERVER['REMOTE_ADDR'];
$removal_agent = $_SERVER['HTTP_USER_AGENT'];
$browser = get_browser_name($removal_agent);
$device_type = is_mobile_device() ? 'Mobile' : 'Desktop';

// Verify device belongs to user and get device details
$verify_sql = "SELECT ud.*, 
                      CASE 
                          WHEN ud.session_id = '" . session_id() . "' THEN 'Current Device'
                          ELSE 'Other Device'
                      END as device_status
               FROM user_devices ud 
               WHERE ud.id = '$device_id' AND ud.user_id = '$user_id'";
$verify_result = mysqli_query($conn, $verify_sql);

if (!$verify_result || mysqli_num_rows($verify_result) === 0) {
    echo json_encode(['success' => false, 'message' => 'Device not found']);
    exit;
}

$device = mysqli_fetch_assoc($verify_result);

// Don't allow removing current device
if ($device['session_id'] === session_id()) {
    echo json_encode(['success' => false, 'message' => 'Cannot remove current device']);
    exit;
}

// Get device details for notification
$device_name = $device['device_name'] ?: 'Unnamed Device';
$device_os = $device['device_os'] ?: 'Unknown OS';
$device_browser = $device['browser'] ?: 'Unknown Browser';
$last_login = $device['last_login'] ? date('F j, Y g:i A', strtotime($device['last_login'])) : 'Never';
$first_seen = $device['created_at'] ? date('F j, Y', strtotime($device['created_at'])) : 'Unknown';
$is_current = $device['session_id'] === session_id();

// Count remaining devices
$device_count_sql = "SELECT COUNT(*) as total_devices FROM user_devices WHERE user_id = '$user_id'";
$device_count_result = mysqli_query($conn, $device_count_sql);
$device_count = mysqli_fetch_assoc($device_count_result)['total_devices'];

// Delete device
$delete_sql = "DELETE FROM user_devices WHERE id = '$device_id' AND user_id = '$user_id'";

if (mysqli_query($conn, $delete_sql)) {
    
    // NOTIFICATION: Device Removed (USER)
    $mail_subject = "Trusted Device Removed - 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>A trusted device has been removed from your account.</strong><br>
                            This device will no longer have automatic access to your account.
                        </p>

                        <!-- Device Details -->
                        <div class='details-section'>
                            <div class='detail-box'>
                                <strong>Removed Device:</strong> " . htmlspecialchars($device_name) . "<br>
                                <strong>Device Type:</strong> " . $device_type . "<br>
                                <strong>Operating System:</strong> " . $device_os . "<br>
                                <strong>Browser:</strong> " . $device_browser . "<br>
                                <strong>Device ID:</strong> DEV-" . $device_id . "<br>
                                <strong>First Seen:</strong> " . $first_seen . "<br>
                                <strong>Last Login:</strong> " . $last_login . "<br>
                                <strong>Removal Date:</strong> " . date('F j, Y g:i A') . "<br>
                                <strong>Removed From IP:</strong> " . $removal_ip . "<br>
                                <strong>Removed Using Browser:</strong> " . $browser . "<br>
                                <strong>Remaining Trusted Devices:</strong> " . ($device_count - 1) . "
                            </div>
                        </div>

                        <!-- Security Implications -->
                        <div style='background: #fff3cd; border: 1px solid #ffeaa7; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #856404;'>🔒 What This Means</h4>
                            <p style='color: #856404;'>
                                <strong>Next time this device tries to login:</strong><br>
                                • Full login credentials required<br>
                                • Two-factor authentication required (if enabled)<br>
                                • Email verification may be required<br>
                                • Will be treated as a new device
                            </p>
                        </div>

                        <!-- Action Taken -->
                        <div class='next-steps'>
                            <h3 style='color: #2c3e50;'>✅ Action Taken</h3>
                            <p style='color: #6c757d;'>The following security actions have been applied:</p>
                            <ul style='color: #6c757d;'>
                                <li>Device removed from trusted devices list</li>
                                <li>All active sessions from this device terminated</li>
                                <li>Device will require full authentication on next login</li>
                                <li>Security logs updated with removal event</li>
                            </ul>
                        </div>

                        <!-- If This Wasn't You -->
                        <div style='background: #f8d7da; border: 1px solid #f5c6cb; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                            <h4 style='color: #721c24;'>🚨 SECURITY ALERT</h4>
                            <p style='color: #721c24;'>
                                <strong>If you did NOT remove this device:</strong><br>
                                Someone may have unauthorized access to your account. Please:<br>
                                1. Change your password immediately<br>
                                2. Review all trusted devices<br>
                                3. Enable two-factor authentication<br>
                                4. Contact our security team
                            </p>
                        </div>

                        <!-- Action Buttons -->
                        <div style='text-align: center; margin: 30px 0;'>
                            <a href='" . $myUrl . "/security.php?tab=devices' 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;'>
                                Manage Devices
                            </a>
                            <a href='" . $myUrl . "/security.php?tab=activity' 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>
                            <a href='" . $myUrl . "/support.php?category=security' 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;'>
                                Report Security Issue
                            </a>
                        </div>

                        <!-- Support Section -->
                        <div class='support-section'>
                            <p class='support-text'>This is an automated security notification.</p>
                            <p class='support-text'>Stay vigilant and regularly review your trusted devices.</p>
                        </div>
                    </div>";

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

    // NOTIFICATION: Device Removed (ADMIN - Security Alert)
    $admin_mail_subject = "Security Alert: Device Removed - User ID: " . $user_id;
    $admin_mail_message = "<!-- Content Section -->
                        <div class='email-content'>
                            <h2 class='greeting'>Security Alert: Trusted Device Removed</h2>
                            
                            <p class='message'>
                                A user has removed a trusted device from their account.
                            </p>

                            <!-- Removal 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>Removed Device ID:</strong> DEV-" . $device_id . "<br>
                                    <strong>Device Name:</strong> " . htmlspecialchars($device_name) . "<br>
                                    <strong>Device OS:</strong> " . $device_os . "<br>
                                    <strong>Device Browser:</strong> " . $device_browser . "<br>
                                    <strong>Removal Date:</strong> " . date('F j, Y g:i A') . "<br>
                                    <strong>Removed From IP:</strong> " . $removal_ip . "<br>
                                    <strong>Removal Browser:</strong> " . $browser . "<br>
                                    <strong>Last Login from Device:</strong> " . $last_login . "<br>
                                    <strong>First Seen:</strong> " . $first_seen . "<br>
                                    <strong>Remaining Devices:</strong> " . ($device_count - 1) . "
                                </div>
                            </div>

                            <!-- User Device History -->
                            <div class='next-steps'>
                                <h3 style='color: #2c3e50;'>User Device History</h3>
                                <p style='color: #6c757d;'>
                                    <strong>Total Device Removals (Last 30 days):</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as removals FROM device_removal_logs 
                                             WHERE user_id='$user_id' AND removal_date >= DATE_SUB(NOW(), INTERVAL 30 DAY)"))['removals'] ?? 0) . "<br>
                                    <strong>Active Sessions:</strong> " . 
                                        (mysqli_fetch_assoc(mysqli_query($conn, 
                                            "SELECT COUNT(*) as sessions FROM user_devices WHERE user_id='$user_id'"))['sessions'] ?? 0) . "<br>
                                    <strong>Account Age:</strong> " . 
                                        (isset($userData['created_at']) ? 
                                         round((time() - strtotime($userData['created_at'])) / (60 * 60 * 24)) . ' days' : 'N/A') . "
                                </p>
                            </div>

                            <!-- Risk Assessment -->
                            <div style='background: #e7f3ff; border: 1px solid #b3d7ff; border-radius: 8px; padding: 20px; margin: 25px 0;'>
                                <h4 style='color: #0056b3;'>📊 Risk Assessment</h4>
                                <p style='color: #0056b3;'>
                                    <strong>Risk Level:</strong> <span style='color: #28a745;'>LOW</span><br>
                                    <strong>Assessment:</strong> User-initiated device management<br>
                                    <strong>Pattern:</strong> Normal security practice<br>
                                    <strong>Recommendation:</strong> No action required unless suspicious pattern detected
                                </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;'>
                                    Security Logs
                                </a>
                                <a href='" . $myUrl . "/admin/device-management.php?user_id=" . $user_id . "' 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;'>
                                    Device Management
                                </a>
                            </div>

                            <!-- Security Notes -->
                            <div class='support-section'>
                                <p class='support-text'>This is an automated security notification.</p>
                                <p class='support-text'>Monitor for unusual device removal patterns.</p>
                            </div>
                        </div>";

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

    // Log the device removal
    $log_sql = "INSERT INTO device_removal_logs 
                (user_id, device_id, device_name, removal_ip, removal_agent, removal_date)
                VALUES 
                ('$user_id', '$device_id', '" . mysqli_real_escape_string($conn, $device_name) . "', 
                 '$removal_ip', '$removal_agent', NOW())";
    mysqli_query($conn, $log_sql);

    echo json_encode(['success' => true, 'message' => 'Device removed successfully']);
} else {
    echo json_encode(['success' => false, 'message' => 'Failed to remove device: ' . 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;
}
?>