<?php

namespace App\Exports;

use Carbon\Carbon;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Mtc\VehicleReservations\Reservation;

class ReservationExport implements FromCollection, WithHeadings
{
    public function __construct(private readonly array $input)
    {
    }

    public function collection(): Collection
    {
        return Reservation::query()
            ->with(['vehicle' => fn($query) => $query->withTrashed()->with(['make', 'model', 'dealership'])])
            ->whereNotNull('confirmed_at')
            ->when(
                !empty($this->input['status']) && $this->input['status'] !== 'all',
                fn($query) => $query->where('status', $this->input['status'])
            )
            ->when(
                !empty($this->input['from']),
                fn($query) => $query->where('confirmed_at', '>=', Carbon::parse($this->input['from'])->startOfDay())
            )
            ->when(
                !empty($this->input['to']),
                fn($query) => $query->where('confirmed_at', '<=', Carbon::parse($this->input['to'])->endOfDay())
            )
            ->latest('confirmed_at')
            ->get()
            ->map(fn(Reservation $reservation) => $this->mapRow($reservation));
    }

    private function mapRow(Reservation $reservation): array
    {
        return [
            $reservation->reference,
            $reservation->name,
            $reservation->email,
            $reservation->contact_number,
            $reservation->status,
            $reservation->amount,
            $reservation->currency,
            $reservation->vehicle?->registration_number,
            $reservation->vehicle?->title,
            $reservation->vehicle?->make?->name,
            $reservation->vehicle?->model?->name,
            $reservation->vehicle?->dealership?->name,
            $reservation->confirmed_at?->format('Y-m-d H:i'),
            $reservation->created_at?->format('Y-m-d H:i'),
        ];
    }

    public function headings(): array
    {
        return [
            'Reference',
            'Customer Name',
            'Email',
            'Contact Number',
            'Status',
            'Amount',
            'Currency',
            'Registration Number',
            'Vehicle',
            'Make',
            'Model',
            'Dealership',
            'Confirmed At',
            'Created At',
        ];
    }
}
