<?php

namespace App\Exports;

use App\Models\Product;
use Maatwebsite\Excel\Concerns\FromCollection;
use Maatwebsite\Excel\Concerns\WithHeadings;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\WithStyles;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;

class StockReportExport implements FromCollection, WithHeadings, WithMapping, WithStyles
{
    protected $stockStatus;

    public function __construct($stockStatus = 'all')
    {
        $this->stockStatus = $stockStatus;
    }

    public function collection()
    {
        $query = Product::with(['saleUnit', 'purchaseUnit'])
            ->where('status', Product::STATUS_ACTIVE);

        if ($this->stockStatus === 'in_stock') {
            $query->where('current_stock', '>', 0);
        } elseif ($this->stockStatus === 'low_stock') {
            $query->whereColumn('current_stock', '<=', 'reorder_level')
                ->where('current_stock', '>', 0);
        } elseif ($this->stockStatus === 'out_of_stock') {
            $query->where('current_stock', '<=', 0);
        }

        return $query->orderBy('name')->get();
    }

    public function headings(): array
    {
        return [
            'Produit',
            'SKU',
            'Stock Actuel',
            'Coût Unitaire',
            'Valeur Stock',
            'Statut',
        ];
    }

    public function map($product): array
    {
        $stockValue = $product->current_stock * ($product->purchase_price ?? 0);
        $status = $this->getStockStatus($product);

        // Use saleUnit name for display
        $unit = $product->saleUnit?->name ?? 'N/A';

        return [
            $product->name,
            $product->sku ?? 'N/A',
            number_format($product->current_stock, 0, ',', ' ') . ' ' . $unit,
            number_format($product->purchase_price ?? 0, 0, ',', ' '),
            number_format($stockValue, 0, ',', ' '),
            $status,
        ];
    }

    public function styles(Worksheet $sheet)
    {
        return [
            // Style the first row as bold
            1 => ['font' => ['bold' => true]],
        ];
    }

    private function getStockStatus($product): string
    {
        if ($product->current_stock <= 0) {
            return 'Rupture';
        } elseif ($product->current_stock <= $product->reorder_level) {
            return 'Stock faible';
        } else {
            return 'En stock';
        }
    }
}
