<?php

namespace App\Console\Commands;

use App\Models\CMMSMachine;
use App\Services\CMMS\GetMachinesInfoListService;
use Exception;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use SoapClient;

class GetMachinesInfoListCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'cmms_machines_info:get_list';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'receive cmms cars information list and update the corresponding tables';

    /**
     * Execute the console command.
     * @throws Exception
     */
    public function handle(GetMachinesInfoListService $getMachinesInfoListService): void
    {
        $response = $getMachinesInfoListService->run();

        $updatedRows = 0;

        if (isset($response['vw_MachBankFull'])) {

            foreach ($response['vw_MachBankFull'] as $entry) {
                // Insert data into the database
                CMMSMachine::query()->updateOrCreate(
                    [
                        'car_id' => $entry['Id'],
                        'machine_code' => $entry['MachineCode'],
                    ],
                    [
                        'car_name' => $entry['CarName'] == [] ? null : $entry['CarName'],
                        'car_group' => $entry['CarGroup'] == [] ? null : $entry['CarGroup'],
                        'machine_code' => $entry['MachineCode'],
                        'unit_name' => $entry['UnitName'],
                        'car_status' => $entry['Status'],
                        'car_id' => $entry['Id'],
                        'unit_group' => $entry['UnitGroup'] == [] ? null : $entry['UnitGroup'],
                        'plak_number' => $entry['PlakNumber'] ?? null,
                    ]);
                $updatedRows += 1;
            }
        }

        $this->info("{$updatedRows} row's updated successfully");
    }
}
