<?php

namespace App\Exports;

use Carbon\Carbon;
use App\Models\Attendance;
use Maatwebsite\Excel\Concerns\WithTitle;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\FromCollection;

class AttendanceExport implements FromCollection, WithHeadings, WithMapping, WithTitle
{
    protected $filters;

    public function __construct(array $filters)
    {
        $this->filters = $filters;
    }

    public function collection()
    {
        $query = Attendance::with(['user.profile', 'location'])
            ->whereBetween('date', [$this->filters['start_date'], $this->filters['end_date']]);

        if (!empty($this->filters['user_id'])) {
            $query->where('user_id', $this->filters['user_id']);
        }

        if (!empty($this->filters['status'])) {
            $query->where('status', $this->filters['status']);
        }

        return $query->orderBy('date', 'desc')->orderBy('time', 'desc')->get();
    }

    public function headings(): array
    {
        return [
            'No',
            'NIP',
            'Nama',
            'Tanggal',
            'Jam',
            'Tipe',
            'Lokasi',
            'Status',
            'Latitude',
            'Longitude',
        ];
    }

    public function map($attendance): array
    {
        static $no = 1;

        return [
            $no++,
            $attendance->user->profile->nip ?? '-',
            $attendance->user->name,
            Carbon::parse($attendance->date)->format('d/m/Y'),
            Carbon::parse($attendance->time)->format('H:i:s'),
            $attendance->type === 'in' ? 'Masuk' : 'Keluar',
            $attendance->location->name ?? '-',
            ucfirst($attendance->status),
            $attendance->latitude,
            $attendance->longitude,
        ];
    }

    public function title(): string
    {
        return 'Laporan Absensi';
    }
}
