<?php

namespace App\Exports;

use App\Models\Category;
use App\Models\Product;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;

class InventoryExport implements FromQuery, WithHeadings, WithMapping
{
    public function __construct(
        protected ?string $search = null
    ) {}

    public function query()
    {
        $query = Product::with(['category', 'supplier', 'unit'])
            ->withSum('stocks as total_stock', 'actual_quantity')
            ->whereNull('deleted_at');

        if ($this->search) {
            $query->whereHas('category', function ($q) {
                $q->where('name', 'like', "%{$this->search}%");
            });
        } else {
            // Sans filtre : n'exporter que les produits dont le stock est > 0
            $query->whereRaw('(SELECT COALESCE(SUM(actual_quantity), 0) FROM stocks WHERE stocks.product_id = products.id AND stocks.deleted_at IS NULL) > 0');
        }

        return $query
            ->orderBy(Category::select('name')->whereColumn('categories.id', 'products.category_id'))
            ->orderBy('name');
    }

    public function headings(): array
    {
        return [
            'Catégorie',
            'Référence catégorie',
            'Produit',
            'Référence produit',
            'Fournisseur',
            'Unité',
            'Stock',
            'Statut',
        ];
    }

    public function map($product): array
    {
        $qty = (int) ($product->total_stock ?? 0);

        return [
            $product->category?->name ?? '-',
            $product->category?->reference ?? '-',
            $product->name,
            $product->reference ?? '-',
            $product->supplier?->name ?? '-',
            $product->unit?->abbreviation ?? $product->unit?->name ?? '-',
            $qty,
            $product->status === 'actif' ? 'Actif' : 'Archivé',
        ];
    }
}
