<?php

namespace App\Http\Controllers\Portal;

use App\Http\Controllers\Controller;
use App\Models\AlertLog;
use App\Models\Client;
use App\Models\GeneratedReport;
use App\Services\Portal\PortalMetricsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;

class PortalDashboardController extends Controller
{
    public function index(Request $request, PortalMetricsService $metricsService): View
    {
        $page_title = 'Müşteri Dashboard';
        $clients = $this->clientsForUser();
        $client = $this->selectedClient($request, $clients);
        $metrics = $client ? $metricsService->overview($client, $request->string('from')->toString() ?: null, $request->string('to')->toString() ?: null) : null;
        $latestReports = $client
            ? GeneratedReport::where('client_id', $client->id)->latest()->limit(6)->get()
            : collect();
        $openAlerts = $client
            ? AlertLog::where('client_id', $client->id)->whereNull('resolved_at')->latest('triggered_at')->limit(6)->get()
            : collect();

        return view('portal.dashboard', compact('page_title', 'clients', 'client', 'metrics', 'latestReports', 'openAlerts'));
    }

    public function reports(Request $request): View
    {
        $page_title = 'Raporlarım';
        $clients = $this->clientsForUser();
        $client = $this->selectedClient($request, $clients);
        $reports = GeneratedReport::query()
            ->when($client, fn ($query) => $query->where('client_id', $client->id))
            ->whereIn('client_id', $clients->pluck('id'))
            ->latest()
            ->paginate(15)
            ->withQueryString();

        return view('portal.reports', compact('page_title', 'clients', 'client', 'reports'));
    }

    public function showReport(GeneratedReport $report): View
    {
        $this->authorizeClientAccess($report->client_id);

        $page_title = 'Rapor Detayı';
        $report->load(['client', 'emailLogs']);

        return view('portal.report-show', compact('page_title', 'report'));
    }

    public function downloadReport(GeneratedReport $report, string $type)
    {
        $this->authorizeClientAccess($report->client_id);
        abort_unless(in_array($type, ['pdf', 'excel', 'csv', 'html'], true), 404);

        $path = match ($type) {
            'pdf' => $report->pdf_path,
            'excel' => $report->excel_path,
            'csv' => $report->csv_path,
            'html' => $report->html_path,
        };

        abort_if(! $path || ! $report->fileExists($path), 404, 'Rapor dosyası bulunamadı.');

        return response()->download(storage_path('app/public/'.$path));
    }

    public function alerts(Request $request): View
    {
        $page_title = 'Uyarılarım';
        $clients = $this->clientsForUser();
        $client = $this->selectedClient($request, $clients);
        $alerts = AlertLog::query()
            ->when($client, fn ($query) => $query->where('client_id', $client->id))
            ->whereIn('client_id', $clients->pluck('id'))
            ->latest('triggered_at')
            ->paginate(20)
            ->withQueryString();

        return view('portal.alerts', compact('page_title', 'clients', 'client', 'alerts'));
    }

    private function clientsForUser()
    {
        $user = Auth::user();

        return Client::where('portal_enabled', true)
            ->whereHas('users', function ($query) use ($user) {
                $query->where('users.id', $user->id)->where('client_user.is_active', true);
            })
            ->orderBy('company_name')
            ->get();
    }

    private function selectedClient(Request $request, $clients): ?Client
    {
        if ($clients->isEmpty()) {
            return null;
        }

        $requestedClientId = (int) $request->query('client_id');

        return $clients->firstWhere('id', $requestedClientId) ?: $clients->first();
    }

    private function authorizeClientAccess(int $clientId): void
    {
        $allowed = $this->clientsForUser()->pluck('id')->contains($clientId);
        abort_unless($allowed, 403, 'Bu müşteri raporuna erişim yetkiniz yok.');
    }
}
