<?php

namespace App\Exports;

use App\Models\Audit;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;

class LaporanExport implements FromCollection, WithHeadings, WithStyles, ShouldAutoSize
{
    protected $filter;

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

    public function collection()
    {
        $query = Audit::with(['bagian', 'tema', 'user.bagian']);

        // === Filter Tema ===
        if (!empty($this->filter['tema'])) {
            $tema = $this->filter['tema'];
            if (is_numeric($tema)) {
                $query->where('tema_id', $tema);
            } else {
                $query->whereHas('tema', function ($q) use ($tema) {
                    $q->where('nama', 'like', '%' . $tema . '%');
                });
            }
        }

        // === Filter Status ===
        if (!empty($this->filter['status'])) {
            if ($this->filter['status'] === 'CloseSesudah') {
                $query->where('status', 'Close')->whereNotNull('foto_sesudah');
            } elseif ($this->filter['status'] === 'CloseBelumFoto') {
                $query->where('status', 'Close')->whereNull('foto_sesudah');
            } else {
                $query->where('status', $this->filter['status']);
            }
        }

        // === Filter Tanggal Audit ===
        if (!empty($this->filter['start_date']) && !empty($this->filter['end_date'])) {
            $query->whereBetween('tanggal_audit', [
                $this->filter['start_date'],
                $this->filter['end_date']
            ]);
        }

        // === Filter Tanggal Verifikasi ===
        if (!empty($this->filter['verif_start']) && !empty($this->filter['verif_end'])) {
            $query->whereBetween('tanggal_verifikasi', [
                $this->filter['verif_start'],
                $this->filter['verif_end']
            ]);
        }

        return $query->orderBy('tanggal_audit', 'asc')->get()->map(function ($audit) {
            return [
                $audit->id,
                $audit->user_id,
                $audit->user?->name ?? '-',                     // auditor
                $audit->user?->bagian?->nama_bagian ?? '-',     // divisi auditor
                $audit->auditi ?? '-',                         // auditee
                $audit->bagian?->nama_bagian ?? '-',            // divisi yang diaudit
                $audit->tema?->nama ?? '-',                     // tema
                $audit->kategori ?? '-', 
                $audit->pic_perbaikan ?? '-', 
                $audit->lokasi ?? '-', 
                $audit->foto_sebelum ?? '-', 
                $audit->foto_sesudah ?? '-', 
                $audit->keterangan ?? '-', 
                $audit->keterangan_sesudah ?? '-', 
                $audit->tanggal_audit?->format('d-m-Y') ?? '-', 
                $audit->tanggal_verifikasi?->format('d-m-Y') ?? '-', 
                ucfirst($audit->status) ?? '-', 
                $audit->created_at?->format('d-m-Y H:i:s') ?? '-', 
                $audit->updated_at?->format('d-m-Y H:i:s') ?? '-', 
            ];
        });
    }

    public function headings(): array
    {
        return [
            'ID',
            'User ID',
            'Auditor',
            'Divisi Auditor',
            'Auditee',
            'Divisi yang Diaudit',
            'Tema',
            'Kategori',
            'PIC Perbaikan',
            'Lokasi/Area',
            'Foto Sebelum',
            'Foto Sesudah',
            'Keterangan Sebelum',
            'Keterangan Sesudah',
            'Tanggal Audit',
            'Tanggal Verifikasi',
            'Status',
            'Created At',
            'Updated At',
        ];
    }

    public function styles(Worksheet $sheet)
    {
        $sheet->getStyle('A1:S1')->applyFromArray([
            'font' => ['bold' => true, 'color' => ['rgb' => 'FFFFFF']],
            'fill' => [
                'fillType' => 'solid',
                'startColor' => ['rgb' => '228B22']
            ],
            'alignment' => ['horizontal' => 'center'],
            'borders' => [
                'allBorders' => ['borderStyle' => 'thin']
            ],
        ]);

        return [];
    }
}
