<?php

namespace Database\Seeders;

use App\Models\CategoryAtributes;
use App\Models\CategoryAtributesValue;
use App\Models\MotorMake;
use App\Models\MotorModel;
use Illuminate\Database\Seeder;
use PhpOffice\PhpSpreadsheet\Reader\Csv;

class CategoryAttributesSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        $makeData = $this->readCSV(__DIR__ . '/../../resources/csv/mn2.csv',"r");
        $modelData = $this->readCSV(__DIR__ . '/../../resources/csv/vm.csv',"r");

        $refineData = [];

        foreach ($modelData as $mkey => $model) {
            $maufacturer = $this->findKeyForRecord($makeData, $model[2], "0");
            if($maufacturer !== null){
                $make = MotorMake::where('name', $maufacturer[1])->firstOrCreate([
                    'name' => $maufacturer[1],
                ]);

                MotorModel::create([
                    'name' => $model[1],
                    'make_id' => $make->id,
                ]);
            }
        }

        echo "Make and Models Seeder Completed\n";
    }

    function readCSV($csvFile){
        $file_handle = fopen($csvFile, 'r');
        while (!feof($file_handle)) {
            $line = fgetcsv($file_handle, 0);
            if ($line !== false) {
                $line_of_text[] = $line;
            }
        }
        fclose($file_handle);
        return $line_of_text;
    }

    function findKeyForRecord($array, $searchValue, $index) {
        foreach ($array as $key => $value) {
            if ($value[$index] == $searchValue) {
                return $value;
            }
        }
        return null; // Return null if the value is not found
    }
}
