<?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 Twig\Environment;
use PDO;

class BlogVisitsAction
{
    private PDO $pdo;
    private Environment $twig;

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

    public function __invoke(Request $request, Response $response, array $args): Response
    {
        // get top aggregates
        $stmt = $this->pdo->query('SELECT ip, useragent, cnt, datetime(first_seen, "unixepoch") AS first_seen, datetime(last_seen, "unixepoch") AS last_seen FROM blog_visits ORDER BY cnt DESC LIMIT 100');
        $visitors = $stmt->fetchAll(PDO::FETCH_ASSOC);

        // read last 200 lines from detail log (if exists)
        $detailPath = dirname(__DIR__, 3) . '/logs/blog_detail.log';
        $recentDetails = [];
        if (is_readable($detailPath)) {
            $lines = array_filter(array_map('rtrim', file($detailPath)));
            $lines = array_slice($lines, -200);
            foreach ($lines as $line) {
                // format: timestamp \t ip \t url
                $parts = preg_split('/\t+/', $line);
                $recentDetails[] = [
                    'timestamp' => $parts[0] ?? '',
                    'ip' => $parts[1] ?? '',
                    'url' => $parts[2] ?? ''
                ];
            }
        }

        $html = $this->twig->render('admin/blog_visits.twig', ['visitors' => $visitors, 'details' => $recentDetails]);
        $response->getBody()->write($html);
        return $response->withHeader('Content-Type', 'text/html');
    }
}
