<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Database;

final class PublicLoginController
{
    public function index(): void
    {
        ini_set('display_errors','0');
        ini_set('log_errors','1');
        error_reporting(E_ALL);

        $db = Database::getInstance();
        if (session_status() !== PHP_SESSION_ACTIVE) session_start();

        $err = null;
        $ok  = null;

        if (($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
            $email = trim((string)($_POST['email'] ?? ''));
            $pass  = (string)($_POST['password'] ?? '');

            $st = $db->prepare("SELECT id, password_hash, is_active FROM users WHERE email=:e LIMIT 1");
            $st->execute([':e'=>$email]);
            $u = $st->fetch();

            if (!$u) $err = "User not found";
            elseif ((int)($u['is_active'] ?? 1) !== 1) $err = "User inactive";
            elseif (!password_verify($pass, (string)$u['password_hash'])) $err = "Invalid password";
            else {
                $_SESSION['user_id'] = (int)$u['id'];
                @session_regenerate_id(true);
                header('Location: ' . (function_exists('base_path') ? base_path('dashboard') : '/'));
                exit;
            }
        }

        header('Content-Type: text/html; charset=utf-8');
        echo "<!doctype html><html><head><meta charset='utf-8'><title>EasyChair Login</title>";
        echo "<style>
          body{font-family:Tahoma,Arial,sans-serif;margin:0;background:#f6f7fb}
          .wrap{max-width:520px;margin:40px auto;padding:0 16px}
          .card{background:#fff;border-radius:14px;box-shadow:0 10px 30px rgba(0,0,0,.08);padding:22px}
          h2{margin:0 0 10px}
          .muted{color:#666;margin-bottom:14px}
          label{display:block;margin:10px 0 6px;font-weight:600}
          input{width:100%;padding:10px 12px;border:1px solid #ddd;border-radius:10px}
          button{width:100%;padding:10px 14px;border:0;border-radius:10px;background:#0d6efd;color:#fff;font-weight:700;cursor:pointer;margin-top:12px}
          .err{background:#ffe6e6;color:#900;padding:10px;border-radius:10px;margin:10px 0}
          .links{margin-top:12px;font-size:12px;color:#666;text-align:center}
          a{color:#0d6efd;text-decoration:none}
        </style></head><body><div class='wrap'><div class='card'>";
        echo "<h2>Login</h2><div class='muted'>Sign in to your dashboard</div>";
        if ($err) echo "<div class='err'>".htmlspecialchars($err,ENT_QUOTES,'UTF-8')."</div>";
        echo "<form method='post'>
              <label>Email</label><input name='email' type='email' required>
              <label>Password</label><input name='password' type='password' required>
              <button type='submit'>Login</button>
              </form>";
        echo "<div class='links'>Session check: <a href='whoami.php'>whoami.php</a> • Direct login: <a href='simple_login.php'>simple_login.php</a></div>";
        echo "</div></div></body></html>";
    }

    public function logout(): void
    {
        if (session_status() !== PHP_SESSION_ACTIVE) session_start();
        $_SESSION = [];
        if (ini_get('session.use_cookies')) {
            $p = session_get_cookie_params();
            setcookie(session_name(), '', time()-42000, $p['path'] ?? '/', $p['domain'] ?? '', (bool)($p['secure'] ?? false), (bool)($p['httponly'] ?? true));
        }
        @session_destroy();
        header('Location: ' . (function_exists('base_path') ? base_path('login') : '/'));
        exit;
    }
}
