<?php
require_once __DIR__ . '/../models/User.php';

class AuthController extends Controller
{
    public function login(): void
    {
        if (Auth::check()) {
            $this->redirect('/admin');
        }

        $this->view('auth.login', ['title' => 'Admin Login | Balorp Ventures']);
    }

    public function authenticate(): void
    {
        if (!$this->isPost()) {
            $this->redirect('/login');
        }

        $token = $_POST['csrf_token'] ?? '';
        $sessionToken = $_SESSION['csrf_token'] ?? 'MISSING';
        if (!CSRF::validate($token)) {
            $this->view('auth.login', [
                'title' => 'Admin Login | Balorp Ventures',
                'error' => 'Security token expired. Please refresh and try again.',
                'debug' => 'CSRF failed. Session token: ' . substr($sessionToken, 0, 16) . '... Posted token: ' . substr($token, 0, 16) . '... Match: ' . (hash_equals($sessionToken, $token) ? 'yes' : 'no'),
            ]);
            return;
        }

        $this->enforceLoginRateLimit();

        $email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL);
        $password = trim((string)($_POST['password'] ?? ''));

        if (!$email || !$password) {
            $this->recordFailedLogin();
            $this->view('auth.login', ['title' => 'Admin Login | Balorp Ventures', 'error' => 'Please enter valid email and password.', 'debug' => 'Empty fields']);
            return;
        }

        $userModel = new User();
        $user = $userModel->findByEmail($email);

        if (!$user) {
            $this->recordFailedLogin();
            $this->view('auth.login', ['title' => 'Admin Login | Balorp Ventures', 'error' => 'Email or password is incorrect. No user found with that email.', 'debug' => 'User not found: ' . $email]);
            return;
        }

        if (password_verify($password, $user['password_hash'])) {
            $this->clearLoginRateLimit();
            Auth::login($user);
            $this->redirect('/admin');
        }

        $this->recordFailedLogin();
        $this->view('auth.login', ['title' => 'Admin Login | Balorp Ventures', 'error' => 'Email or password is incorrect. Password hash mismatch.', 'debug' => 'Password verify failed for: ' . $email]);
    }

    private function enforceLoginRateLimit(): void
    {
        $key = $this->rateLimitKey();
        $data = $_SESSION[$key] ?? ['attempts' => 0, 'locked_until' => 0];
        if (!empty($data['locked_until']) && $data['locked_until'] > time()) {
            $this->view('auth.login', [
                'title' => 'Admin Login | Balorp Ventures',
                'error' => 'Too many failed attempts. Please wait a few minutes and try again.',
            ]);
            exit;
        }
    }

    private function recordFailedLogin(): void
    {
        $key = $this->rateLimitKey();
        $data = $_SESSION[$key] ?? ['attempts' => 0, 'locked_until' => 0];
        $data['attempts'] += 1;
        if ($data['attempts'] >= 5) {
            $data['locked_until'] = time() + 300;
        }
        $_SESSION[$key] = $data;
    }

    private function clearLoginRateLimit(): void
    {
        $key = $this->rateLimitKey();
        unset($_SESSION[$key]);
    }

    private function rateLimitKey(): string
    {
        $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
        return 'login_rate_limit_' . md5($ip);
    }

    public function logout(): void
    {
        Auth::logout();
        $this->redirect('/login');
    }
}
