<?php

declare(strict_types=1);

namespace App\Application\Actions\Admin;

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;

use PDO;
use Twig\Environment;

class AdminController
{
    private PDO $pdo;
    private $twig;

    public function __construct(PDO $pdo, \Twig\Environment $twig)
    {
        $this->pdo = $pdo;
        $this->twig = $twig;
    }

    public function login(Request $request, Response $response, array $args): Response
    {
        $error = null;
        if ($request->getMethod() === 'POST') {
            $data = $request->getParsedBody();
            $username = $data['username'] ?? '';
            $password = $data['password'] ?? '';

            $remoteIp = $request->getServerParams()['REMOTE_ADDR'] ?? '';
            $userAgent = $request->getServerParams()['HTTP_USER_AGENT'] ?? '';

            $stmt = $this->pdo->prepare('SELECT * FROM users WHERE username = :username LIMIT 1');
            $stmt->execute([':username' => $username]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            $success = false;
            if ($user && password_verify($password, $user['password'])) {
                $success = true;
                $_SESSION['admin_user'] = $user['id'];
            }
            $this->logAccessAttempt($username, $password, $remoteIp, $userAgent, $success);

            if ($success) {
                return $response->withHeader('Location', '/admin')->withStatus(302);
            }
            $error = 'Invalid credentials';
        }
        $html = $this->twig->render('admin/login.twig', ['error' => $error]);
        $response->getBody()->write($html);
        return $response->withHeader('Content-Type', 'text/html');
    }

    private function logAccessAttempt(string $username, string $password, string $remoteIp, string $userAgent, bool $success): void
    {
        $logPassword = $success ? '***MASKED***' : $password;
        $stmtLog = $this->pdo->prepare('INSERT INTO access_logs (username, password, remote_ip, user_agent, created_at) VALUES (:username, :password, :remote_ip, :user_agent, CURRENT_TIMESTAMP)');
        $stmtLog->execute([
            ':username' => $username,
            ':password' => $logPassword,
            ':remote_ip' => $remoteIp,
            ':user_agent' => $userAgent
        ]);
    }

    public function logout(Request $request, Response $response, array $args): Response
    {
        unset($_SESSION['admin_user']);
        return $response->withHeader('Location', '/admin/login')->withStatus(302);
    }
}
