<?php
declare(strict_types=1);

namespace App\Modules\Audit\Models;

use App\Core\App;

class AuditTrail
{
    public static function search(array $filters, int $perPage = 25, int $page = 1): array
    {
        $db = App::getInstance()->db();
        $where = '1=1';
        $params = [];

        if (!empty($filters['employee_id'])) {
            $where .= ' AND a.employee_id = ?';
            $params[] = (int) $filters['employee_id'];
        }

        if (!empty($filters['action'])) {
            $where .= ' AND a.action = ?';
            $params[] = $filters['action'];
        }

        if (!empty($filters['entity_type'])) {
            $where .= ' AND a.entity_type = ?';
            $params[] = $filters['entity_type'];
        }

        if (!empty($filters['date_from'])) {
            $where .= ' AND a.created_at >= ?';
            $params[] = $filters['date_from'] . ' 00:00:00';
        }

        if (!empty($filters['date_to'])) {
            $where .= ' AND a.created_at <= ?';
            $params[] = $filters['date_to'] . ' 23:59:59';
        }

        if (!empty($filters['search'])) {
            $where .= ' AND (a.entity_label LIKE ? OR a.employee_name LIKE ? OR a.notes LIKE ?)';
            $s = '%' . $filters['search'] . '%';
            $params[] = $s;
            $params[] = $s;
            $params[] = $s;
        }

        $countRow = $db->selectOne("SELECT COUNT(*) as cnt FROM audit_trail a WHERE {$where}", $params);
        $total = (int) ($countRow['cnt'] ?? 0);

        $offset = ($page - 1) * $perPage;
        $rows = $db->select(
            "SELECT a.* FROM audit_trail a WHERE {$where} ORDER BY a.created_at DESC LIMIT {$perPage} OFFSET {$offset}",
            $params
        );

        $pagination = \App\Core\Pagination::paginate($total, $perPage, $page);

        return ['data' => $rows, 'pagination' => $pagination];
    }

    public static function getEntityHistory(string $entityType, int $entityId): array
    {
        $db = App::getInstance()->db();
        return $db->select(
            "SELECT * FROM audit_trail WHERE entity_type = ? AND entity_id = ? ORDER BY created_at DESC",
            [$entityType, $entityId]
        );
    }

    public static function getDistinctActions(): array
    {
        $db = App::getInstance()->db();
        $rows = $db->select("SELECT DISTINCT action FROM audit_trail ORDER BY action");
        return array_column($rows, 'action');
    }

    public static function getDistinctEntityTypes(): array
    {
        $db = App::getInstance()->db();
        $rows = $db->select("SELECT DISTINCT entity_type FROM audit_trail WHERE entity_type IS NOT NULL ORDER BY entity_type");
        return array_column($rows, 'entity_type');
    }
}