<?php

namespace App\Http\Controllers\Admin\Report;

use App\Exports\ContestsExport;
use App\Http\Controllers\Controller;
use App\Models\Contest;
use App\Services\Helper\PdfGenerator;
use App\Services\ModalIndexQuey;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Maatwebsite\Excel\Facades\Excel;

class ContestReportController extends Controller
{
    public function index()
    {
        adminUserHasPermission('read');

        $query = Contest::query()
            ->withCount('participants')
            ->withAvg('participants', 'score')
            ->withAvg('participants', 'time_taken');

        $contests = ModalIndexQuey::get($query, ['category']);

        $columns = [
            ['label' => __('Contest Title'), 'key' => 'translation.title'],
            ['label' => __('Participant Count'), 'key' => 'participants_count'],
            ['label' => __('Contest Score (Avg)'), 'key' => 'participants_avg_score'],
            ['label' => __('Contest Time (Avg)'), 'key' => 'participants_avg_time_taken'],
        ];

        $buttons = [
            [
                'label' => __('Export Report'),
                'icon' => 'ph ph-download-simple',
                'type' => 'link',
                'link' => route('admin.reports.contests.export', ['excel', ...request()->all()]),
            ],
            [
                'label' => __('Pdf Report'),
                'icon' => 'ph ph-file-pdf',
                'type' => 'link',
                'link' => route('admin.reports.contests.export', ['pdf', ...request()->all()]),
            ],
        ];

        return view('admin.pages.reports.contest.index', compact('contests', 'columns', 'buttons'));
    }

    public function getExport(Request $request, $type)
    {
        adminUserHasPermission(permission: 'read');

        $storage = Storage::disk('report');

        if ($type === 'excel') {
            Excel::store(new ContestsExport($request->all()), 'reports/contests.xlsx', 'report');

            return response()->download($storage->path('reports/contests.xlsx'));
        }

        $query = Contest::query()
            ->withCount('participants')
            ->withAvg('participants', 'score')
            ->withAvg('participants', 'time_taken')
            ->with(['category']);

        PdfGenerator::generate($query, 'reports.contests', 'contests.pdf');

        return response()->download($storage->path('reports/contests.pdf'));
    }
}
