<?php

namespace App\Exports;

use App\Models\MovementStock;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class AnnualReportExport implements FromQuery, WithHeadings, WithMapping
{
    public function __construct(
        protected int $year,
        protected ?int $departmentId = null
    ) {}

    public function query()
    {
        $query = MovementStock::with(['product', 'department', 'user'])
            ->whereNull('deleted_at')
            ->whereYear('created_at', $this->year)
            ->orderBy('created_at', 'desc');

        if ($this->departmentId) {
            $query->where('department_id', $this->departmentId);
        }

        return $query;
    }

    public function headings(): array
    {
        return [
            'Référence',
            'Date',
            'Type',
            'Produit',
            'Quantité',
            'Département',
            'Utilisateur',
        ];
    }

    public function map($mouvement): array
    {
        $typeLabels = [
            'entree' => 'Entrée',
            'sortie' => 'Sortie',
            'transfert' => 'Transfert',
            'perte' => 'Perte',
            'endommagement' => 'Endommagement',
            'expiration' => 'Expiration',
        ];

        return [
            $mouvement->reference ?? '-',
            $mouvement->created_at?->format('d/m/Y H:i') ?? '-',
            $typeLabels[$mouvement->type] ?? $mouvement->type,
            $mouvement->product?->name ?? '-',
            $mouvement->quantity,
            $mouvement->department?->name ?? '-',
            $mouvement->user?->full_name ?? '-',
        ];
    }
}
