<?php

namespace App\Exports;

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

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

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

    public function collection()
    {
        $query = Permission::with(['user.profile', 'approver'])
            ->where(function ($q) {
                $q->whereBetween('start_date', [$this->filters['start_date'], $this->filters['end_date']])
                  ->orWhereBetween('end_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']);
        }

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

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

    public function headings(): array
    {
        return [
            'No',
            'NIP',
            'Nama',
            'Kategori',
            'Tanggal Mulai',
            'Tanggal Selesai',
            'Durasi (Hari)',
            'Alasan',
            'Status',
            'Disetujui Oleh',
            'Tanggal Disetujui',
        ];
    }

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

        return [
            $no++,
            $permission->user->profile->nip ?? '-',
            $permission->user->name,
            $permission->category,
            Carbon::parse($permission->start_date)->format('d/m/Y'),
            Carbon::parse($permission->end_date)->format('d/m/Y'),
            $permission->duration,
            $permission->reason,
            ucfirst($permission->status),
            $permission->approver->name ?? '-',
            $permission->approved_at ? Carbon::parse($permission->approved_at)->format('d/m/Y H:i') : '-',
        ];
    }

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