<?php

namespace App\Imports;

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

class UnitImport 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', 'unit']);
            $desc = $this->extractValue($rowArray, ['desc', 'deskripsi', 'description', 'keterangan']);

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

            $exists = Unit::where('name', $name)->first();
            if ($exists) {
                $this->skipped[] = [
                    'name' => $name,
                    'reason' => 'Already exists'
                ];
                continue;
            }

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

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

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