<?php
session_start();
require_once 'db.php';
require 'vendor/autoload.php';

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

define('ISE_SECRET_KEY', '1MZEEO92K55S1LFKEG0NMVA6JHJTNJ54');
define('ISE_TOKEN_EXPIRY', 3600);

if (!isset($_SESSION['pending_user_id']) || !isset($_SESSION['pending_username']) || !isset($_SESSION['pending_email']) || !isset($_SESSION['pending_ise_auth'])) {
    session_destroy();
    header('Location: ise-login.php');
    exit;
}

function generateISEToken($user_id, $email, $username) {
    $expires = time() + ISE_TOKEN_EXPIRY;
    $data = [
        'user_id' => $user_id,
        'email' => $email,
        'username' => $username,
        'expires' => $expires,
        'timestamp' => time(),
        'ise_auth' => true
    ];
    
    $token = base64_encode(json_encode($data));
    $signature = hash_hmac('sha256', $token . $expires, ISE_SECRET_KEY);
    
    return [
        'token' => $token,
        'expires' => $expires,
        'signature' => $signature
    ];
}

function buildISEAuthURL($user_id, $email, $username) {
    $tokenData = generateISEToken($user_id, $email, $username);
    
    $params = http_build_query([
        'token' => $tokenData['token'],
        'expires' => $tokenData['expires'],
        'signature' => $tokenData['signature']
    ]);
    
    return "https://ise.imators.systems/auth?" . $params;
}

function getDeviceInfo($user_agent) {
    $device_info = [
        'device' => 'Unknown',
        'os' => 'Unknown',
        'browser' => 'Unknown'
    ];

    if(preg_match('/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i',$user_agent)) {
        $device_info['device'] = 'Mobile';
    } elseif(preg_match('/tablet|ipad|playbook|silk/i', $user_agent)) {
        $device_info['device'] = 'Tablet';
    } else {
        $device_info['device'] = 'Desktop';
    }

    if(preg_match('/windows/i', $user_agent)) {
        $device_info['os'] = 'Windows';
    } elseif(preg_match('/macintosh|mac os x/i', $user_agent)) {
        $device_info['os'] = 'MacOS / iOS';
    } elseif(preg_match('/linux/i', $user_agent)) {
        $device_info['os'] = 'Linux';
    } elseif(preg_match('/iphone|ipad|ipod/i', $user_agent)) {
        $device_info['os'] = 'iOS';
    } elseif(preg_match('/android/i', $user_agent)) {
        $device_info['os'] = 'Android';
    }

    if(preg_match('/MSIE|Trident/i', $user_agent)) {
        $device_info['browser'] = 'Internet Explorer';
    } elseif(preg_match('/Firefox/i', $user_agent)) {
        $device_info['browser'] = 'Firefox';
    } elseif(preg_match('/Chrome/i', $user_agent)) {
        $device_info['browser'] = 'Chrome';
    } elseif(preg_match('/Safari/i', $user_agent)) {
        $device_info['browser'] = 'Safari';
    } elseif(preg_match('/Opera|OPR/i', $user_agent)) {
        $device_info['browser'] = 'Opera';
    }

    return $device_info;
}

