<?php

namespace App\Exports;

use App\Exports\Concerns\StyledHeadingRow;
use App\Models\User;
use App\Services\Admin\Users\StudentService;
use Illuminate\Support\Enumerable;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;

class StudentsExport implements FromCollection, ShouldAutoSize, WithEvents, WithHeadings, WithMapping, WithStyles
{
    use StyledHeadingRow;

    public function __construct(
        private readonly string $search = '',
        private readonly ?string $gender = null,
        private readonly ?int $departmentId = null,
        private readonly ?string $status = null,
        private readonly ?int $enrollmentYear = null,
    ) {}

    public function title(): string
    {
        return 'Data Mahasiswa';
    }

    public function collection(): Enumerable
    {
        return app(StudentService::class)->forExport($this->search, $this->gender, $this->departmentId, $this->status, $this->enrollmentYear);
    }

    public function headings(): array
    {
        return [
            'NIM',
            'Nama Lengkap',
            'Username',
            'Email',
            'Nomor Telepon',
            'Jurusan',
            'Angkatan',
            'Status',
            'Jenis Kelamin',
            'Tempat Lahir',
            'Tanggal Lahir',
            'Alamat',
        ];
    }

    public function map($user): array
    {
        /** @var User $user */
        return [
            $user->student?->student_number ?? '-',
            $user->profile?->full_name ?? '-',
            $user->username,
            $user->email,
            $user->profile?->phone_number ?? '-',
            $user->student?->department?->name ?? '-',
            $user->student?->enrollment_year ?? '-',
            $user->student?->status?->label() ?? '-',
            $user->profile?->gender?->label() ?? '-',
            $user->profile?->birth_place ?? '-',
            $user->profile?->birth_date?->format('d M Y') ?? '-',
            $user->profile?->address ?? '-',
        ];
    }
}
