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

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

const MAX_ATTEMPTS = 3;
const LOCKOUT_DURATION = 300;

define('ISE_SECRET_KEY', '1MZEEO92K55S1LFKEG0NMVA6JHJTNJ54');
define('ISE_TOKEN_EXPIRY', 3600);
define('FORMORE_SECRET_KEY', '9LUcqkH6:C7k&}$c%y.?my{mkR:]:@QE[ND2p?5%Az-p-J1j#`vrS`bq3(V}b9V');
define('FORMORE_TOKEN_EXPIRY', 31536000);

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

function generateFormoreToken($user_id, $email, $username, $profile_picture) {
   $expires = time() + FORMORE_TOKEN_EXPIRY;
   $data = [
       'user_id' => $user_id,
       'email' => $email,
       'username' => $username,
       'profile_picture' => $profile_picture,
       'expires' => $expires,
       'timestamp' => time()
   ];
   
   $token = base64_encode(json_encode($data));
   $signature = hash_hmac('sha256', $token . $expires, FORMORE_SECRET_KEY);
   
   return [
       'token' => $token,
       'expires' => $expires,
       'signature' => $signature
   ];
}

function buildFormoreAuthURL($user_id, $email, $username, $profile_picture) {
   $tokenData = generateFormoreToken($user_id, $email, $username, $profile_picture);
   
   $params = http_build_query([
       'token' => $tokenData['token'],
       'expires' => $tokenData['expires'],
       'signature' => $tokenData['signature']
   ]);
   
   if (isset($_GET['app']) && $_GET['app'] === 'ios') {
       return "formore://auth?" . $params;
   } else {
       return "https://formore.tv/home.php?" . $params;
   }
}

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;
}

if(isset($_SESSION['user_id'])) {
   $redirect_url = "https://idsma.imators.com/dashboard.php";
   
   if (isset($_GET['formore-connection-protocole'])) {
       try {
           $db = new Database();
           $conn = $db->connect();
           
           $stmt = $conn->prepare("SELECT * FROM utilisateurs WHERE id = ? LIMIT 1");
           $stmt->execute([$_SESSION['user_id']]);
           $user = $stmt->fetch(PDO::FETCH_ASSOC);
           
           if($user) {
               $redirect_url = buildFormoreAuthURL($user['id'], $user['email'], $user['username'], $user['profile-picture'] ?? 'https://cdn.imators.com/default-profile.png');
           }
       } catch(PDOException $e) {
           error_log("Database error: " . $e->getMessage());
       }
   }
   
   if (isset($_GET['forumconnectionaccount']) && !empty($_GET['forumconnectionaccount'])) {
       $redirect_url = $_GET['forumconnectionaccount'];
       
       if (strpos($redirect_url, '/new-post') !== false) {
           $redirect_url .= (strpos($redirect_url, '?') !== false ? '&' : '?') . 'auth_token=' . $_SESSION['user_id'];
       }
   }
   
   if (isset($_GET['notification']) && !empty($_GET['notification'])) {
       $redirect_url = $_GET['notification'];
       
       if (strpos($redirect_url, '/dashboard') !== false) {
           $redirect_url .= (strpos($redirect_url, '?') !== false ? '&' : '?') . 'auth_token=' . $_SESSION['user_id'];
       }
   }
   
   header('Location: ' . $redirect_url);
   exit;
}

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 sendLoginNotification($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 = 'New Login to Your Imators Account';
       
       $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;">We detected a new login to your account with the following details:</h1>
                   <ul style="margin-bottom: 20px; list-style: none; padding: 0;">
                       <li style="margin-bottom: 5px;">Location: ' . $location_text . '</li>
                       <li style="margin-bottom: 5px;">Device: ' . $device_info['device'] . ' (' . $device_info['os'] . ')</li>
                       <li style="margin-bottom: 5px;">Browser: ' . $device_info['browser'] . '</li>
                       <li style="margin-bottom: 5px;">Time: ' . 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>
                   <p style="margin-top: 20px; font-size: 12px; color: #888;">
                       If you believe someone has unauthorized access to your account, please contact our support team immediately.
                   </p>
               </div>
           </div>';

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

function logSuccessfulLogin($conn, $user, $location, $device_info) {
   $ip_address = $_SERVER['REMOTE_ADDR'];
   
   $location_data = [
       'ip' => $ip_address,
       'location' => $location['location'] ?? 'Unknown'
   ];
   
   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;
   }
   
   $watchguard_data = [
       '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')
   ];

   $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' => $watchguard_data['user_id'],
       ':ip_connected' => $watchguard_data['ip-connected'],
       ':identified_screen' => $watchguard_data['identified-screen'],
       ':hours_of_connect' => $watchguard_data['hours-of-connect'],
       ':date_of_connect' => $watchguard_data['date-of-connect']
   ]);
}

