<?php

namespace App\Services;

use App\Repositories\AuditLogRepository;

class AuditLogService
{
    protected $repository;

    public function __construct(AuditLogRepository $repository)
    {
        $this->repository = $repository;
    }

    public function getListWithPaginate(?string $orgHex, array $filters, int $perPage = 50)
    {
        return $this->repository->paginateByOrganization($orgHex, $perPage, $filters);
    }

    public function getDashboardMetrics(?string $orgHex, array $filters = [])
    {
        return $this->repository->getDashboardMetrics($orgHex, $filters);
    }

    public function getUsers(?string $orgHex)
    {
        return $this->repository->getUsersByOrganization($orgHex);
    }

    public function deleteLog(int $id, ?string $orgHex)
    {
        return $this->repository->deleteByIdInOrganization($id, $orgHex);
    }

    public function deleteAll(?string $orgHex)
    {
        $deleted = $this->repository->countInOrganization($orgHex);
        $this->repository->deleteAllInOrganization($orgHex);
        return $deleted;
    }

    public function getAll(?string $orgHex)
    {
        return $this->repository->getAllByOrganization($orgHex);
    }

    public function getExportData(?string $orgHex, string $view = 'logs'): array
    {
        $logs = $this->getAll($orgHex);

        if ($view === 'latest-koc') {
            return ['type' => 'latest-koc', 'rows' => $this->getLatestRows($logs, 'KOC')];
        }

        if ($view === 'latest-campaign') {
            return ['type' => 'latest-campaign', 'rows' => $this->getLatestRows($logs, 'Chiến dịch')];
        }

        return ['type' => 'logs', 'rows' => $logs];
    }

    private function getLatestRows($logs, string $objectType): array
    {
        $grouped = [];

        foreach ($logs as $log) {
            $logObjType = $this->getObjectTypeLabel($log);
            if ($logObjType !== $objectType) continue;

            $targetName = trim((string) ($log['object_name'] ?? ''));
            if (!$targetName) continue;

            $prevDate = isset($grouped[$targetName]) ? strtotime($grouped[$targetName]['created_at']) : 0;
            $currDate = strtotime($log['created_at']);
            if ($currDate && (!$prevDate || $currDate > $prevDate)) {
                $grouped[$targetName] = $log;
            }
        }

        $rows = [];
        foreach ($grouped as $targetName => $log) {
            $rows[] = [
                'targetName' => $targetName,
                'latestAt' => $log['created_at'],
                'username' => $log['username'] ?? '—',
                'tabName' => $this->normalizeTab($log['tab_name']),
                'action' => $log['action'] ?? '—',
                'details' => $log['details'] ?? '—',
            ];
        }

        usort($rows, function ($a, $b) {
            $aTime = strtotime($a['latestAt']) ?: 0;
            $bTime = strtotime($b['latestAt']) ?: 0;
            return $bTime - $aTime;
        });

        return $rows;
    }

    private function getObjectTypeLabel($log): string
    {
        $raw = strtolower(trim((string) ($log['object_type'] ?? '')));
        if (!$raw) {
            $action = strtolower(trim((string) ($log['action'] ?? '')));
            if (str_contains($action, 'koc')) return 'KOC';
            if (str_contains($action, 'campaign') || str_contains($action, 'chiến dịch') || str_contains($action, 'chiến_dịch')) return 'Chiến dịch';
            return 'Khác';
        }
        if (str_contains($raw, 'koc')) return 'KOC';
        if (str_contains($raw, 'chiến dịch') || str_contains($raw, 'campaign')) return 'Chiến dịch';
        return $log['object_type'] ?? 'Khác';
    }

    private function normalizeTab(?string $tabName): string
    {
        $lower = strtolower(trim((string) $tabName));
        if (!$lower) return 'Khác';

        $map = [
            'login' => 'Đăng nhập',
            'admin' => 'Quản lý nhân viên',
            'campaigns' => 'Quản lý chiến dịch',
            'campaign-detail' => 'Chi tiết chiến dịch',
            'booking' => 'Quản lý booking',
            'koc' => 'Quản lý KOC',
            'videos' => 'Video',
        ];

        return $map[$lower] ?? $tabName;
    }
}
