<?php

namespace App\Traits;

use App\Models\ItemTemp;
use App\Models\Settings;
use App\Models\Warehouse;
use Carbon\Carbon;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Schema;

trait GetItemITRTraits
{

    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 getItem()
    {
        try {
            $this->isloading = true;
            $this->dispatch('refresh');
            $now = Carbon::now()->toDateString();
            $user = Auth::user();
            $setting = Settings::where('wh_code', $user->whs_code)->first();
            $wh = Warehouse::where('code', $user->whs_code)->first();
            $userId = auth()->user()->id;
            $url = $setting->url;
            $whscode = $setting->wh_code;
            $id_pricelist = $wh->id_pricelist;
            $member_pricelist = $setting->member;
            if ($member_pricelist != '0') {
                $response = Http::post($url . '/api/search', [
                    "Select" => "b.\"ItemCode\" as \"code\",c.\"CodeBars\" as \"barcode\",c.\"ItemName\" as \"name\",c.\"ItmsGrpCod\" as \"group_code\",'" . $userId . "' as \"id_user\",'" . $id_pricelist . "' as \"idprice1\",ifnull((select \"Price\" from ITM1 where \"ItemCode\"=b.\"ItemCode\" and \"PriceList\"='" . $id_pricelist . "'),0) \"price1\",'" . $member_pricelist . "' as \"idprice2\",ifnull((select \"Price\" from ITM1 where \"ItemCode\"=b.\"ItemCode\" and \"PriceList\"='" . $member_pricelist . "'),0) \"price2\" , c.\"InvntItem\" as \"inventory\" , c.\"PrchseItem\" as \"purchase\" , c.\"SellItem\" as \"sales\", case when case when \"frozenFrom\" is null and \"frozenTo\" is null then \"frozenFor\" else case when '" . $now . "' between \"frozenFor\" and \"frozenTo\" then 'N' else 'Y' end end = 'Y' then 'N' else 'Y' end as \"active\"",
                    "From" => "OWTQ a inner join WTQ1 b on a.\"DocEntry\"= b.\"DocEntry\" inner join OITM c on b.\"ItemCode\"=c.\"ItemCode\"",
                    "Where" => "b.\"WhsCode\"='" . $whscode . "' group by b.\"ItemCode\",c.\"CodeBars\",c.\"ItemName\",c.\"ItmsGrpCod\", c.\"InvntItem\", c.\"PrchseItem\", c.\"SellItem\", c.\"frozenFor\",c.\"frozenFrom\",c.\"frozenTo\"",
                ]);
            } else {
                $response = Http::post($url . '/api/search', [
                    "Select" => "b.\"ItemCode\" as \"code\",c.\"CodeBars\" as \"barcode\",c.\"ItemName\" as \"name\",c.\"ItmsGrpCod\" as \"group_code\",'" . $userId . "' as \"id_user\",'" . $id_pricelist . "' as \"idprice1\",ifnull((select \"Price\" from ITM1 where \"ItemCode\"=b.\"ItemCode\" and \"PriceList\"='" . $id_pricelist . "'),0) \"price1\",'0' as \"idprice2\",0 \"price2\" , c.\"InvntItem\" as \"inventory\" , c.\"PrchseItem\" as \"purchase\" , c.\"SellItem\" as \"sales\" , case when case when \"frozenFrom\" is null and \"frozenTo\" is null then \"frozenFor\" else case when '" . $now . "' between \"frozenFor\" and \"frozenTo\" then 'N' else 'Y' end end = 'Y' then 'N' else 'Y' end as \"active\"",
                    "From" => "OWTQ a inner join WTQ1 b on a.\"DocEntry\"= b.\"DocEntry\" inner join OITM c on b.\"ItemCode\"=c.\"ItemCode\"",
                    "Where" => "b.\"WhsCode\"='" . $whscode . "' group by b.\"ItemCode\",c.\"CodeBars\",c.\"ItemName\",c.\"ItmsGrpCod\", c.\"InvntItem\", c.\"PrchseItem\", c.\"SellItem\", c.\"frozenFor\",c.\"frozenFrom\",c.\"frozenTo\"",
                ]);
            }


            if ($response->successful()) {
                $jsonData = $response->json();
                ItemTemp::where('id_user', $userId)->delete();
                if ($jsonData[0]['code'] != '') {
                    if (!empty($jsonData)) {
                        $chunks = array_chunk($jsonData, 1000);

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

                            foreach ($chunk as $item) {
                                $insertData[] = [
                                    'code' => $item['code'],
                                    'barcode' => $item['barcode'],
                                    'name' => $item['name'],
                                    'group_code' => $item['group_code'],
                                    'id_user' => $userId,
                                    'idprice1' => $item['idprice1'],
                                    'price1' => $item['price1'],
                                    'idprice2' => $item['idprice2'],
                                    'price2' => $item['price2'],
                                    'inventory' => $item['inventory'],
                                    'sales' => $item['sales'],
                                    'purchase' => $item['purchase'],
                                ];
                            }
                            DB::table('Luv2_item_temp')->insert($insertData);
                        }
                    }


                    #insert item
                    DB::statement("
                    INSERT INTO \"Luv2_item\" (\"code\", \"barcode\", \"name\", \"group_code\", \"inventory\", \"sales\", \"purchase\" ) 
                    SELECT DISTINCT \"code\", \"barcode\", \"name\", \"group_code\", \"inventory\", \"sales\", \"purchase\"
                    FROM \"Luv2_item_temp\"
                    WHERE NOT EXISTS (
                        SELECT 1 FROM \"Luv2_item\" WHERE \"Luv2_item\".\"code\" = \"Luv2_item_temp\".\"code\") and \"Luv2_item_temp\".\"id_user\"='" . $userId . "' 
                ");

                    #update item
                    DB::statement("
                    UPDATE \"Luv2_item\"
                    SET \"barcode\"=\"Luv2_item_temp\".\"barcode\",\"name\"=\"Luv2_item_temp\".\"name\",\"group_code\"=\"Luv2_item_temp\".\"group_code\", \"inventory\"=\"Luv2_item_temp\".\"inventory\", \"sales\"=\"Luv2_item_temp\".\"sales\", \"purchase\"=\"Luv2_item_temp\".\"purchase\"
                    FROM \"Luv2_item_temp\"
                    WHERE \"Luv2_item_temp\".\"code\"=\"Luv2_item\".\"code\" AND \"Luv2_item_temp\".\"id_user\"='" . $userId . "'
                    AND (
                        \"Luv2_item_temp\".\"barcode\"<>\"Luv2_item\".\"barcode\" OR
                        \"Luv2_item_temp\".\"name\"<>\"Luv2_item\".\"name\" OR
                        \"Luv2_item_temp\".\"group_code\"<>\"Luv2_item\".\"group_code\" OR
                        \"Luv2_item_temp\".\"inventory\"<>\"Luv2_item\".\"inventory\" OR
                        \"Luv2_item_temp\".\"sales\"<>\"Luv2_item\".\"sales\" OR
                        \"Luv2_item_temp\".\"purchase\"<>\"Luv2_item\".\"purchase\"
                    );
                ");

                    #insert price1
                    DB::statement("
                    INSERT INTO \"Luv2_item_pricelist\" (\"item_code\", \"id_pricelist\", \"price\") 
                    SELECT DISTINCT \"code\", \"idprice1\", \"price1\"
                    FROM \"Luv2_item_temp\"
                    WHERE NOT EXISTS (
                        SELECT 1 FROM \"Luv2_item_pricelist\" WHERE \"Luv2_item_pricelist\".\"item_code\" = \"Luv2_item_temp\".\"code\" and \"Luv2_item_pricelist\".\"id_pricelist\" = \"Luv2_item_temp\".\"idprice1\") and \"Luv2_item_temp\".\"id_user\"='" . $userId . "'
                ");

                    #update price1
                    DB::statement("
                    UPDATE \"Luv2_item_pricelist\"
                    SET \"price\"=\"Luv2_item_temp\".\"price1\"
                    FROM \"Luv2_item_temp\"
                    WHERE \"Luv2_item_temp\".\"code\"=\"Luv2_item_pricelist\".\"item_code\" AND \"Luv2_item_temp\".\"idprice1\"=\"Luv2_item_pricelist\".\"id_pricelist\" AND \"Luv2_item_temp\".\"id_user\"='" . $userId . "'
                    AND \"Luv2_item_temp\".\"price1\"<>\"Luv2_item_pricelist\".\"price\";
                ");

                    if ($member_pricelist != 0) {
                        #insert price2
                        DB::statement("
                        INSERT INTO \"Luv2_item_pricelist\" (\"item_code\", \"id_pricelist\", \"price\") 
                        SELECT DISTINCT \"code\", \"idprice2\", \"price2\"
                        FROM \"Luv2_item_temp\"
                        WHERE NOT EXISTS (
                            SELECT 1 FROM \"Luv2_item_pricelist\" WHERE \"Luv2_item_pricelist\".\"item_code\" = \"Luv2_item_temp\".\"code\") and \"Luv2_item_pricelist\".\"id_pricelist\" = \"Luv2_item_temp\".\"idprice2\" and \"Luv2_item_temp\".\"id_user\"='" . $userId . "'
                    ");

                        #update price2
                        DB::statement("
                        UPDATE \"Luv2_item_pricelist\"
                        SET \"price\"=\"Luv2_item_temp\".\"price2\"
                        FROM \"Luv2_item_temp\"
                        WHERE \"Luv2_item_temp\".\"code\"=\"Luv2_item_pricelist\".\"item_code\" AND \"Luv2_item_temp\".\"idprice2\"=\"Luv2_item_pricelist\".\"id_pricelist\" AND \"Luv2_item_temp\".\"id_user\"='" . $userId . "'
                        AND \"Luv2_item_temp\".\"price2\"<>\"Luv2_item_pricelist\".\"price\";
                    ");
                    }

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

                    $this->alert('success', 'Data Item Synchrone succesfully', [
                        'position' => 'top-right',
                        'timer' => 3000,
                        'toast' => true,
                        'timerProgressBar' => true,
                    ]);
                    $this->dispatch('disableButton');
                    $this->dispatch('redirectTo');
                } else {
                    $this->alert('info', 'Theres no data to synchrone', [
                        'position' => 'top-right',
                        'timer' => 3000,
                        'toast' => true,
                        'timerProgressBar' => true,
                    ]);
                    $this->isloading = false;
                    $this->dispatch('disableButton');
                }
            }
        } 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('getItem');
            } else {
                throw $e;
            }
        }
    }

    public function getItemWithFilter()
    {
        try {
            $this->isloading = true;
            $this->dispatch('refresh');
            $now = Carbon::now()->toDateString();
            $user = Auth::user();
            $setting = Settings::where('wh_code', $user->whs_code)->first();
            $wh = Warehouse::where('code', $user->whs_code)->first();
            $userId = auth()->user()->id;
            $url = $setting->url;
            $whscode = $setting->wh_code;
            $id_pricelist = $wh->id_pricelist;
            $member_pricelist = $setting->member;
            if ($member_pricelist != '0') {
                $response = Http::post($url . '/api/search', [
                    "Select" => "b.\"ItemCode\" as \"code\",c.\"CodeBars\" as \"barcode\",c.\"ItemName\" as \"name\",c.\"ItmsGrpCod\" as \"group_code\",'" . $userId . "' as \"id_user\",'" . $id_pricelist . "' as \"idprice1\",ifnull((select \"Price\" from ITM1 where \"ItemCode\"=b.\"ItemCode\" and \"PriceList\"='" . $id_pricelist . "'),0) \"price1\",'" . $member_pricelist . "' as \"idprice2\",ifnull((select \"Price\" from ITM1 where \"ItemCode\"=b.\"ItemCode\" and \"PriceList\"='" . $member_pricelist . "'),0) \"price2\" , c.\"InvntItem\" as \"inventory\" , c.\"PrchseItem\" as \"purchase\" , c.\"SellItem\" as \"sales\", case when case when \"frozenFrom\" is null and \"frozenTo\" is null then \"frozenFor\" else case when '" . $now . "' between \"frozenFor\" and \"frozenTo\" then 'N' else 'Y' end end = 'Y' then 'N' else 'Y' end as \"active\"",
                    "From" => "OWTQ a inner join WTQ1 b on a.\"DocEntry\"= b.\"DocEntry\" inner join OITM c on b.\"ItemCode\"=c.\"ItemCode\"",
                    "Where" => "b.\"WhsCode\"='" . $whscode . "' and a.\"DocDate\" BETWEEN '" . $this->startDate . "' and '" . $this->endDate . "' group by b.\"ItemCode\",c.\"CodeBars\",c.\"ItemName\",c.\"ItmsGrpCod\", c.\"InvntItem\", c.\"PrchseItem\", c.\"SellItem\", c.\"frozenFor\",c.\"frozenFrom\",c.\"frozenTo\"",
                ]);
            } else {
                $response = Http::post($url . '/api/search', [
                    "Select" => "b.\"ItemCode\" as \"code\",c.\"CodeBars\" as \"barcode\",c.\"ItemName\" as \"name\",c.\"ItmsGrpCod\" as \"group_code\",'" . $userId . "' as \"id_user\",'" . $id_pricelist . "' as \"idprice1\",ifnull((select \"Price\" from ITM1 where \"ItemCode\"=b.\"ItemCode\" and \"PriceList\"='" . $id_pricelist . "'),0) \"price1\",'0' as \"idprice2\",0 \"price2\" , c.\"InvntItem\" as \"inventory\" , c.\"PrchseItem\" as \"purchase\" , c.\"SellItem\" as \"sales\" , case when case when \"frozenFrom\" is null and \"frozenTo\" is null then \"frozenFor\" else case when '" . $now . "' between \"frozenFor\" and \"frozenTo\" then 'N' else 'Y' end end = 'Y' then 'N' else 'Y' end as \"active\"",
                    "From" => "OWTQ a inner join WTQ1 b on a.\"DocEntry\"= b.\"DocEntry\" inner join OITM c on b.\"ItemCode\"=c.\"ItemCode\"",
                    "Where" => "b.\"WhsCode\"='" . $whscode . "' and a.\"DocDate\" BETWEEN '" . $this->startDate . "' and '" . $this->endDate . "' group by b.\"ItemCode\",c.\"CodeBars\",c.\"ItemName\",c.\"ItmsGrpCod\", c.\"InvntItem\", c.\"PrchseItem\", c.\"SellItem\", c.\"frozenFor\",c.\"frozenFrom\",c.\"frozenTo\"",
                ]);
            }

            if ($response->successful()) {
                $jsonData = $response->json();
                ItemTemp::where('id_user', $userId)->delete();
                if ($jsonData[0]['code'] != '') {
                    if (!empty($jsonData)) {
                        $chunks = array_chunk($jsonData, 1000);

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

                            foreach ($chunk as $item) {
                                $insertData[] = [
                                    'code' => $item['code'],
                                    'barcode' => $item['barcode'],
                                    'name' => $item['name'],
                                    'group_code' => $item['group_code'],
                                    'id_user' => $userId,
                                    'idprice1' => $item['idprice1'],
                                    'price1' => $item['price1'],
                                    'idprice2' => $item['idprice2'],
                                    'price2' => $item['price2'],
                                    'inventory' => $item['inventory'],
                                    'sales' => $item['sales'],
                                    'purchase' => $item['purchase'],
                                ];
                            }
                            DB::table('Luv2_item_temp')->insert($insertData);
                        }
                    }

                    #insert item
                    DB::statement("
                        INSERT INTO \"Luv2_item\" (\"code\", \"barcode\", \"name\", \"group_code\", \"inventory\", \"sales\", \"purchase\" ) 
                        SELECT DISTINCT \"code\", \"barcode\", \"name\", \"group_code\", \"inventory\", \"sales\", \"purchase\"
                        FROM \"Luv2_item_temp\"
                        WHERE NOT EXISTS (
                            SELECT 1 FROM \"Luv2_item\" WHERE \"Luv2_item\".\"code\" = \"Luv2_item_temp\".\"code\") and \"Luv2_item_temp\".\"id_user\"='" . $userId . "'
                    ");

                    #update item
                    DB::statement("
                        UPDATE \"Luv2_item\"
                        SET \"barcode\"=\"Luv2_item_temp\".\"barcode\",\"name\"=\"Luv2_item_temp\".\"name\",\"group_code\"=\"Luv2_item_temp\".\"group_code\", \"inventory\"=\"Luv2_item_temp\".\"inventory\", \"sales\"=\"Luv2_item_temp\".\"sales\", \"purchase\"=\"Luv2_item_temp\".\"purchase\"
                        FROM \"Luv2_item_temp\"
                        WHERE \"Luv2_item_temp\".\"code\"=\"Luv2_item\".\"code\" AND \"Luv2_item_temp\".\"id_user\"='" . $userId . "'
                        AND (
                            \"Luv2_item_temp\".\"barcode\"<>\"Luv2_item\".\"barcode\" OR
                            \"Luv2_item_temp\".\"name\"<>\"Luv2_item\".\"name\" OR
                            \"Luv2_item_temp\".\"group_code\"<>\"Luv2_item\".\"group_code\" OR
                            \"Luv2_item_temp\".\"inventory\"<>\"Luv2_item\".\"inventory\" OR
                            \"Luv2_item_temp\".\"sales\"<>\"Luv2_item\".\"sales\" OR
                            \"Luv2_item_temp\".\"purchase\"<>\"Luv2_item\".\"purchase\"
                        );
                    ");

                    #insert price1
                    DB::statement("
                        INSERT INTO \"Luv2_item_pricelist\" (\"item_code\", \"id_pricelist\", \"price\") 
                        SELECT DISTINCT \"code\", \"idprice1\", \"price1\"
                        FROM \"Luv2_item_temp\"
                        WHERE NOT EXISTS (
                            SELECT 1 FROM \"Luv2_item_pricelist\" WHERE \"Luv2_item_pricelist\".\"item_code\" = \"Luv2_item_temp\".\"code\" and \"Luv2_item_pricelist\".\"id_pricelist\" = \"Luv2_item_temp\".\"idprice1\") and \"Luv2_item_temp\".\"id_user\"='" . $userId . "'
                    ");

                    #update price1
                    DB::statement("
                        UPDATE \"Luv2_item_pricelist\"
                        SET \"price\"=\"Luv2_item_temp\".\"price1\"
                        FROM \"Luv2_item_temp\"
                        WHERE \"Luv2_item_temp\".\"code\"=\"Luv2_item_pricelist\".\"item_code\" AND \"Luv2_item_temp\".\"idprice1\"=\"Luv2_item_pricelist\".\"id_pricelist\" AND \"Luv2_item_temp\".\"id_user\"='" . $userId . "'
                        AND \"Luv2_item_temp\".\"price1\"<>\"Luv2_item_pricelist\".\"price\";
                    ");

                    if ($member_pricelist != 0) {
                        #insert price2
                        DB::statement("
                            INSERT INTO \"Luv2_item_pricelist\" (\"item_code\", \"id_pricelist\", \"price\") 
                            SELECT DISTINCT \"code\", \"idprice2\", \"price2\"
                            FROM \"Luv2_item_temp\"
                            WHERE NOT EXISTS (
                                SELECT 1 FROM \"Luv2_item_pricelist\" WHERE \"Luv2_item_pricelist\".\"item_code\" = \"Luv2_item_temp\".\"code\" and \"Luv2_item_pricelist\".\"id_pricelist\" = \"Luv2_item_temp\".\"idprice2\") and \"Luv2_item_temp\".\"id_user\"='" . $userId . "'
                        ");

                        #update price2
                        DB::statement("
                            UPDATE \"Luv2_item_pricelist\"
                            SET \"price\"=\"Luv2_item_temp\".\"price2\"
                            FROM \"Luv2_item_temp\"
                            WHERE \"Luv2_item_temp\".\"code\"=\"Luv2_item_pricelist\".\"item_code\" AND \"Luv2_item_temp\".\"idprice2\"=\"Luv2_item_pricelist\".\"id_pricelist\" AND \"Luv2_item_temp\".\"id_user\"='" . $userId . "'
                            AND \"Luv2_item_temp\".\"price2\"<>\"Luv2_item_pricelist\".\"price\";
                        ");
                    }


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

                    $this->alert('success', 'Data Item Synchrone succesfully', [
                        'position' => 'top-right',
                        'timer' => 3000,
                        'toast' => true,
                        'timerProgressBar' => true,
                    ]);
                    $this->dispatch('disableButton');
                    $this->dispatch('redirectTo');
                } else {
                    $this->alert('info', 'Theres no data to synchrone', [
                        'position' => 'top-right',
                        'timer' => 3000,
                        'toast' => true,
                        'timerProgressBar' => true,
                    ]);
                    $this->isloading = false;
                    $this->dispatch('disableButton');
                }
            }
        } 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,
                ]);
                // Do something or re-do the function
                $this->reDoFunction('getItemWithFilter');
            } else {
                // Handle other errors
                throw $e; // Re-throw the error
            }
        }
    }

    public function getItemWhereDocnum()
    {
        try {
            $this->isloading = true;
            $this->dispatch('refresh');
            $now = Carbon::now()->toDateString();
            $user = Auth::user();
            $setting = Settings::where('wh_code', $user->whs_code)->first();
            $wh = Warehouse::where('code', $user->whs_code)->first();
            $userId = auth()->user()->id;
            $url = $setting->url;
            $whscode = $setting->wh_code;
            $id_pricelist = $wh->id_pricelist;
            $member_pricelist = $setting->member;
            if ($member_pricelist != '0') {
                $response = Http::post($url . '/api/search', [
                    "Select" => "b.\"ItemCode\" as \"code\",c.\"CodeBars\" as \"barcode\",c.\"ItemName\" as \"name\",c.\"ItmsGrpCod\" as \"group_code\",'" . $userId . "' as \"id_user\",'" . $id_pricelist . "' as \"idprice1\",ifnull((select \"Price\" from ITM1 where \"ItemCode\"=b.\"ItemCode\" and \"PriceList\"='" . $id_pricelist . "'),0) \"price1\",'" . $member_pricelist . "' as \"idprice2\",ifnull((select \"Price\" from ITM1 where \"ItemCode\"=b.\"ItemCode\" and \"PriceList\"='" . $member_pricelist . "'),0) \"price2\" , c.\"InvntItem\" as \"inventory\" , c.\"PrchseItem\" as \"purchase\" , c.\"SellItem\" as \"sales\", case when case when \"frozenFrom\" is null and \"frozenTo\" is null then \"frozenFor\" else case when '" . $now . "' between \"frozenFor\" and \"frozenTo\" then 'N' else 'Y' end end = 'Y' then 'N' else 'Y' end as \"active\"",
                    "From" => "OWTQ a inner join WTQ1 b on a.\"DocEntry\"= b.\"DocEntry\" inner join OITM c on b.\"ItemCode\"=c.\"ItemCode\"",
                    "Where" => "b.\"WhsCode\"='" . $whscode . "' and a.\"DocNum\" = '" . $this->docNum . "' group by b.\"ItemCode\",c.\"CodeBars\",c.\"ItemName\",c.\"ItmsGrpCod\", c.\"InvntItem\", c.\"PrchseItem\", c.\"SellItem\", c.\"frozenFor\",c.\"frozenFrom\",c.\"frozenTo\"",
                ]);
            } else {
                $response = Http::post($url . '/api/search', [
                    "Select" => "b.\"ItemCode\" as \"code\",c.\"CodeBars\" as \"barcode\",c.\"ItemName\" as \"name\",c.\"ItmsGrpCod\" as \"group_code\",'" . $userId . "' as \"id_user\",'" . $id_pricelist . "' as \"idprice1\",ifnull((select \"Price\" from ITM1 where \"ItemCode\"=b.\"ItemCode\" and \"PriceList\"='" . $id_pricelist . "'),0) \"price1\",'0' as \"idprice2\",0 \"price2\" , c.\"InvntItem\" as \"inventory\" , c.\"PrchseItem\" as \"purchase\" , c.\"SellItem\" as \"sales\" , case when case when \"frozenFrom\" is null and \"frozenTo\" is null then \"frozenFor\" else case when '" . $now . "' between \"frozenFor\" and \"frozenTo\" then 'N' else 'Y' end end = 'Y' then 'N' else 'Y' end as \"active\"",
                    "From" => "OWTQ a inner join WTQ1 b on a.\"DocEntry\"= b.\"DocEntry\" inner join OITM c on b.\"ItemCode\"=c.\"ItemCode\"",
                    "Where" => "b.\"WhsCode\"='" . $whscode . "' and a.\"DocNum\" = '" . $this->docNum . "' group by b.\"ItemCode\",c.\"CodeBars\",c.\"ItemName\",c.\"ItmsGrpCod\", c.\"InvntItem\", c.\"PrchseItem\", c.\"SellItem\", c.\"frozenFor\",c.\"frozenFrom\",c.\"frozenTo\"",
                ]);
            }


            if ($response->successful()) {
                $jsonData = $response->json();
                ItemTemp::where('id_user', $userId)->delete();
                if ($jsonData[0]['code'] != '') {
                    if (!empty($jsonData)) {
                        $chunks = array_chunk($jsonData, 1000);

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

                            foreach ($chunk as $item) {
                                $insertData[] = [
                                    'code' => $item['code'],
                                    'barcode' => $item['barcode'],
                                    'name' => $item['name'],
                                    'group_code' => $item['group_code'],
                                    'id_user' => $userId,
                                    'idprice1' => $item['idprice1'],
                                    'price1' => $item['price1'],
                                    'idprice2' => $item['idprice2'],
                                    'price2' => $item['price2'],
                                    'inventory' => $item['inventory'],
                                    'sales' => $item['sales'],
                                    'purchase' => $item['purchase'],
                                ];
                            }
                            DB::table('Luv2_item_temp')->insert($insertData);
                        }
                    }


                    #insert item
                    DB::statement("
                    INSERT INTO \"Luv2_item\" (\"code\", \"barcode\", \"name\", \"group_code\", \"inventory\", \"sales\", \"purchase\" ) 
                    SELECT DISTINCT \"code\", \"barcode\", \"name\", \"group_code\", \"inventory\", \"sales\", \"purchase\"
                    FROM \"Luv2_item_temp\"
                    WHERE NOT EXISTS (
                        SELECT 1 FROM \"Luv2_item\" WHERE \"Luv2_item\".\"code\" = \"Luv2_item_temp\".\"code\") and \"Luv2_item_temp\".\"id_user\"='" . $userId . "' 
                ");

                    #update item
                    DB::statement("
                    UPDATE \"Luv2_item\"
                    SET \"barcode\"=\"Luv2_item_temp\".\"barcode\",\"name\"=\"Luv2_item_temp\".\"name\",\"group_code\"=\"Luv2_item_temp\".\"group_code\", \"inventory\"=\"Luv2_item_temp\".\"inventory\", \"sales\"=\"Luv2_item_temp\".\"sales\", \"purchase\"=\"Luv2_item_temp\".\"purchase\"
                    FROM \"Luv2_item_temp\"
                    WHERE \"Luv2_item_temp\".\"code\"=\"Luv2_item\".\"code\" AND \"Luv2_item_temp\".\"id_user\"='" . $userId . "'
                    AND (
                        \"Luv2_item_temp\".\"barcode\"<>\"Luv2_item\".\"barcode\" OR
                        \"Luv2_item_temp\".\"name\"<>\"Luv2_item\".\"name\" OR
                        \"Luv2_item_temp\".\"group_code\"<>\"Luv2_item\".\"group_code\" OR
                        \"Luv2_item_temp\".\"inventory\"<>\"Luv2_item\".\"inventory\" OR
                        \"Luv2_item_temp\".\"sales\"<>\"Luv2_item\".\"sales\" OR
                        \"Luv2_item_temp\".\"purchase\"<>\"Luv2_item\".\"purchase\"
                    );
                ");

                    #insert price1
                    DB::statement("
                    INSERT INTO \"Luv2_item_pricelist\" (\"item_code\", \"id_pricelist\", \"price\") 
                    SELECT DISTINCT \"code\", \"idprice1\", \"price1\"
                    FROM \"Luv2_item_temp\"
                    WHERE NOT EXISTS (
                        SELECT 1 FROM \"Luv2_item_pricelist\" WHERE \"Luv2_item_pricelist\".\"item_code\" = \"Luv2_item_temp\".\"code\" and \"Luv2_item_pricelist\".\"id_pricelist\" = \"Luv2_item_temp\".\"idprice1\") and \"Luv2_item_temp\".\"id_user\"='" . $userId . "'
                ");

                    #update price1
                    DB::statement("
                    UPDATE \"Luv2_item_pricelist\"
                    SET \"price\"=\"Luv2_item_temp\".\"price1\"
                    FROM \"Luv2_item_temp\"
                    WHERE \"Luv2_item_temp\".\"code\"=\"Luv2_item_pricelist\".\"item_code\" AND \"Luv2_item_temp\".\"idprice1\"=\"Luv2_item_pricelist\".\"id_pricelist\" AND \"Luv2_item_temp\".\"id_user\"='" . $userId . "'
                    AND \"Luv2_item_temp\".\"price1\"<>\"Luv2_item_pricelist\".\"price\";
                ");

                    if ($member_pricelist != 0) {
                        #insert price2
                        DB::statement("
                            INSERT INTO \"Luv2_item_pricelist\" (\"item_code\", \"id_pricelist\", \"price\") 
                            SELECT DISTINCT \"code\", \"idprice2\", \"price2\"
                            FROM \"Luv2_item_temp\"
                            WHERE NOT EXISTS (
                                SELECT 1 FROM \"Luv2_item_pricelist\" WHERE \"Luv2_item_pricelist\".\"item_code\" = \"Luv2_item_temp\".\"code\" and \"Luv2_item_pricelist\".\"id_pricelist\" = \"Luv2_item_temp\".\"idprice2\") and \"Luv2_item_temp\".\"id_user\"='" . $userId . "'
                        ");

                        #update price2
                        DB::statement("
                            UPDATE \"Luv2_item_pricelist\"
                            SET \"price\"=\"Luv2_item_temp\".\"price2\"
                            FROM \"Luv2_item_temp\"
                            WHERE \"Luv2_item_temp\".\"code\"=\"Luv2_item_pricelist\".\"item_code\" AND \"Luv2_item_temp\".\"idprice2\"=\"Luv2_item_pricelist\".\"id_pricelist\" AND \"Luv2_item_temp\".\"id_user\"='" . $userId . "'
                            AND \"Luv2_item_temp\".\"price2\"<>\"Luv2_item_pricelist\".\"price\";
                        ");
                    }
                    ItemTemp::where('id_user', $userId)->delete();

                    $this->alert('success', 'Data Item Synchrone succesfully', [
                        'position' => 'top-right',
                        'timer' => 3000,
                        'toast' => true,
                        'timerProgressBar' => true,
                    ]);
                    $this->dispatch('disableButton');
                    $this->dispatch('redirectTo');
                } else {
                    $this->alert('info', 'Theres no data item to synchrone', [
                        'position' => 'top-right',
                        'timer' => 3000,
                        'toast' => true,
                        'timerProgressBar' => true,
                    ]);
                    $this->isloading = false;
                    $this->dispatch('disableButton');
                }
            }
        } 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,
                ]);
                // Do something or re-do the function
                $this->reDoFunction('getItemWhereDocnum');
            } else {
                // Handle other errors
                throw $e; // Re-throw the error
            }
        }
    }

    // public function simpan()
    // {
    //     $response = Http::post($url . '/api/search', [
    //         "Select" => "b.\"ItemCode\" as \"code\",c.\"CodeBars\" as \"barcode\",c.\"ItemName\" as \"name\",c.\"ItmsGrpCod\" as \"group_code\",'" . $userId . "' as \"id_user\",'" . $id_pricelist . "' as \"idprice1\",ifnull((select \"Price\" from ITM1 where \"ItemCode\"=b.\"ItemCode\" and \"PriceList\"='" . $id_pricelist . "'),0) \"price1\",'" . $member_pricelist . "' as \"idprice2\",ifnull((select \"Price\" from ITM1 where \"ItemCode\"=b.\"ItemCode\" and \"PriceList\"='" . $member_pricelist . "'),0) \"price2\" , c.\"InvntItem\" as \"inventory\" , c.\"PrchseItem\" as \"purchase\" , c.\"SellItem\" as \"sales\", case when case when \"frozenFrom\" is null and \"frozenTo\" is null then \"frozenFor\" else case when '" . $now . "' between \"frozenFor\" and \"frozenTo\" then 'N' else 'Y' end end = 'Y' then 'N' else 'Y' end as \"active\"",
    //         "From" => "OWTQ a inner join WTQ1 b on a.\"DocEntry\"= b.\"DocEntry\" inner join OITM c on b.\"ItemCode\"=c.\"ItemCode\"",
    //         "Where" => "b.\"WhsCode\"='" . $whscode . "' group by b.\"ItemCode\",c.\"CodeBars\",c.\"ItemName\",c.\"ItmsGrpCod\", c.\"InvntItem\", c.\"PrchseItem\", c.\"SellItem\", c.\"frozenFor\",c.\"frozenFrom\",c.\"frozenTo\"",
    //     ]);
    // }
}
