<?php

namespace App\Exports;

use App\Models\ServiceTicket;
use Illuminate\Contracts\View\View;
use Maatwebsite\Excel\Concerns\FromView;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
use Maatwebsite\Excel\Concerns\WithStyles;
use Maatwebsite\Excel\Concerns\WithTitle;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class TicketsExport implements FromView, ShouldAutoSize, WithStyles, WithTitle
{
    public function __construct(
        private readonly ?int    $year,
        private readonly ?int    $month,
        private readonly ?string $status,
    ) {}

    // ── Data source ───────────────────────────────────

    public function view(): View
    {
        $query = ServiceTicket::with('customer')
            ->orderByDesc('created_at');

        if ($this->year) {
            $query->whereYear('created_at', $this->year);
        }

        if ($this->month) {
            $query->whereMonth('created_at', $this->month);
        }

        if ($this->status && in_array($this->status, ServiceTicket::STATUSES)) {
            $query->where('status', $this->status);
        }

        $tickets = $query->get();

        return view('admin.reports.export', compact('tickets'));
    }

    // ── Sheet title ───────────────────────────────────

    public function title(): string
    {
        $parts = ['Data Servis'];

        if ($this->year && $this->month) {
            $parts[] = \Carbon\Carbon::create($this->year, $this->month, 1)->translatedFormat('F Y');
        } elseif ($this->year) {
            $parts[] = (string) $this->year;
        }

        if ($this->status) {
            $parts[] = $this->status;
        }

        return implode(' - ', $parts);
    }

    // ── Cell styling ──────────────────────────────────

    public function styles(Worksheet $sheet): array
    {
        return [
            // Header row (row 1)
            1 => [
                'font'      => ['bold' => true, 'color' => ['argb' => 'FFFFFFFF']],
                'fill'      => ['fillType' => 'solid', 'startColor' => ['argb' => 'FF2563EB']],
                'alignment' => ['horizontal' => 'center'],
            ],
        ];
    }
}
