<?php

namespace App\Imports;

use App\Models\ProductRack;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;

class ProductRackImport implements ToCollection, WithHeadingRow
{
    protected $created = [];
    protected $skipped = [];

    private function extractValue(array $row, array $keys)
    {
        foreach ($keys as $key) {
            if (isset($row[$key])) {
                $v = is_string($row[$key]) ? trim($row[$key]) : $row[$key];
                if (!empty($v)) {
                    return $v;
                }
            }
        }
        return null;
    }

    public function collection(Collection $rows)
    {
        foreach ($rows as $row) {
            $rowArray = $row->toArray();

            $name = $this->extractValue($rowArray, ['name', 'nama', 'rack', 'rak']);
            $desc = $this->extractValue($rowArray, ['desc', 'deskripsi', 'description', 'keterangan']);

            if (empty($name)) {
                continue;
            }

            // Check case-insensitive duplicate
            $exists = ProductRack::whereRaw('LOWER(name) = ?', [strtolower($name)])->exists();
            if ($exists) {
                $this->skipped[] = [
                    'name' => $name,
                    'reason' => 'Already exists'
                ];
                continue;
            }

            $data = new ProductRack;
            $data->name = $name;
            $data->desc = $desc;
            $data->save();

            $this->created[] = $data;
        }
    }

    public function getResults()
    {
        return [
            'created' => $this->created,
            'skipped' => $this->skipped,
        ];
    }
}
