<?php

namespace App\Services;

use App\Models\SiteCode;
use App\Models\Country;
use App\Models\Region;

class SiteCodeBulkUpload
{
    public function importData($path)
    {
        $count = 1;
        $items = $this->getItems($path);
        if (empty($items)) return false;

        foreach ($items['csvData'] as $key => $item) {

            if (!count($item)) continue; //skip empty columns

            if ($csvData = $this->generateCSVData($item)) {
                SiteCode::updateOrCreate(['code' => $csvData['code']], $csvData);
                $count++;
            }
        }

        return $count;
    }

    public function getItems($path)
    {
        if (!file_exists($path)) return false;
        $items = csv_to_array($path);
        if (empty($items)) return false;
        return $items;
    }

    public function generateCSVData($item)
    {
        if (empty($item) || empty($item['Region'])) {
            return false;
        }
        $region = Region::firstOrCreate(['name' => $item['Region']]);
        $country = Country::firstOrCreate(['name' => $item['Country']]);
        return [
            'code'         => $item['Site Code'],
            'region_id'    => $region->id,
            'country_id' => $country->id
        ];
    }
}
