<?php

namespace App\Http\Controllers\Admin\Report;

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

class QuizReportController extends Controller
{
    public function index()
    {
        adminUserHasPermission(permission: 'read');

        $userQuizzes = ModalIndexQuey::get(UserQuiz::query());

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

        $columns = [
            [
                'label' => __('User'),
                'key' => 'user.first_name',
                'header_class' => 'lg:w-[350px]',
            ],
            [
                'label' => __('Email'),
                'key' => 'user.email',
                'header_class' => 'lg:w-[350px]',
            ],
            [
                'label' => __('Quiz level'),
                'key' => 'quiz.quiz_level',
                'header_class' => 'lg:w-[350px]',
            ],
            [
                'label' => __('Status'),
                'key' => 'status',
                'header_class' => 'lg:w-[350px]',
                'render' => fn ($quiz) => '<span class="status '.$quiz->status->color().'">'.$quiz->status->label().'</span>',
            ],
            [
                'label' => __('Score'),
                'key' => 'score',
                'header_class' => 'lg:w-[350px]',
            ],
        ];

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

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

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

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

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

        $query = UserQuiz::query()->with(['user', 'quiz']);

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

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