$error = '';
$success = '';
$is_locked = false;
$remaining_time = 0;
$redirect_url = 'https://idsma.imators.com/dashboard';
$is_formore = false;
$step = 'email';
$user_exists = false;

if (isset($_GET['formore-connection-protocole'])) {
   $is_formore = true;
   $redirect_url = 'formore-connection';
}

if (isset($_GET['forumconnectionaccount'])) {
   $redirect_url = $_GET['forumconnectionaccount'];
}

if (isset($_GET['notification'])) {
   $redirect_url = $_GET['notification'];
}

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

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

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

if(isset($_GET['verified'])) {
   $success = "Email verified! Please login to continue.";
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && !$is_locked) {
   
   // Première étape: vérifier l'email
   if (isset($_POST['email']) && !isset($_POST['password'])) {
       $email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
       
       try {
           $db = new Database();
           $conn = $db->connect();

           $stmt = $conn->prepare("SELECT id, username FROM utilisateurs WHERE email = ? AND is_verified = 1 LIMIT 1");
           $stmt->execute([$email]);
           
           if($stmt->rowCount() > 0) {
               $user = $stmt->fetch(PDO::FETCH_ASSOC);
               $_SESSION['temp_email'] = $email;
               $_SESSION['temp_username'] = $user['username'];
               $step = 'password';
           } else {
               // Rediriger vers inscription
               $signup_url = './register';
               if ($is_formore) {
                   $signup_url .= '?formore-connection-protocole';
               }
               if (isset($_GET['app']) && $_GET['app'] === 'ios') {
                   $signup_url .= ($is_formore ? '&' : '?') . 'app=ios';
               }
               header('Location: ' . $signup_url);
               exit;
           }
       } catch(PDOException $e) {
           $error = "Database connection failed";
       }
   }
   
   // Deuxième étape: vérifier le mot de passe
   elseif (isset($_POST['password']) && isset($_SESSION['temp_email'])) {
       $email = $_SESSION['temp_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'])) {
                   
                   // Vérification passkey seulement si pas Formore
                   if ($redirect_url !== 'formore-connection') {
                       $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_passkey_auth'] = true;
                           $_SESSION['pending_user_id'] = $user['id'];
                           $_SESSION['pending_username'] = $user['username'];
                           $_SESSION['pending_email'] = $user['email'];
                           $_SESSION['redirect_after_passkey'] = $redirect_url;
                           header('Location: https://idsma.imators.com/passkey.php');
                           exit;
                       }
                   }

                   // Nettoyer les sessions temporaires
                   unset($_SESSION['login_attempts']);
                   unset($_SESSION['lockout_time']);
                   unset($_SESSION['temp_email']);
                   unset($_SESSION['temp_username']);

                   // Créer la session utilisateur
                   $_SESSION['user_id'] = $user['id'];
                   $_SESSION['username'] = $user['username'];

                   // Logging
                   $device_info = getDeviceInfo($_SERVER['HTTP_USER_AGENT']);
                   $location = [];
                   
                   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']}"
                           ];
                       }
                   }

                   logSuccessfulLogin($conn, $user, $location, $device_info);
                   sendLoginNotification($user['email'], $location, $device_info);

                   // Redirection finale
                   if ($redirect_url === 'formore-connection') {
                       $redirect_url = buildFormoreAuthURL($user['id'], $user['email'], $user['username'], $user['profile-picture'] ?? 'https://cdn.imators.com/default-profile.png');
                   } elseif (strpos($redirect_url, '/new-post') !== false) {
                       $redirect_url .= (strpos($redirect_url, '?') !== false ? '&' : '?') . 'auth_token=' . $user['id'];
                   } elseif (strpos($redirect_url, '/dashboard') !== false) {
                       $redirect_url .= (strpos($redirect_url, '?') !== false ? '&' : '?') . 'auth_token=' . $user['id'];
                   } else {
                       $redirect_url = 'https://idsma.imators.com/dashboard.php';
                   }

                   header('Location: ' . $redirect_url);
                   exit;
                   
               } else {
                   $_SESSION['login_attempts']++;
                   
                   if ($_SESSION['login_attempts'] >= MAX_ATTEMPTS) {
                       $_SESSION['lockout_time'] = time() + LOCKOUT_DURATION;
                       $is_locked = true;
                       $error = 'Too many failed attempts. Please wait 5 minutes.';
                   } else {
                       $remaining_attempts = MAX_ATTEMPTS - $_SESSION['login_attempts'];
                       $error = "Invalid password. $remaining_attempts attempts remaining.";
                   }
                   $step = 'password';
               }
           } else {
               $error = 'Account not found';
               $step = 'password';
           }
       } catch(PDOException $e) {
           $error = "Login failed. Please try again.";
           $step = 'password';
       }
   }
}