function sendISELoginNotification($email, $location, $device_info) {
    $profile_picture = 'https://cdn.imators.com/default-profile.png';
    
    try {
        $db = new Database();
        $conn = $db->connect();
        
        if(isset($_SESSION['pending_user_id'])) {
            $userId = $_SESSION['pending_user_id'];
            
            $query = "SELECT `profile-picture` FROM utilisateurs WHERE id = :id";
            $stmt = $conn->prepare($query);
            $stmt->bindParam(':id', $userId, PDO::PARAM_INT);
            $stmt->execute();
            
            if($stmt->rowCount() > 0) {
                $row = $stmt->fetch(PDO::FETCH_ASSOC);
                if(isset($row['profile-picture']) && !empty($row['profile-picture'])) {
                    $profile_picture = $row['profile-picture'];
                }
            }
        }
    } catch (Exception $e) {
        error_log("Error fetching profile picture: " . $e->getMessage());
    }
    
    $mail = new PHPMailer(true);
    try {
        $mail->isSMTP();
        $mail->Host = 'mail.imators.com';
        $mail->SMTPAuth = true;
        $mail->Username = 'no-reply@imators.systems';
        $mail->Password = 'imators.managements4455*#@';
        $mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
        $mail->Port = 587;
        $mail->SMTPOptions = [
            'ssl' => [
                'verify_peer' => false,
                'verify_peer_name' => false,
                'allow_self_signed' => true
            ]
        ];

        $mail->setFrom('no-reply@imators.systems', 'Imators');
        $mail->addAddress($email);
        $mail->addReplyTo('no-reply@imators.systems', 'No Reply');
        $mail->isHTML(true);
        $mail->Subject = 'ISE Engine Access - Passkey Authentication';
        
        $location_text = isset($location['formatted_address']) ? 
            $location['formatted_address'] : 
            ($location['location'] ?? 'Unknown');
            
        $mail->Body = '
            <div style="font-family: \'Poppins\', sans-serif; max-width: 600px; margin: 0 auto;">
                <div style="background: #1a1a1a; padding: 30px; border-radius: 10px; color: white;">
                    <div style="text-align: center; margin-bottom: 20px;">
                        <img src="' . $profile_picture . '" alt="Profile Picture" style="width: 100px; height: 100px; border-radius: 50%; object-fit: cover; border: 2px solid #00ff00;">
                    </div>                
                    <h1 style="margin-bottom: 20px;">ISE Engine Access via Passkey</h1>
                    <p style="margin-bottom: 15px;">Your Imators account was used to access ISE Engine with Passkey authentication:</p>
                    <ul style="margin-bottom: 20px; list-style: none; padding: 0;">
                        <li style="margin-bottom: 5px;"><strong>Imators Service:</strong> ISE Engine Workspace</li>
                        <li style="margin-bottom: 5px;"><strong>Location:</strong> ' . $location_text . '</li>
                        <li style="margin-bottom: 5px;"><strong>Device:</strong> ' . $device_info['device'] . ' (' . $device_info['os'] . ')</li>
                        <li style="margin-bottom: 5px;"><strong>Browser:</strong> ' . $device_info['browser'] . '</li>
                        <li style="margin-bottom: 5px;"><strong>Time:</strong> ' . date('F j, Y g:i A') . '</li>
                        <li style="margin-bottom: 5px;"><strong>Authentication:</strong> Passkey</li>
                    </ul>
                    <p style="margin-bottom: 30px;">If this wasn\'t you, please secure your account immediately.</p>
                    <a href="https://idsma.imators.com" style="display: inline-block; background-color: #00ff00; color: black; padding: 10px 20px; text-decoration: none; border-radius: 5px;">
                        Go to Account Settings
                    </a>
                </div>
            </div>';

        $mail->send();
    } catch (Exception $e) {
        error_log("ISE Login email error: " . $mail->ErrorInfo);
    }
}

