<?php

namespace App\Exports;

use App\Models\ContestParticipant;
use App\Services\ModalIndexQuey;
use Illuminate\Contracts\Support\Responsable;
use Maatwebsite\Excel\Concerns\Exportable;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Excel;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

class ContestParticipantExport implements FromQuery, Responsable, WithColumnFormatting, WithHeadings, WithMapping
{
    use Exportable;

    /**
     * File name used when download is triggered
     */
    private $fileName = 'contest_participants.xlsx';

    /**
     * Optional Writer Type
     */
    private $writerType = Excel::XLSX;

    /**
     * Optional headers
     */
    private $headers = [
        'Content-Type' => 'text/csv',
    ];

    public function __construct(
        public ?array $filters
    ) {}

    public function query()
    {
        $query = ContestParticipant::query()->with(['user', 'contest', 'prize']);

        return ModalIndexQuey::globalQuery($query);
    }

    /**
     * @param  \App\Models\ContestParticipant  $participant
     */
    public function map($participant): array
    {
        return [
            $participant->id,
            $participant->user->full_name ?? 'N/A',
            $participant->user->email ?? 'N/A',
            $participant->contest->name ?? 'N/A',
            $participant->prize->name ?? 'None',
            $participant->score,
            $participant->time_taken,
            $participant->submitted_at
                ? Date::dateTimeToExcel($participant->submitted_at)
                : 'Not Submitted',
        ];
    }

    public function headings(): array
    {
        return [
            'ID',
            'User Name',
            'Email',
            'Contest Name',
            'Prize',
            'Score',
            'Time Taken',
            'Submitted At',
            'Status',
        ];
    }

    public function columnFormats(): array
    {
        return [
            'H' => NumberFormat::FORMAT_DATE_DDMMYYYY,
        ];
    }
}