if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['back'])) {
   unset($_SESSION['temp_email']);
   unset($_SESSION['temp_username']);
   $step = 'email';
}

if (isset($_SESSION['temp_email']) && $step === 'email') {
   $step = 'password';
   $user_exists = true;
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title><?php echo $is_formore ? 'Login to Formore' : 'Imators Auth.'; ?></title>
   <meta name="description" content="Log in to your Imators account or create one to access a multitude of features that give you control over the system at your fingertips.">
   <meta property="og:url" content="https://accounts.imators.com">
   <meta property="og:type" content="website">
   <meta property="og:title" content="<?php echo $is_formore ? 'Login to Formore' : 'Imators Auth.'; ?>">
   <meta property="og:description" content="Log in to your Imators account or create one to access a multitude of features that give you control over the system at your fingertips.">
   <meta property="og:image" content="https://opengraph.b-cdn.net/production/images/fb6bc1ea-5744-46f1-bee6-fc033a6c6b56.png?token=_EL6e3nPPtxSgvlGKURhJgrJb5NireVFT99X4BXVrYA&height=600&width=1200&expires=33267345049">
   <meta name="twitter:card" content="summary_large_image">
   <meta property="twitter:domain" content="accounts.imators.com">
   <meta property="twitter:url" content="https://accounts.imators.com">
   <meta name="twitter:title" content="<?php echo $is_formore ? 'Login to Formore' : 'Imators Auth.'; ?>">
   <meta name="twitter:description" content="Log in to your Imators account or create one to access a multitude of features that give you control over the system at your fingertips.">
   <meta name="twitter:image" content="https://opengraph.b-cdn.net/production/images/fb6bc1ea-5744-46f1-bee6-fc033a6c6b56.png?token=_EL6e3nPPtxSgvlGKURhJgrJb5NireVFT99X4BXVrYA&height=600&width=1200&expires=33267345049">
   <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">
   <link href="https://cdn.imators.com/logo.png" rel="icon" type="image/png" />

   <style>
       * {
           margin: 0;
           padding: 0;
           box-sizing: border-box;
       }
       
       body {
           font-family: 'Poppins', sans-serif;
           background: #000;
           color: #fff;
           height: 100vh;
           display: flex;
           align-items: center;
           justify-content: center;
       }
       
       .main-container {
           width: 100%;
           max-width: 400px;
           padding: 40px;
           text-align: center;
       }
       
       .logo {
           height: 40px;
           margin-bottom: 40px;
       }
       
       .title {
           font-size: 28px;
           font-weight: 300;
           margin-bottom: 8px;
           line-height: 1.2;
       }
       
       .subtitle {
           color: #666;
           font-size: 14px;
           margin-bottom: 40px;
       }
       
       .back-btn {
           background: none;
           border: none;
           color: #666;
           font-size: 14px;
           cursor: pointer;
           margin-bottom: 20px;
           padding: 5px 0;
           text-decoration: none;
           transition: color 0.3s;
           display: block;
           text-align: left;
       }
       
       .back-btn:hover {
           color: #fff;
       }
       
       .form-group {
           margin-bottom: 20px;
           text-align: left;
       }
       
       .form-label {
           display: block;
           font-size: 14px;
           margin-bottom: 8px;
           color: #ccc;
       }
       
       .form-input {
           width: 100%;
           padding: 12px 0;
           border: none;
           border-bottom: 1px solid #333;
           background: transparent;
           color: #fff;
           font-size: 16px;
           transition: border-color 0.3s;
       }
       
       .form-input:focus {
           outline: none;
           border-bottom-color: #fff;
       }
       
       .password-container {
           position: relative;
       }
       
       .password-toggle {
           position: absolute;
           right: 0;
           bottom: 12px;
           background: none;
           border: none;
           color: #666;
           cursor: pointer;
           font-size: 14px;
       }
       
       .login-btn {
           width: 100%;
           padding: 16px;
           background: #fff;
           color: #000;
           font-size: 16px;
           font-weight: 500;
           cursor: pointer;
           margin-top: 30px;
           transition: background-color 0.3s;
       }
       
       .login-btn:hover {
           background: #f0f0f0;
       }
       
       .login-btn:disabled {
           opacity: 0.5;
           cursor: not-allowed;
       }
       
       .links {
           margin-top: 30px;
       }
       
       .links a {
           color: #666;
           text-decoration: none;
           font-size: 14px;
           display: block;
           margin-bottom: 8px;
           transition: color 0.3s;
       }
       
       .links a:hover {
           color: #fff;
       }
       
       .alert {
           padding: 12px;
           margin-bottom: 20px;
           border-radius: 4px;
           font-size: 14px;
           text-align: left;
       }
       
       .alert-error {
           background: rgba(220, 53, 69, 0.1);
           border: 1px solid #dc3545;
           color: #dc3545;
       }
       
       .alert-info {
           background: rgba(13, 202, 240, 0.1);
           border: 1px solid #0dcaf0;
           color: #0dcaf0;
       }
       
       .alert-warning {
           background: rgba(255, 193, 7, 0.1);
           border: 1px solid #ffc107;
           color: #ffc107;
       }
       
       .user-info {
           display: flex;
           align-items: center;
           margin-bottom: 20px;
           font-size: 14px;
           color: #ccc;
           text-align: left;
       }
       
       .user-avatar {
           width: 32px;
           height: 32px;
           border-radius: 50%;
           background: #333;
           margin-right: 12px;
           display: flex;
           align-items: center;
           justify-content: center;
           font-weight: 500;
       }
   </style>
</head>
<body>
   <div class="main-container">
       <img src="https://cdn.imators.com/logo.png" alt="Imators" class="logo">
       
       <?php if ($step === 'email'): ?>
           <h1 class="title">Login to your Imators Account</h1>
           <p class="subtitle"><?php echo $is_formore ? 'Link your Imators Account' : 'Access all your features'; ?></p>
           
           <?php if($is_formore): ?>
               <div class="alert alert-info">
                   You need to login to access Formore streaming platform.
               </div>
           <?php endif; ?>
           
           <?php if(isset($_GET['forumconnectionaccount'])): ?>
               <div class="alert alert-info">
                   You need to login to create a new post in our forum.
               </div>
           <?php endif; ?>
           
           <?php if(isset($_GET['notification'])): ?>
               <div class="alert alert-info">
                   You need to create or connect an Imators Account to receive news and more about our products.
               </div>
           <?php endif; ?>
           
           <?php if($error): ?>
               <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
           <?php endif; ?>

           <?php if($is_locked): ?>
               <div class="alert alert-warning">
                   <p>Too many login attempts</p>
                   <p>Time remaining: <?php echo ceil($remaining_time / 60); ?> minutes</p>
               </div>
           <?php endif; ?>
           
           <form method="POST">
               <div class="form-group">
                   <label class="form-label">Email</label>
                   <input type="email" name="email" class="form-input" required <?php echo $is_locked ? 'disabled' : ''; ?> autofocus>
               </div>
               
               <button type="submit" class="rounded-full login-btn" <?php echo $is_locked ? 'disabled' : ''; ?>>
                   Continue
               </button>
           </form>
           
       <?php else: ?>
           <a href="?back<?php echo isset($_GET['formore-connection-protocole']) ? '&formore-connection-protocole' : ''; ?><?php echo isset($_GET['app']) ? '&app=' . urlencode($_GET['app']) : ''; ?><?php echo isset($_GET['forumconnectionaccount']) ? '&forumconnectionaccount=' . urlencode($_GET['forumconnectionaccount']) : ''; ?><?php echo isset($_GET['notification']) ? '&notification=' . urlencode($_GET['notification']) : ''; ?>" class="back-btn">← Back</a>
           
           <div class="user-info">
               <div class="user-avatar"><?php echo strtoupper(substr($_SESSION['temp_username'], 0, 1)); ?></div>
               <span><?php echo htmlspecialchars($_SESSION['temp_username']); ?></span>
           </div>
           
           <h1 class="title">Enter your password</h1>
           <p class="subtitle">Welcome back, <?php echo htmlspecialchars($_SESSION['temp_username']); ?></p>
           
           <?php if($error): ?>
               <div class="alert alert-error"><?php echo htmlspecialchars($error); ?></div>
           <?php endif; ?>
           
           <form method="POST">
               <div class="form-group">
                   <label class="form-label">Password</label>
                   <div class="password-container">
                       <input type="password" name="password" class="form-input" required autofocus>
                       <button type="button" class="password-toggle" onclick="togglePassword(this)">Show</button>
                   </div>
               </div>
               
               <button type="submit" class="login-btn">
                   Login
               </button>
           </form>
       <?php endif; ?>
       
       <div class="links">
           <a href="./register<?php echo $is_formore ? '?formore-connection-protocole' : ''; ?><?php echo isset($_GET['app']) ? ($is_formore ? '&' : '?') . 'app=' . urlencode($_GET['app']) : ''; ?>">Create an account</a>
           <a href="./forgot-password">Forgot your password?</a>
       </div>
   </div>

   <script>
       function togglePassword(btn) {
           const field = btn.previousElementSibling;
           
           if (field.type === 'password') {
               field.type = 'text';
               btn.textContent = 'Hide';
           } else {
               field.type = 'password';
               btn.textContent = 'Show';
           }
       }
   </script>
</body>
</html>