function logISEAccess($conn, $user_id, $location, $device_info) {
    $ip_address = $_SERVER['REMOTE_ADDR'];
    
    $location_data = [
        'ip' => $ip_address,
        'location' => $location['location'] ?? 'Unknown',
        'service' => 'ISE Engine',
        'auth_method' => 'Passkey'
    ];
    
    if (isset($location['latitude']) && isset($location['longitude'])) {
        $location_data['latitude'] = $location['latitude'];
        $location_data['longitude'] = $location['longitude'];
        $location_data['formatted_address'] = $location['formatted_address'] ?? null;
    }
    
    $stmt = $conn->prepare("
        INSERT INTO `connection-watchguard` 
        (user_id, `ip-connected`, `identified-screen`, `hours-of-connect`, `date-of-connect`) 
        VALUES (:user_id, :ip_connected, :identified_screen, :hours_of_connect, :date_of_connect)
    ");
    
    $stmt->execute([
        ':user_id' => $user_id,
        ':ip_connected' => json_encode($location_data),
        ':identified_screen' => json_encode($device_info),
        ':hours_of_connect' => date('H:i:s'),
        ':date_of_connect' => date('Y-m-d H:i:s')
    ]);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json');
    try {
        $db = new Database();
        $conn = $db->connect();
        
        $data = json_decode(file_get_contents('php://input'), true);
        
        $stmt = $conn->prepare("SELECT * FROM passkeys WHERE user_id = ?");
        $stmt->execute([$_SESSION['pending_user_id']]);
        $passkey = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($passkey) {
            $user_id = $_SESSION['pending_user_id'];
            $username = $_SESSION['pending_username'];
            $email = $_SESSION['pending_email'];

            $device_info = getDeviceInfo($_SERVER['HTTP_USER_AGENT']);
            
            $location = [];
            if(isset($data['exact_location'])) {
                $exact_location = $data['exact_location'];
                if($exact_location) {
                    $location = [
                        'country' => $exact_location['country'],
                        'city' => $exact_location['city'],
                        'region' => $exact_location['state'],
                        'location' => "{$exact_location['city']}, {$exact_location['country']}",
                        'latitude' => $exact_location['latitude'],
                        'longitude' => $exact_location['longitude'],
                        'formatted_address' => $exact_location['formatted']
                    ];
                }
            }
            
            if(empty($location)) {
                $ip_details = json_decode(file_get_contents("http://ip-api.com/json/" . $_SERVER['REMOTE_ADDR']), true);
                if($ip_details && $ip_details['status'] === 'success') {
                    $location = [
                        'country' => $ip_details['country'],
                        'city' => $ip_details['city'],
                        'region' => $ip_details['regionName'],
                        'location' => "{$ip_details['city']}, {$ip_details['country']}"
                    ];
                }
            }

            logISEAccess($conn, $user_id, $location, $device_info);
            sendISELoginNotification($email, $location, $device_info);

            $stmt = $conn->prepare("UPDATE passkeys SET last_used_at = NOW() WHERE user_id = ?");
            $stmt->execute([$user_id]);

            session_unset();
            
            $ise_url = buildISEAuthURL($user_id, $email, $username);
            echo json_encode(['success' => true, 'redirect' => $ise_url]);
            exit;
        } else {
            echo json_encode(['error' => 'Invalid passkey']);
        }
    } catch (Exception $e) {
        echo json_encode(['error' => $e->getMessage()]);
    }
    exit;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ISE Engine Passkey Authentication - Imators</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body { 
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #000000, #0a0a0a, #141414);
            background-attachment: fixed;
        }
        .glass-effect {
            backdrop-filter: blur(16px);
            background: rgba(255, 255, 255, 0.02);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        .gradient-border {
            position: relative;
            border-radius: 1.25rem;
            background: linear-gradient(145deg, rgba(26, 26, 26, 0.8), rgba(45, 45, 45, 0.4));
            padding: 1px;
        }
        .hover-scale {
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
        .hover-scale:hover {
            transform: translateY(-4px) scale(1.01);
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
        }
    </style>
    <script>
    function getExactLocation() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(
                function(position) {
                    const latitude = position.coords.latitude;
                    const longitude = position.coords.longitude;
                    
                    fetch(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${latitude}&lon=${longitude}&zoom=18&addressdetails=1`)
                        .then(response => response.json())
                        .then(data => {
                            window.exactLocation = {
                                latitude: latitude,
                                longitude: longitude,
                                city: data.address.city || data.address.town || data.address.village || data.address.hamlet || 'Unknown',
                                country: data.address.country || 'Unknown',
                                state: data.address.state || data.address.county || 'Unknown',
                                formatted: data.display_name || 'Unknown',
                            };
                        })
                        .catch(error => {
                            console.error("Error fetching address:", error);
                        });
                },
                function(error) {
                    console.error("Geolocation error:", error);
                }
            );
        }
    }

    document.addEventListener('DOMContentLoaded', getExactLocation);
    </script>
</head>
<body class="bg-black text-white min-h-screen flex items-center justify-center p-4">
    <div class="w-full max-w-md">
        <div class="text-center mb-8">
            <img src="https://cdn.imators.com/logo.png" alt="Logo" class="mx-auto mb-4" style="height: 60px;">
            <h1 class="text-3xl text-green-200">ISE Engine Access</h1>
            <p class="text-sm text-gray-400 mt-2">Complete your ISE Engine login with Passkey verification</p>
        </div>

        <div class="bg-blue-500/20 border border-blue-500 text-blue-300 p-3 rounded-lg text-sm mb-6">
            <p>🔒 Secure access to ISE Engine workspace via Passkey authentication.</p>
        </div>

        <div id="error-message" class="hidden bg-red-500/20 border border-red-500/20 text-red-400 p-4 rounded-lg mb-4 text-center"></div>

        <div class="gradient-border hover-scale">
            <div class="glass-effect rounded-xl p-8">
                <div class="flex justify-center mb-6">
                    <div id="verification-status" class="animate-pulse w-20 h-20 bg-blue-500/20 rounded-full flex items-center justify-center">
                        <svg class="w-10 h-10 text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z"/>
                        </svg>
                    </div>
                </div>

                <div class="text-center space-y-4">
                    <p class="text-gray-300" id="status-text">Use your passkey to access ISE Engine...</p>
                    <div class="text-sm text-gray-500">
                        <p>Authenticating for ISE Engine access:</p>
                        <p class="text-gray-300 font-medium"><?php echo htmlspecialchars($_SESSION['pending_email']); ?></p>
                    </div>
                    <a href="ise-login.php" class="inline-block text-sm text-gray-500 hover:text-gray-400 transition-colors mt-4">
                        Cancel and return to ISE login
                    </a>
                </div>
            </div>
        </div>
    </div>

    <script>
    async function verifyPasskey() {
        try {
            const challenge = new Uint8Array(32);
            window.crypto.getRandomValues(challenge);

            const credential = await navigator.credentials.get({
                publicKey: {
                    challenge,
                    rpId: window.location.hostname,
                    timeout: 60000,
                    userVerification: "preferred",
                    allowCredentials: []
                }
            });

            const requestData = {
                id: credential.id,
                rawId: arrayBufferToBase64(credential.rawId),
                response: {
                    clientDataJSON: arrayBufferToBase64(credential.response.clientDataJSON),
                    authenticatorData: arrayBufferToBase64(credential.response.authenticatorData),
                    signature: arrayBufferToBase64(credential.response.signature)
                }
            };
            
            if (window.exactLocation) {
                requestData.exact_location = window.exactLocation;
            }

            const response = await fetch(window.location.href, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(requestData)
            });

            const result = await response.json();
            
            if (result.success) {
                showSuccess();
                setTimeout(() => {
                    window.location.href = result.redirect;
                }, 1000);
            } else {
                throw new Error(result.error || 'Verification failed');
            }
        } catch (error) {
            showError(error.message);
        }
    }

    function showSuccess() {
        const status = document.getElementById('verification-status');
        const statusText = document.getElementById('status-text');
        
        status.classList.remove('animate-pulse', 'bg-blue-500/20');
        status.classList.add('bg-green-500/20');
        status.innerHTML = `
            <svg class="w-10 h-10 text-green-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"/>
            </svg>`;
        statusText.textContent = 'Success! Connecting to ISE Engine...';
    }

    function showError(message) {
        const status = document.getElementById('verification-status');
        const statusText = document.getElementById('status-text');
        const errorMessage = document.getElementById('error-message');
        
        status.classList.remove('animate-pulse', 'bg-blue-500/20');
        status.classList.add('bg-red-500/20');
        status.innerHTML = `
            <svg class="w-10 h-10 text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/>
            </svg>`;
        
        statusText.textContent = 'Authentication failed. Please try again.';
        errorMessage.textContent = message;
        errorMessage.classList.remove('hidden');
    }

    function arrayBufferToBase64(buffer) {
        const bytes = new Uint8Array(buffer);
        let binary = '';
        for (let i = 0; i < bytes.byteLength; i++) {
            binary += String.fromCharCode(bytes[i]);
        }
        return window.btoa(binary);
    }

    window.addEventListener('load', verifyPasskey);
    </script>
</body>
</html>