<?php

namespace App\Console\Commands;

use App\Models\Client;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Http;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Canvas -> client RM reasons';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
    
        $clients = Client::where('shadow_pro_id', null)->get();
        $this->info("Processing ".count($clients)." clients");

        $successCount = 0;
        foreach($clients as $client){
            $this->info("Processing client:: ".$client->cell_number);
            $canvasJson = $client->canvas_data;
            if(!$canvasJson){
                $this->info("No canvas");
                continue;
            }
           
            $canvas = json_decode($canvasJson, true);
            $dx = isset($canvas['dx'])?$canvas['dx']:null; 

            if(!$dx){
                $this->info("No DX");
                continue;
            }
                
            $dxItems = $dx['items'];
            $positionIndex = 0;
            foreach($dxItems as $dxItem){
                if(!isset($dxItem['icd'])){
                    $this->info("DX item has no icd");
                    continue;
                }
                if(!isset($dxItem['title'])){
                    $this->info("DX item has no title");
                    continue;
                }
                $icd = $dxItem['icd'];
                $description = $dxItem['title'];
                $this->info('Client UID: '.$client->uid.' icd:'.$icd.' description:'.$description);
                $javaResponse = $this->submitToJava([
                    'clientUid'=>$client->uid, 
                    'icd'=>$icd, 
                    'description'=>$description, 
                    'secret'=>'superman2021',
                    'cellNumber'=>2025507072,
                    'positionIndex' => $positionIndex
                ]);
                $this->info("Java response: ".json_encode($javaResponse));
                $positionIndex++;
            }
            $successCount++;
        }

        $this->info("success count: ".$successCount);
    }

    private function submitToJava($data)
    {
        $url =  config('stag.backendUrl') . '/dev/createClientRmReason';
        $response = Http::asForm()
            ->withHeaders([
               
            ])
            ->post($url, $data)
            ->json();
        return $response;
    }
}
