<?php

declare(strict_types=1);

namespace App\Repositories;

use PDO;

final class AuditLogRepository
{
    public function __construct(private PDO $pdo)
    {
    }

    public function tableReady(): bool
    {
        return table_exists($this->pdo, 'audit_logs');
    }

    public function users(): array
    {
        return $this->pdo->query("SELECT id, username, full_name FROM users ORDER BY username")->fetchAll() ?: [];
    }

    public function actions(): array
    {
        return $this->pdo->query("SELECT DISTINCT action FROM audit_logs ORDER BY action")->fetchAll() ?: [];
    }

    public function count(array $filters): int
    {
        [$wsql, $params] = $this->buildWhere($filters);
        $st = $this->pdo->prepare("SELECT COUNT(*) FROM audit_logs al $wsql");
        $st->execute($params);
        return (int)($st->fetchColumn() ?: 0);
    }

    public function paginated(array $filters, int $page, int $perPage): array
    {
        [$wsql, $params] = $this->buildWhere($filters);
        $offset = max(0, ($page - 1) * $perPage);
        $st = $this->pdo->prepare("SELECT al.*, u.username, u.full_name FROM audit_logs al LEFT JOIN users u ON u.id=al.user_id $wsql ORDER BY al.id DESC LIMIT $perPage OFFSET $offset");
        $st->execute($params);
        return $st->fetchAll() ?: [];
    }

    private function buildWhere(array $filters): array
    {
        $where = [];
        $params = [];
        if (($filters['user_id'] ?? 0) > 0) {
            $where[] = 'al.user_id=?';
            $params[] = (int)$filters['user_id'];
        }
        if (($filters['action_code'] ?? '') !== '') {
            $where[] = 'al.action=?';
            $params[] = (string)$filters['action_code'];
        }
        if (($filters['from'] ?? '') !== '') {
            $where[] = 'al.created_at>=?';
            $params[] = (string)$filters['from'] . ' 00:00:00';
        }
        if (($filters['to'] ?? '') !== '') {
            $where[] = 'al.created_at<=?';
            $params[] = (string)$filters['to'] . ' 23:59:59';
        }

        return [$where ? ('WHERE ' . implode(' AND ', $where)) : '', $params];
    }
}
