<?php

namespace App\Livewire\Pos\Employee;

use App\Models\SalesEmpTemp;
use App\Models\Settings;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Attributes\On;
use Livewire\Component;

class EmpIndex extends Component
{
    use LivewireAlert;
    
    public $isloading = false;


    protected function isConnectionResetError($e)
    {
        return $e instanceof \GuzzleHttp\Exception\RequestException &&
            strpos($e->getMessage(), 'cURL error 56: Recv failure: Connection was reset') !== false;
    }

    protected function reDoFunction($function, $args = [])
    {
        call_user_func_array([$this, $function], $args);
    }

    public function render()
    {
        return view('livewire.pos.employee.emp-index');
    }

    public function firstClick()
    {
        $this->isloading = true;
        $this->dispatch('getsalesEmp');
    }

    #[On('getsalesEmp')]
    public function sapGetSalesEmp()
    {
        $user = Auth::user();
        $setting = Settings::where('wh_code', $user->whs_code)->first();
        $userId = auth()->user()->id;
        $url = $setting->url;
        $whscode = $setting->wh_code;

        try {
            $response = Http::post($url . '/api/search', [
                "Select" => "\"SlpCode\" as \"code\",\"SlpName\" as \"name\",\"Memo\" as \"position\",\"Active\" as \"active\",'" . $userId . "' as \"id_user\" ",
                "From" => "OSLP",
            ]);
            $responseBody = $response->getBody()->getContents();
            $responseData = json_decode($responseBody, true);
            if ($response->successful()) {
                $jsonData = $response->json();

                SalesEmpTemp::where('id_user', $userId)->delete();

                $chunks = array_chunk($jsonData, 1000);

                foreach ($chunks as $chunk) {
                    $insertData = [];

                    foreach ($chunk as $item) {
                        $insertData[] = [
                            'code' => $item['code'],
                            'name' => $item['name'],
                            'position' => $item['position'],
                            'active' => $item['active'],
                            'id_user' => $item['id_user'],
                        ];
                    }

                    DB::table('Luv2_salesemp_temp')->insert($insertData);
                }

                #insert salesemp
                DB::statement("
                    INSERT INTO \"Luv2_salesemp\" (\"code\", \"name\", \"position\", \"active\") 
                    SELECT DISTINCT \"code\", \"name\", \"position\", \"active\"
                    FROM \"Luv2_salesemp_temp\"
                    WHERE NOT EXISTS (
                        SELECT 1 FROM \"Luv2_salesemp\" WHERE \"Luv2_salesemp\".\"code\" = \"Luv2_salesemp_temp\".\"code\" and \"Luv2_salesemp_temp\".\"id_user\"='" . $userId . "'
                    ) and \"Luv2_salesemp_temp\".\"id_user\"='" . $userId . "' 
                ");

                #update salesemp
                DB::statement("
                    UPDATE \"Luv2_salesemp\"
                    SET \"name\"=\"Luv2_salesemp_temp\".\"name\",\"position\"=\"Luv2_salesemp_temp\".\"position\",\"active\"=\"Luv2_salesemp_temp\".\"active\"
                    FROM \"Luv2_salesemp_temp\"
                    WHERE \"Luv2_salesemp_temp\".\"code\"=\"Luv2_salesemp\".\"code\" AND \"Luv2_salesemp_temp\".\"id_user\"='" . $userId . "'
                    AND (
                        \"Luv2_salesemp_temp\".\"name\"<>\"Luv2_salesemp\".\"name\" OR
                        \"Luv2_salesemp_temp\".\"position\"<>\"Luv2_salesemp\".\"position\" OR
                        \"Luv2_salesemp_temp\".\"active\"<>\"Luv2_salesemp\".\"active\"
                    );
                ");

                SalesEmpTemp::where('id_user', $userId)->delete();
                $this->alert('success', 'Data synchrone succesfully', [
                    'position' => 'top-right',
                    'timer' => 3000,
                    'toast' => true,
                    'timerProgressBar' => true,
                ]);
            }
        } catch (\Exception $e) {
            if ($this->isConnectionResetError($e)) {
                $this->alert('info', 'Please Wait Re-trying Sync Items', [
                    'position' => 'top-right',
                    'timer' => 3000,
                    'toast' => true,
                    'timerProgressBar' => true,
                ]);
                $this->reDoFunction('sapGetSalesEmp');
            } else {
                $this->alert('error', 'No Internet Connection to Sync', [
                    'position' => 'top-end',
                    'timer' => 5000,
                    'toast' => true,
                    'timerProgressBar' => true,
                ]);
            }
        }

        $this->isloading = false;
        $this->dispatch('successsync');
    }

    #[On('successsync')]
    public function successsync()
    {
        sleep(1);
        return $this->redirect('salesemp');
    }
}
