<?php

namespace App\Livewire\Pos\It\ItIn;

use App\Models\ItemTemp;
use App\Models\ItInTemp;
use App\Models\Settings;
use App\Models\Warehouse;
use App\Traits\GetItemTraits;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\On;
use Illuminate\Support\Facades\Http;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Component;

class Syncit extends Component
{    
    use LivewireAlert;
    use GetItemTraits;

    public $startDate;
    public $endDate;
    public $docNum;
    public $isloading = false;
    public $isCheckedAll = true;
    public $isPeriod = false;
    public $isDocnum = false;
    public $selectedFilter;
    
    public function render()
    {
        return view('livewire.pos.it.itin.syncit');
    }

    
    public function mount()
    {
        $this->startDate = Carbon::now()->toDateString();
        $this->endDate = Carbon::now()->toDateString();
    }

    public function updatedIsCheckedAll($value)
    {
        if ($value) {
            $this->isPeriod = false;
            $this->isDocnum = false;
        } else {
            $this->isPeriod = true;
        }
    }
    public function firstClick()
    {

        $this->isloading = true;
        if ($this->isPeriod && !$this->isDocnum && !$this->isCheckedAll) {
            $this->dispatch('filterItIn');
        } elseif (!$this->isPeriod && $this->isDocnum && !$this->isCheckedAll) {
            $this->dispatch('filterItIn');
        } elseif ($this->isCheckedAll && !$this->isDocnum && !$this->isPeriod) {
            $this->dispatch('notFilterItIn');
        } else {

        }
    }

    public function updatedSelectedFilter($value)
    {
        if ($value === 'Period') {
            $this->isPeriod = true;
            $this->isDocnum = false;
        } elseif ($value === 'Docnum') {
            $this->isPeriod = false;
            $this->isDocnum = true;
        }
    }

