<?php

namespace App\Http\Controllers;

use App\Models\MexcoEventUsage;
use App\Models\MexcoInvoice;
use App\Models\MexcoOrganisation;
use App\Models\MeetupEvent;
use Illuminate\Http\Response;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\StreamedResponse;

class MexcoSuperAdminReportsController extends Controller
{
    public function index(): \Illuminate\View\View
    {
        return view('super-admin.reports.index');
    }

    public function export(Request $request): StreamedResponse|Response
    {
        $type = $request->input('type', 'events');
        $filename = 'mexco-'.$type.'-'.now()->format('Y-m-d').'.csv';

        return response()->streamDownload(function () use ($type) {
            $out = fopen('php://output', 'w');

            match ($type) {
                'events' => $this->exportEvents($out),
                'revenue' => $this->exportRevenue($out),
                'usage' => $this->exportUsage($out),
                'organisations' => $this->exportOrganisations($out),
                default => fputcsv($out, ['Unknown report type']),
            };

            fclose($out);
        }, $filename, ['Content-Type' => 'text/csv']);
    }

    protected function exportEvents($out): void
    {
        fputcsv($out, ['Event ID', 'Event name', 'Organisation', 'Plan', 'Platform status', 'Participants', 'Sessions', 'Booths', 'Starts', 'Ends']);

        MeetupEvent::query()
            ->with(['organisation', 'license.plan', 'usage'])
            ->orderBy('name')
            ->chunk(100, function ($events) use ($out) {
                foreach ($events as $event) {
                    fputcsv($out, [
                        $event->id,
                        $event->name,
                        $event->organisation?->name,
                        $event->license?->plan?->name,
                        $event->platform_status,
                        $event->usage?->participants_count ?? 0,
                        $event->usage?->sessions_count ?? 0,
                        $event->usage?->booths_count ?? 0,
                        $event->starts_at?->toDateString(),
                        $event->ends_at?->toDateString(),
                    ]);
                }
            });
    }

    protected function exportRevenue($out): void
    {
        fputcsv($out, ['Invoice', 'Organisation', 'Event', 'Status', 'Subtotal', 'Discount', 'Tax', 'Total', 'Currency', 'Issued', 'Paid']);

        MexcoInvoice::query()
            ->with(['organisation', 'event'])
            ->orderByDesc('created_at')
            ->chunk(100, function ($invoices) use ($out) {
                foreach ($invoices as $inv) {
                    fputcsv($out, [
                        $inv->invoice_number,
                        $inv->organisation?->name,
                        $inv->event_id,
                        $inv->status,
                        $inv->subtotal_cents / 100,
                        $inv->discount_cents / 100,
                        $inv->tax_cents / 100,
                        $inv->total_cents / 100,
                        $inv->currency,
                        $inv->issued_at?->toDateString(),
                        $inv->paid_at?->toDateString(),
                    ]);
                }
            });
    }

    protected function exportUsage($out): void
    {
        fputcsv($out, ['Event ID', 'Event name', 'Plan', 'Participants', 'Sessions', 'Booths', 'Certificates', 'Last calculated']);

        MexcoEventUsage::query()
            ->with(['event.license.plan'])
            ->orderByDesc('participants_count')
            ->chunk(100, function ($rows) use ($out) {
                foreach ($rows as $usage) {
                    fputcsv($out, [
                        $usage->event_id,
                        $usage->event?->name,
                        $usage->event?->license?->plan?->name,
                        $usage->participants_count,
                        $usage->sessions_count,
                        $usage->booths_count,
                        $usage->certificates_issued_count,
                        $usage->last_calculated_at?->toDateTimeString(),
                    ]);
                }
            });
    }

    protected function exportOrganisations($out): void
    {
        fputcsv($out, ['Name', 'Slug', 'Type', 'Status', 'Email', 'Events', 'Organisers']);

        MexcoOrganisation::query()
            ->withCount(['events', 'users'])
            ->orderBy('name')
            ->chunk(100, function ($orgs) use ($out) {
                foreach ($orgs as $org) {
                    fputcsv($out, [
                        $org->name,
                        $org->slug,
                        $org->type,
                        $org->status,
                        $org->email,
                        $org->events_count,
                        $org->users_count,
                    ]);
                }
            });
    }
}
