<?php

namespace App\Exports;

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

class MovementsExport implements FromQuery, WithHeadings, WithMapping
{
    public function __construct(
        protected ?string $tab = null,
        protected ?int $departmentId = null,
        protected ?string $dateFrom = null,
        protected ?string $dateTo = null
    ) {}

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

        if ($this->tab === 'entree') {
            $query->where('type', 'entree');
        } elseif ($this->tab === 'sortie') {
            $query->where('type', 'sortie');
        }

        if ($this->departmentId) {
            $query->where('department_id', $this->departmentId);
        }
        if ($this->dateFrom) {
            $query->whereDate('created_at', '>=', $this->dateFrom);
        }
        if ($this->dateTo) {
            $query->whereDate('created_at', '<=', $this->dateTo);
        }

        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?->name ?? $mouvement->user?->full_name ?? '-',
        ];
    }
}