    #[On('notFilterItIn')]
    public function sapGetItIn()
    {
        set_time_limit(2000);

        $this->isloading = true;

        $user = Auth::user();
        $setting = Settings::where('wh_code', $user->whs_code)->first();
        $userId = auth()->user()->id;
        $url = $setting->url;
        $whscode = $setting->wh_code;
       
            $response = Http::post($url . '/api/search', [
                "Select" => "b.\"WhsCode\" as \"whs_code\",b.\"FromWhsCod\" as \"whs_code_from\", TO_CHAR(a.\"DocDate\", 'yyyy-MM-dd') as \"date\",a.\"Comments\" \"comments\",a.\"DocNum\" as \"no\",a.\"CANCELED\" as \"canceled\",'" . $userId . "' as \"id_user\" ",
                "From" => "OWTR a inner join WTR1 b on a.\"DocEntry\"=b.\"DocEntry\"",
                "Where" => "b.\"WhsCode\"='" . $whscode . "' group by b.\"WhsCode\", b.\"FromWhsCod\", a.\"DocDate\", a.\"Comments\", a.\"DocNum\", a.\"CANCELED\""
            ]);

            $responseDet = Http::post($url . '/api/search', [
                "Select" => "b.\"WhsCode\" as \"whs_code\",a.\"DocDate\" as \"date\",a.\"CANCELED\" \"canceled\",a.\"DocNum\" as \"no\",b.\"ItemCode\" as \"item_code\",b.\"Quantity\" as \"qty\",b.\"LineNum\" as \"linenum\",'" . $userId . "' as \"id_user\",c.\"CodeBars\" as \"item_barcode\",c.\"ItemName\" as \"item_name\",c.\"ItmsGrpCod\" as \"item_group_code\" ",
                "From" => "OWTR a inner join WTR1 b on a.\"DocEntry\"=b.\"DocEntry\" inner join OITM c on b.\"ItemCode\"=c.\"ItemCode\"",
                "Where" => "b.\"WhsCode\"='" . $whscode . "'",
            ]);

        if ($response->successful() && $responseDet->successful()) {
            $jsonData = $response->json();
            $jsonDataDet = $responseDet->json();
                if (!empty($jsonData)) {
                    ItInTemp::where('id_user', $userId)->delete();
                    $chunks = array_chunk($jsonData, 1000);
                    foreach ($chunks as $chunk) {
                        $insertData = [];
                        foreach ($chunk as $it) {
                            $insertData[] = [
                                'whs_code' => $it['whs_code'],
                                'whs_code_from' => $it['whs_code_from'],
                                'date' => $it['date'],
                                'comments' => $it['comments'],
                                'no' => $it['no'],
                                'canceled' => $it['canceled'],
                                'id_user' => $it['id_user'],
                            ];
                        }
                        DB::table('Luv2_it_in_temp')->insert($insertData);
                    }
    
                    $chunks = array_chunk($jsonDataDet, 1000);
    
                    foreach ($chunks as $chunk) {
                        $insertDataDet = [];
    
                        foreach ($chunk as $item) {
                            $insertDataDet[] = [
                                'no' => $item['no'],
                                'item_code' => $item['item_code'],
                                'qty' => $item['qty'],
                                'linenum' => $item['linenum'],
                                'id_user' => $item['id_user'],
                                'whs_code' => $item['whs_code'],
                                'date' => $item['date'],
                                'canceled' => $item['canceled'],
                            ];
                        }
    
                        DB::table('Luv2_it_in_temp_detail')->insert($insertDataDet);
                    }
    
                    #insert it
                    DB::statement("
                        INSERT INTO \"Luv2_it_in\" (\"whs_code\", \"whs_code_from\", \"date\", \"comments\", \"no\", \"canceled\", \"id_user\") 
                        SELECT \"whs_code\", \"whs_code_from\", \"date\", \"comments\", \"no\", \"canceled\", '" . $userId . "'
                        FROM \"Luv2_it_in_temp\"
                        WHERE NOT EXISTS (
                            SELECT 1 FROM \"Luv2_it_in\" WHERE \"Luv2_it_in\".\"no\" = \"Luv2_it_in_temp\".\"no\"
                        ) and \"Luv2_it_in_temp\".\"id_user\"='" . $userId . "' 
                    ");
    
                    #update it
                    DB::statement("
                        UPDATE \"Luv2_it_in\"
                        SET \"canceled\"=\"Luv2_it_in_temp\".\"canceled\"
                        FROM \"Luv2_it_in_temp\"
                        WHERE \"Luv2_it_in_temp\".\"no\"=\"Luv2_it_in\".\"no\"
                        AND \"Luv2_it_in_temp\".\"canceled\"<>\"Luv2_it_in\".\"canceled\";
                    ");
    
                    #insert it det
                    DB::statement("
                        INSERT INTO \"Luv2_it_in_detail\" (\"no\", \"item_code\", \"qty\", \"linenum\") 
                        SELECT \"no\", \"item_code\", \"qty\", \"linenum\"
                        FROM \"Luv2_it_in_temp_detail\"
                        WHERE NOT EXISTS (
                            SELECT 1 FROM \"Luv2_it_in_detail\" WHERE \"Luv2_it_in_detail\".\"no\" = \"Luv2_it_in_temp_detail\".\"no\" and \"Luv2_it_in_detail\".\"linenum\" = \"Luv2_it_in_temp_detail\".\"linenum\"
                        ) and \"Luv2_it_in_temp_detail\".\"id_user\"='" . $userId . "' 
                    ");
    
                    #insert item trans
                    DB::statement("
                        INSERT INTO \"Luv2_item_trans\" (\"whs_code\", \"no_trans\", \"tipe\", \"qty\", \"date\", \"canceled\", \"item_code\", \"linenum\") 
                        SELECT \"whs_code\", \"no\", '67', \"qty\", \"date\", \"canceled\", \"item_code\", \"linenum\"
                        FROM \"Luv2_it_in_temp_detail\"
                        WHERE NOT EXISTS (
                            SELECT 1 FROM \"Luv2_item_trans\" WHERE \"Luv2_item_trans\".\"no_trans\" = \"Luv2_it_in_temp_detail\".\"no\" and \"Luv2_item_trans\".\"linenum\" = \"Luv2_it_in_temp_detail\".\"linenum\" and \"Luv2_item_trans\".\"tipe\"='67'
                        ) and \"Luv2_it_in_temp_detail\".\"id_user\"='" . $userId . "' 
                    ");
    
                    ItInTemp::where('id_user', $userId)->delete();
                    $this->alert('success', 'Data IT In synchrone succesfully', [
                        'position' => 'top-right',
                        'timer' => 3000,
                        'toast' => true,
                        'timerProgressBar' => true,
                    ]);
                    $this->dispatch('disableButton');
                    $this->dispatch('tosyncItemsnofilter');
                } else {
                    $this->isloading = false;
                    $this->alert('info', 'Theres no data to synchrone', [
                        'position' => 'top-right',
                        'timer' => 3000,
                        'toast' => true,
                        'timerProgressBar' => true,
                    ]);
                }
            
            
        }
    }

    #[On('filterItIn')]
    public function sapGetItInisFilter()
    {
        $this->isloading = true;

        $user = Auth::user();
        $setting = Settings::where('wh_code', $user->whs_code)->first();
        $userId = auth()->user()->id;
        $url = $setting->url;
        $whscode = $setting->wh_code;
        if($this->isPeriod){
            $response = Http::post($url . '/api/search', [
                "Select" => "b.\"WhsCode\" as \"whs_code\",b.\"FromWhsCod\" as \"whs_code_from\", TO_CHAR(a.\"DocDate\", 'yyyy-MM-dd') as \"date\",a.\"Comments\" \"comments\",a.\"DocNum\" as \"no\",a.\"CANCELED\" as \"canceled\",'" . $userId . "' as \"id_user\" ",
                "From" => "OWTR a inner join WTR1 b on a.\"DocEntry\"=b.\"DocEntry\"",
                "Where" => "b.\"WhsCode\"='" . $whscode . "' and a.\"DocDate\" BETWEEN '" . $this->startDate . "' and '" . $this->endDate . "' group by b.\"WhsCode\", b.\"FromWhsCod\", a.\"DocDate\", a.\"Comments\", a.\"DocNum\", a.\"CANCELED\"",
                // "Where" => "\"ToWhsCode\"='" . $whscode . "' and \"DocDate\" = '" . $this->startDate . "'",
            ]);
    
            $responseDet = Http::post($url . '/api/search', [
                "Select" => "b.\"WhsCode\" as \"whs_code\",a.\"DocDate\" as \"date\",a.\"CANCELED\" \"canceled\",a.\"DocNum\" as \"no\",b.\"ItemCode\" as \"item_code\",b.\"Quantity\" as \"qty\",b.\"LineNum\" as \"linenum\",'" . $userId . "' as \"id_user\",c.\"CodeBars\" as \"item_barcode\",c.\"ItemName\" as \"item_name\",c.\"ItmsGrpCod\" as \"item_group_code\" ",
                "From" => "OWTR a inner join WTR1 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 . "'",
                // "Where" => "\"ToWhsCode\"='" . $whscode . "' and \"DocDate\" = '" . $this->startDate . "'",

            ]);  
        }elseif($this->isDocnum){
            $response = Http::post($url . '/api/search', [
                "Select" => "b.\"WhsCode\" as \"whs_code\",b.\"FromWhsCod\" as \"whs_code_from\", TO_CHAR(a.\"DocDate\", 'yyyy-MM-dd') as \"date\",a.\"Comments\" \"comments\",a.\"DocNum\" as \"no\",a.\"CANCELED\" as \"canceled\",'" . $userId . "' as \"id_user\" ",
                "From" => "OWTR a inner join WTR1 b on a.\"DocEntry\"=b.\"DocEntry\"",
                "Where" => "b.\"WhsCode\"='" . $whscode . "' and a.\"DocNum\" = '" . $this->docNum . "' group by b.\"WhsCode\", b.\"FromWhsCod\", a.\"DocDate\", a.\"Comments\", a.\"DocNum\", a.\"CANCELED\"",
            ]);
    
            $responseDet = Http::post($url . '/api/search', [
                "Select" => "b.\"WhsCode\" as \"whs_code\",a.\"DocDate\" as \"date\",a.\"CANCELED\" \"canceled\",a.\"DocNum\" as \"no\",b.\"ItemCode\" as \"item_code\",b.\"Quantity\" as \"qty\",b.\"LineNum\" as \"linenum\",'" . $userId . "' as \"id_user\",c.\"CodeBars\" as \"item_barcode\",c.\"ItemName\" as \"item_name\",c.\"ItmsGrpCod\" as \"item_group_code\" ",
                "From" => "OWTR a inner join WTR1 b on a.\"DocEntry\"=b.\"DocEntry\" inner join OITM c on b.\"ItemCode\"=c.\"ItemCode\"",
                "Where" => "b.\"WhsCode\"='" . $whscode . "' and a.\"DocNum\" = '" . $this->docNum . "'",
            ]);
        }
        if ($response->successful() && $responseDet->successful()) {
            $jsonData = $response->json();
            $jsonDataDet = $responseDet->json();
            if($jsonData[0]['whs_code'] !== '')
            {
                    ItInTemp::where('id_user', $userId)->delete();
                    $chunks = array_chunk($jsonData, 1000);
                    foreach ($chunks as $chunk) {
                        $insertData = [];
                        foreach ($chunk as $it) {
                            $insertData[] = [
                                'whs_code' => $it['whs_code'],
                                'whs_code_from' => $it['whs_code_from'],
                                'date' => $it['date'],
                                'comments' => $it['comments'],
                                'no' => $it['no'],
                                'canceled' => $it['canceled'],
                                'id_user' => $it['id_user'],
                            ];
                        }
                        DB::table('Luv2_it_in_temp')->insert($insertData);
                    }
    
                    $chunks = array_chunk($jsonDataDet, 1000);
    
                    foreach ($chunks as $chunk) {
                        $insertDataDet = [];
    
                        foreach ($chunk as $item) {
                            $insertDataDet[] = [
                                'no' => $item['no'],
                                'item_code' => $item['item_code'],
                                'qty' => $item['qty'],
                                'linenum' => $item['linenum'],
                                'id_user' => $item['id_user'],
                                'whs_code' => $item['whs_code'],
                                'date' => $item['date'],
                                'canceled' => $item['canceled'],
                            ];
                        }
    
                        DB::table('Luv2_it_in_temp_detail')->insert($insertDataDet);
                    }
    
                    #insert it
                    DB::statement("
                        INSERT INTO \"Luv2_it_in\" (\"whs_code\", \"whs_code_from\", \"date\", \"comments\", \"no\", \"canceled\", \"id_user\") 
                        SELECT \"whs_code\", \"whs_code_from\", \"date\", \"comments\", \"no\", \"canceled\", '" . $userId . "'
                        FROM \"Luv2_it_in_temp\"
                        WHERE NOT EXISTS (
                            SELECT 1 FROM \"Luv2_it_in\" WHERE \"Luv2_it_in\".\"no\" = \"Luv2_it_in_temp\".\"no\"
                        ) and \"Luv2_it_in_temp\".\"id_user\"='" . $userId . "' 
                    ");
    
                    #update it
                    DB::statement("
                        UPDATE \"Luv2_it_in\"
                        SET \"canceled\"=\"Luv2_it_in_temp\".\"canceled\"
                        FROM \"Luv2_it_in_temp\"
                        WHERE \"Luv2_it_in_temp\".\"no\"=\"Luv2_it_in\".\"no\"
                        AND \"Luv2_it_in_temp\".\"canceled\"<>\"Luv2_it_in\".\"canceled\";
                    ");
    
                    #insert it det
                    DB::statement("
                        INSERT INTO \"Luv2_it_in_detail\" (\"no\", \"item_code\", \"qty\", \"linenum\") 
                        SELECT \"no\", \"item_code\", \"qty\", \"linenum\"
                        FROM \"Luv2_it_in_temp_detail\"
                        WHERE NOT EXISTS (
                            SELECT 1 FROM \"Luv2_it_in_detail\" WHERE \"Luv2_it_in_detail\".\"no\" = \"Luv2_it_in_temp_detail\".\"no\" and \"Luv2_it_in_detail\".\"linenum\" = \"Luv2_it_in_temp_detail\".\"linenum\"
                        ) and \"Luv2_it_in_temp_detail\".\"id_user\"='" . $userId . "' 
                    ");
    
                    #insert item trans
                    DB::statement("
                        INSERT INTO \"Luv2_item_trans\" (\"whs_code\", \"no_trans\", \"tipe\", \"qty\", \"date\", \"canceled\", \"item_code\", \"linenum\") 
                        SELECT \"whs_code\", \"no\", '67', \"qty\", \"date\", \"canceled\", \"item_code\", \"linenum\"
                        FROM \"Luv2_it_in_temp_detail\"
                        WHERE NOT EXISTS (
                            SELECT 1 FROM \"Luv2_item_trans\" WHERE \"Luv2_item_trans\".\"no_trans\" = \"Luv2_it_in_temp_detail\".\"no\" and \"Luv2_item_trans\".\"linenum\" = \"Luv2_it_in_temp_detail\".\"linenum\" and \"Luv2_item_trans\".\"tipe\"='67'
                        ) and \"Luv2_it_in_temp_detail\".\"id_user\"='" . $userId . "' 
                    ");
    
                    ItInTemp::where('id_user', $userId)->delete();
                    $this->alert('success', 'Data IT In synchrone succesfully', [
                        'position' => 'top-right',
                        'timer' => 3000,
                        'toast' => true,
                        'timerProgressBar' => true,
                    ]);
                    $this->dispatch('disableButton');
                    $this->dispatch('tosyncItems');
                
            } else {
                $this->isloading = false;
                $this->alert('info', 'Data IT Not Found', [
                    'position' => 'top-right',
                    'timer' => 3000,
                    'toast' => true,
                    'timerProgressBar' => true,
                ]);
            }
            
        }
    }

    #[On('tosyncItemsnofilter')]
    public function toSyncnofilterItem()
    {
        $this->dispatch('syncItemsnoFilter');
    }

    #[On('tosyncItems')]
    public function toSyncItem()
    {
        $this->dispatch('syncItems');
    }

    #[On('syncItemsnoFilter')]
    public function sapGetItem()
    {
        $this->getItemwithUDF();
    }

    #[On('syncItems')]
    public function sapGetItemWithFilter()
    {
        if ($this->isPeriod) {
            $this->getItemwithUDFandFilter();
        } elseif ($this->isDocnum) {
            $this->getItemwithUDFWhereDocnum();
        }
    }

    #[On('finish')]
    public function afterSuccess()
    {
        return redirect()->route('it.itin');
    }
}
