<?php

namespace App\Exports;

use App\Models\Tugasan;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithEvents;
use Maatwebsite\Excel\Events\AfterSheet;
use PhpOffice\PhpSpreadsheet\Shared\Date;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
use Maatwebsite\Excel\Concerns\WithColumnFormatting;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use DateTime;
use Carbon\Carbon;

class ExcelSenaraiTugasExport implements FromCollection, WithHeadings, WithEvents, WithColumnFormatting, ShouldAutoSize, WithMapping
{
    /**
     * @return \Illuminate\Support\Collection
     */

    protected $institusi;
    protected $jabatan;
    protected $sesi;

    function __construct($institusi, $jabatan, $sesi)
    {
        $this->institusi = $institusi;
        $this->jabatan = $jabatan;
        $this->sesi = $sesi;
    }

    public function headings(): array
    {
        return ["NAMA", "JABATAN", "TUGAS", "UNIT TUGAS SAMPINGAN", "SESI", "STATUS", "AKTIF", "TARIKH LANTIKAN", "CATATAN", "PERINGKAT", "GRED"];
    }

    public function map($laporan): array
    {

        $tarikh_lantikan = new DateTime($laporan->tarikh_lantikan . ' ' . now()->toTimeString());

        return [
            $laporan->nama_pengguna,
            $laporan->nama_jabatan,
            $laporan->nama_tugas_sampingan,
            $laporan->nama_unit_tugasan_sampingan,
            $laporan->nama_sesi,
            $laporan->nama_status,
            $laporan->aktif,
            Date::dateTimeToExcel($tarikh_lantikan),
            $laporan->catatan,
            $laporan->nama_peringkat,
            $laporan->nama_gred,
        ];
    }

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

    public function registerEvents(): array
    {
        return [
            AfterSheet::class => function (AfterSheet $event) {
                $event->sheet->getStyle('A1:N1')->applyFromArray([
                    'font' => [
                        'bold' => true
                    ]
                ]);
            },
        ];
    }

    public function collection()
    {
        return collect(Tugasan::senaraiTugasanBaru($this->institusi, $this->jabatan, $this->sesi));
    }
}
