<?php

namespace App\Imports;

use App\Models\Category;
use App\Models\StockItem;
use App\Services\Inventory\StockItemService;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;
use Maatwebsite\Excel\Concerns\SkipsOnFailure;
use Maatwebsite\Excel\Concerns\SkipsFailures;

class StockItemsImport implements ToCollection, WithHeadingRow, WithValidation, SkipsOnFailure
{
    use SkipsFailures;

    protected int $importedCount = 0;
    protected int $skippedCount = 0;
    protected array $errors = [];

    public function collection(Collection $rows)
    {
        $stockItemService = app(StockItemService::class);

        foreach ($rows as $index => $row) {
            $rowNumber = $index + 2; // Account for header row

            // Skip row if required fields are missing
            if (empty($row['category']) || empty($row['item_name'])) {
                $this->skippedCount++;
                $this->errors[] = "Row {$rowNumber}: Missing category or item name";
                continue;
            }

            $categoryName = trim($row['category']);
            $itemName = trim($row['item_name']);

            // Create or get category
            $category = Category::firstOrCreate(['name' => $categoryName]);

            // Skip if item with same name already exists in this category
            $existing = StockItem::where('item_name', $itemName)
                ->where('category_id', $category->id)
                ->exists();

            if ($existing) {
                $this->skippedCount++;
                $this->errors[] = "Row {$rowNumber}: Item '{$itemName}' already exists in category '{$categoryName}'";
                continue;
            }

            try {
                // Generate item code if not provided
                $itemCode = !empty($row['item_code'])
                    ? trim($row['item_code'])
                    : $stockItemService->generateItemCode();

                // Create new stock item with all fields
                StockItem::create([
                    'item_code' => $itemCode,
                    'item_name' => $itemName,
                    'category_id' => $category->id,
                    'description' => $row['description'] ?? null,
                    'uom' => $row['uom'] ?? null,
                    'quantity' => $this->parseNumeric($row['quantity'] ?? 0),
                    'min_stock' => $this->parseNumeric($row['min_stock'] ?? 0),
                    'max_stock' => $this->parseNumeric($row['max_stock'] ?? null),
                    'sgst' => $this->parseNumeric($row['sgst'] ?? null),
                    'cgst' => $this->parseNumeric($row['cgst'] ?? null),
                    'igst' => $this->parseNumeric($row['igst'] ?? null),
                    'hsn_code' => $row['hsn_code'] ?? null,
                    'status' => $row['status'] ?? StockItem::STATUS_ACTIVE,
                    'created_by' => auth()->id(),
                ]);

                $this->importedCount++;
            } catch (\Exception $e) {
                $this->skippedCount++;
                $this->errors[] = "Row {$rowNumber}: " . $e->getMessage();
                Log::error("Stock Item Import Error at row {$rowNumber}", [
                    'item_name' => $itemName,
                    'error' => $e->getMessage(),
                ]);
            }
        }
    }

    /**
     * Validation rules for each row
     */
    public function rules(): array
    {
        return [
            'category' => 'required|string|max:255',
            'item_name' => 'required|string|max:255',
            'uom' => 'nullable|string|max:50',
            'quantity' => 'nullable|numeric|min:0',
            'min_stock' => 'nullable|numeric|min:0',
            'max_stock' => 'nullable|numeric|min:0',
            'sgst' => 'nullable|numeric|min:0|max:100',
            'cgst' => 'nullable|numeric|min:0|max:100',
            'igst' => 'nullable|numeric|min:0|max:100',
            'hsn_code' => 'nullable|string|max:20',
        ];
    }

    /**
     * Parse numeric value, handling empty strings
     */
    protected function parseNumeric($value): ?float
    {
        if ($value === null || $value === '') {
            return null;
        }
        return is_numeric($value) ? (float) $value : null;
    }

    /**
     * Get imported count
     */
    public function getImportedCount(): int
    {
        return $this->importedCount;
    }

    /**
     * Get skipped count
     */
    public function getSkippedCount(): int
    {
        return $this->skippedCount;
    }

    /**
     * Get import errors
     */
    public function getErrors(): array
    {
        return $this->errors;
    }

    /**
     * Get import summary
     */
    public function getSummary(): array
    {
        return [
            'imported' => $this->importedCount,
            'skipped' => $this->skippedCount,
            'errors' => $this->errors,
        ];
    }
}
