<?php

namespace App\Services;

use Illuminate\Support\Facades\Http;

class Matomo
{
    private int $siteId;

    public static array $allowedMetrics = [
        'VisitsSummary.get',
    ];

    public function setSiteId($siteId): self
    {
        if (is_numeric($siteId)) {
            $this->siteId = (int)$siteId;
        }
        return $this;
    }

    public function runReport(int $dateRange, array $metrics)
    {
        $query_params = [
            'module' => 'API',
            'method' => 'API.getBulkRequest',
            'format' => 'json',
            'urls' => array_map(
                fn ($metric) => "method=$metric&idSite=$this->siteId&date=last$dateRange&period=day",
                $metrics
            ),
        ];
        $response = Http::asForm()->post($this->domain() . '?' . http_build_query($query_params), [
            'token_auth' => config('services.matomo.auth_token'),
        ]);
        if ($response->successful()) {
            return $response->json();
        }

        throw new \Exception('Failed to authenticate Matomo');
    }

    public function getVisitorsForDate(string $date): int
    {
        $query_params = [
            'module' => 'API',
            'method' => 'VisitsSummary.getVisits',
            'idSite' => $this->siteId,
            'period' => 'day',
            'date' => $date,
            'format' => 'json',
        ];

        $response = Http::asForm()->post($this->domain() . '?' . http_build_query($query_params), [
            'token_auth' => config('services.matomo.auth_token'),
        ]);

        if ($response->successful()) {
            $data = $response->json();
            return is_numeric($data['value'] ?? $data) ? (int) ($data['value'] ?? $data) : 0;
        }

        throw new \Exception('Failed to fetch visitors from Matomo');
    }

    private function domain(): string
    {
        return config('services.matomo.domain');
    }
}
