<?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);
const MAX_ATTEMPTS = 3;
const LOCKOUT_DURATION = 300;

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) {
    global $conn;
    
    $stmt = $conn->prepare("SELECT `profile-picture` FROM utilisateurs WHERE email = ?");
    $stmt->execute([$email]);
    $user_data = $stmt->fetch(PDO::FETCH_ASSOC);
    $profile_picture = $user_data['profile-picture'] ?? 'https://cdn.imators.com/default-profile.png';
    
    $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 - Login Detected';
        
        $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 Detected</h1>
                    <p style="margin-bottom: 15px;">Your Imators account was used to access ISE Engine with the following details:</p>
                    <ul style="margin-bottom: 20px; list-style: none; padding: 0;">
                        <li style="margin-bottom: 5px;"><strong>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>
                    </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, $location, $device_info) {
    $ip_address = $_SERVER['REMOTE_ADDR'];
    
    $location_data = [
        'ip' => $ip_address,
        'location' => $location['location'] ?? 'Unknown',
        'service' => 'ISE Engine'
    ];
    
    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')
    ]);
}

$error = '';
$is_locked = false;
$remaining_time = 0;

$_SESSION['ise_login_attempts'] ??= 0;

if (isset($_SESSION['ise_lockout_time']) && $_SESSION['ise_lockout_time'] > time()) {
    $is_locked = true;
    $remaining_time = $_SESSION['ise_lockout_time'] - time();
}

if (isset($_GET['unlock']) && (!isset($_SESSION['ise_lockout_time']) || $_SESSION['ise_lockout_time'] <= time())) {
    unset($_SESSION['ise_login_attempts']);
    unset($_SESSION['ise_lockout_time']);
    $is_locked = false;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$is_locked) {
    $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
    $password = $_POST['password'];
    
    try {
        $db = new Database();
        $conn = $db->connect();

        $stmt = $conn->prepare("SELECT * FROM utilisateurs WHERE email = ? AND is_verified = 1 LIMIT 1");
        $stmt->execute([$email]);
        
        if($stmt->rowCount() > 0) {
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            if(password_verify($password, $user['password'])) {
                $stmt = $conn->prepare("SELECT passkey_enabled FROM utilisateurs WHERE id = ? LIMIT 1");
                $stmt->execute([$user['id']]);
                $passkey_enabled = $stmt->fetchColumn();
            
                if ($passkey_enabled) {
                    $_SESSION['pending_ise_auth'] = true;
                    $_SESSION['pending_user_id'] = $user['id'];
                    $_SESSION['pending_username'] = $user['username'];
                    $_SESSION['pending_email'] = $user['email'];
                    header('Location: ise-passkey.php');
                    exit;
                }

                unset($_SESSION['ise_login_attempts']);
                unset($_SESSION['ise_lockout_time']);

                $device_info = getDeviceInfo($_SERVER['HTTP_USER_AGENT']);
                
                $location = [];
                if(isset($_POST['exact_location'])) {
                    $exact_location = json_decode($_POST['exact_location'], true);
                    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, $location, $device_info);
                sendISELoginNotification($email, $location, $device_info);

                $ise_url = buildISEAuthURL($user['id'], $user['email'], $user['username']);
                header('Location: ' . $ise_url);
                exit;
            } else {
                $_SESSION['ise_login_attempts']++;
                
                if ($_SESSION['ise_login_attempts'] >= MAX_ATTEMPTS) {
                    $_SESSION['ise_lockout_time'] = time() + LOCKOUT_DURATION;
                    $is_locked = true;
                    $error = "Too many failed attempts. Please wait 5 minutes.";
                } else {
                    $error = "Invalid password";
                }
            }
        } else {
            $error = "Email not found or not verified";
        }
    } catch(PDOException $e) {
        $error = "Login failed: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Connect to ISE Engine - Imators Auth</title>
    <meta name="description" content="Use your Imators account to securely access ISE Engine workspace and tools.">
    <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>
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v6.4.0/css/all.css">
    <link href="https://cdn.imators.com/logo.png" rel="icon" type="image/png" />
    <style>
        body {
            font-family: 'Poppins', sans-serif;
        }
    </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 => {
                            const location = {
                                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',
                            };
                            
                            const locationInput = document.createElement('input');
                            locationInput.type = 'hidden';
                            locationInput.name = 'exact_location';
                            locationInput.value = JSON.stringify(location);
                            document.querySelector('form').appendChild(locationInput);
                        })
                        .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">
    <div class="w-full max-w-md p-8">
        <div class="text-center mb-8">
            <img src="https://cdn.imators.com/logo.png" alt="Logo" class="mx-left mb-4" style="height: 60px;">
            <h1 class="text-3xl text-left text-green-200">Connect your account to IS_Engine</h1>
            <p class="text-sm mt-2 text-left text-gray-400"><i class="fa-solid fa-circle-info"></i> The IS_Engine site (https://ise.imators.systems) to request the connection to this service. You can <a href="https://ise.imators.systems" class="underline font-semibold italic">cancel the request</a> from the service.</p>
        </div>

        <form method="POST" class="space-y-6">
            <?php if($error): ?>
                <div class="bg-red-500 text-white p-3 rounded-lg text-center mb-4">
                    <?php echo htmlspecialchars($error); ?>
                </div>
            <?php endif; ?>
            
            <?php if($is_locked): ?>
                <div class="bg-yellow-500/20 border border-yellow-500 text-yellow-300 p-4 rounded-lg text-center mb-4">
                    <p>Too many login attempts</p>
                    <p>Time remaining: <span id="countdown"><?php echo $remaining_time; ?></span> seconds</p>
                    <a href="?unlock" class="mt-2 inline-block bg-green-500 text-white px-4 py-2 rounded">Try Again</a>
                </div>
            <?php endif; ?>
            
            <div>
                <label class="block text-sm font-medium mb-2">Email</label>
                <input 
                    type="email" 
                    name="email" 
                    required 
                    <?php echo $is_locked ? 'disabled' : ''; ?>
                    class="w-full px-4 py-2 rounded-lg bg-gray-900 border border-gray-800 focus:border-white focus:outline-none <?php echo $is_locked ? 'opacity-50 cursor-not-allowed' : ''; ?>"
                >
            </div>
            
            <div>
                <label class="block text-sm font-medium mb-2">Password</label>
                <input 
                    type="password" 
                    name="password" 
                    required 
                    <?php echo $is_locked ? 'disabled' : ''; ?>
                    class="w-full px-4 py-2 rounded-lg bg-gray-900 border border-gray-800 focus:border-white focus:outline-none <?php echo $is_locked ? 'opacity-50 cursor-not-allowed' : ''; ?>"
                >
            </div>
            
            <button 
                type="submit" 
                <?php echo $is_locked ? 'disabled' : ''; ?>
                class="w-full bg-white text-black py-2 px-4 rounded-lg font-medium hover:bg-gray-100 transition-colors <?php echo $is_locked ? 'opacity-50 cursor-not-allowed' : ''; ?>"
            >
                Proceed
            </button>
        </form>
        
        <p class="mt-4 text-left text-sm">
            <a href="./login.php" class="text-gray-400 hover:text-white hover:underline">← Back to regular login</a>
        </p>
        </div>
</body>
</html>