<?php

namespace App\Imports;

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

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

    private function extractName(array $row)
    {
        $candidates = ['name', 'nama', 'producttype', 'product_type', 'type', 'tipe'];
        foreach ($candidates as $key) {
            if (isset($row[$key])) {
                $v = is_string($row[$key]) ? trim($row[$key]) : '';
                if ($v !== '') {
                    return $v;
                }
            }
        }
        foreach ($row as $v) {
            if (is_string($v)) {
                $v = trim($v);
                if ($v !== '') {
                    return $v;
                }
            }
        }
        return '';
    }

    public function collection(Collection $rows)
    {
        foreach ($rows as $row) {
            $name = $this->extractName($row->toArray());
            if ($name === '') {
                continue;
            }
            $exists = Producttype::where('name', $name)->first();
            if ($exists) {
                $this->skipped[] = $name;
                continue;
            }
            $data = new Producttype;
            $data->name = $name;
            $data->save();
            $this->created[] = $data;
        }
    }

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