<?php

namespace App\Livewire\Pos\It\ItOut;

use App\Models\ItemTemp;
use App\Models\ItOutTemp;
use App\Models\ItReqOut;
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 Illuminate\Support\Facades\Http;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Attributes\On;
use Livewire\Component;

class Syncout 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.itout.syncout');
    }

    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('filterItOut');
        } elseif (!$this->isPeriod && $this->isDocnum && !$this->isCheckedAll) {
            $this->dispatch('filterItOut');
        } elseif ($this->isCheckedAll && !$this->isDocnum && !$this->isPeriod) {
            $this->dispatch('notFilterItOut');
        } else {
        }
    }

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

    #[On('notFilterItOut')]
    public function sapGetItOut()
    {
        $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.\"FromWhsCod\" as \"whs_code\",b.\"WhsCode\" as \"whs_code_to\", 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.\"FromWhsCod\"='" . $whscode . "' group by b.\"FromWhsCod\", b.\"WhsCode\", a.\"DocDate\", a.\"Comments\", a.\"DocNum\", a.\"CANCELED\""
        ]);

        $responseDet = Http::post($url . '/api/search', [
            "Select" => "a.\"Filler\" 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" => "a.\"Filler\"='" . $whscode . "'",
        ]);

        if ($response->successful() && $responseDet->successful()) {
            $jsonData = $response->json();
            $jsonDataDet = $responseDet->json();
            if (!empty($jsonData)) {
                ItOutTemp::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_to' => $it['whs_code_to'],
                            'date' => $it['date'],
                            'comments' => $it['comments'],
                            'no' => $it['no'],
                            'canceled' => $it['canceled'],
                            'id_user' => $it['id_user'],
                        ];
                    }
                    DB::table('Luv2_it_out_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_out_temp_detail')->insert($insertDataDet);
                }
                #insert it
                DB::statement("
                    INSERT INTO \"Luv2_it_out\" (\"whs_code\", \"whs_code_to\", \"date\", \"comments\", \"no\", \"canceled\", \"id_user\") 
                    SELECT \"whs_code\", \"whs_code_to\", \"date\", \"comments\", \"no\", \"canceled\", '" . $userId . "'
                    FROM \"Luv2_it_out_temp\"
                    WHERE NOT EXISTS (
                        SELECT 1 FROM \"Luv2_it_out\" WHERE \"Luv2_it_out\".\"no\" = \"Luv2_it_out_temp\".\"no\"
                    ) and \"Luv2_it_out_temp\".\"id_user\"='" . $userId . "' 
                ");

                #update it
                DB::statement("
                    UPDATE \"Luv2_it_out\"
                    SET \"canceled\"=\"Luv2_it_out_temp\".\"canceled\"
                    FROM \"Luv2_it_out_temp\"
                    WHERE \"Luv2_it_out_temp\".\"no\"=\"Luv2_it_out\".\"no\"
                    AND \"Luv2_it_out_temp\".\"canceled\"<>\"Luv2_it_out\".\"canceled\";
                ");

                #insert it det
                DB::statement("
                    INSERT INTO \"Luv2_it_out_detail\" (\"no\", \"item_code\", \"qty\", \"linenum\") 
                    SELECT \"no\", \"item_code\", \"qty\", \"linenum\"
                    FROM \"Luv2_it_out_temp_detail\"
                    WHERE NOT EXISTS (
                        SELECT 1 FROM \"Luv2_it_out_detail\" WHERE \"Luv2_it_out_detail\".\"no\" = \"Luv2_it_out_temp_detail\".\"no\" and \"Luv2_it_out_detail\".\"linenum\" = \"Luv2_it_out_temp_detail\".\"linenum\"
                    ) and \"Luv2_it_out_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\"*-1, \"date\", \"canceled\", \"item_code\", \"linenum\"
                    FROM \"Luv2_it_out_temp_detail\"
                    WHERE NOT EXISTS (
                        SELECT 1 FROM \"Luv2_item_trans\" WHERE \"Luv2_item_trans\".\"no_trans\" = \"Luv2_it_out_temp_detail\".\"no\" and \"Luv2_item_trans\".\"linenum\" = \"Luv2_it_out_temp_detail\".\"linenum\" and \"Luv2_item_trans\".\"tipe\"='67'
                    ) and \"Luv2_it_out_temp_detail\".\"id_user\"='" . $userId . "' 
                ");
                $this->alert('success', 'Data synchrone succesfully', [
                    'position' => 'top-right',
                    'timer' => 3000,
                    'toast' => true,
                    'timerProgressBar' => true,
                ]);
                ItOutTemp::where('id_user', $userId)->delete();
                $this->dispatch('disableButton');
                $this->dispatch('tosyncItemsnofilter');
                $this->dispatch('updateITReq', $insertData);
            } else {
                $this->isloading = false;
                $this->alert('info', 'Theres no data to synchrone', [
                    'position' => 'top-right',
                    'timer' => 3000,
                    'toast' => true,
                    'timerProgressBar' => true,
                ]);
            }
        }
    }

    #[On('filterItOut')]
    public function sapGetItOutisFilter()
    {
        $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.\"FromWhsCod\" as \"whs_code\",b.\"WhsCode\" as \"whs_code_to\", 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.\"FromWhsCod\"='" . $whscode . "' and a.\"DocDate\" BETWEEN '" . $this->startDate . "' and '" . $this->endDate . "' group by b.\"WhsCode\", b.\"FromWhsCod\", a.\"DocDate\", a.\"Comments\", a.\"DocNum\", a.\"CANCELED\"",
            ]);

            $responseDet = Http::post($url . '/api/search', [
                "Select" => "b.\"FromWhsCod\" 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.\"FromWhsCod\"='" . $whscode . "' and a.\"DocDate\" BETWEEN '" . $this->startDate . "' and '" . $this->endDate . "'",
            ]);
        } elseif ($this->isDocnum) {
            $response = Http::post($url . '/api/search', [
                "Select" => "b.\"FromWhsCod\" as \"whs_code\",b.\"WhsCode\" as \"whs_code_to\", 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.\"FromWhsCod\"='" . $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.\"FromWhsCod\" 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.\"FromWhsCod\"='" . $whscode . "' and a.\"DocNum\" = '" . $this->docNum . "'",
            ]);
        }

        if ($response->successful() && $responseDet->successful()) {
            $jsonData = $response->json();
            $jsonDataDet = $responseDet->json();
            if ($jsonData[0]['whs_code'] !== '') {
                ItOutTemp::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_to' => $it['whs_code_to'],
                            'date' => $it['date'],
                            'comments' => $it['comments'],
                            'no' => $it['no'],
                            'canceled' => $it['canceled'],
                            'id_user' => $it['id_user'],
                        ];
                    }
                    DB::table('Luv2_it_out_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_out_temp_detail')->insert($insertDataDet);
                }
                #insert it
                DB::statement("
                    INSERT INTO \"Luv2_it_out\" (\"whs_code\", \"whs_code_to\", \"date\", \"comments\", \"no\", \"canceled\", \"id_user\") 
                    SELECT \"whs_code\", \"whs_code_to\", \"date\", \"comments\", \"no\", \"canceled\", '" . $userId . "'
                    FROM \"Luv2_it_out_temp\"
                    WHERE NOT EXISTS (
                        SELECT 1 FROM \"Luv2_it_out\" WHERE \"Luv2_it_out\".\"no\" = \"Luv2_it_out_temp\".\"no\"
                    ) and \"Luv2_it_out_temp\".\"id_user\"='" . $userId . "' 
                ");

                #update it
                DB::statement("
                    UPDATE \"Luv2_it_out\"
                    SET \"canceled\"=\"Luv2_it_out_temp\".\"canceled\"
                    FROM \"Luv2_it_out_temp\"
                    WHERE \"Luv2_it_out_temp\".\"no\"=\"Luv2_it_out\".\"no\"
                    AND \"Luv2_it_out_temp\".\"canceled\"<>\"Luv2_it_out\".\"canceled\";
                ");

                #insert it det
                DB::statement("
                    INSERT INTO \"Luv2_it_out_detail\" (\"no\", \"item_code\", \"qty\", \"linenum\") 
                    SELECT \"no\", \"item_code\", \"qty\", \"linenum\"
                    FROM \"Luv2_it_out_temp_detail\"
                    WHERE NOT EXISTS (
                        SELECT 1 FROM \"Luv2_it_out_detail\" WHERE \"Luv2_it_out_detail\".\"no\" = \"Luv2_it_out_temp_detail\".\"no\" and \"Luv2_it_out_detail\".\"linenum\" = \"Luv2_it_out_temp_detail\".\"linenum\"
                    ) and \"Luv2_it_out_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\"*-1, \"date\", \"canceled\", \"item_code\", \"linenum\"
                    FROM \"Luv2_it_out_temp_detail\"
                    WHERE NOT EXISTS (
                        SELECT 1 FROM \"Luv2_item_trans\" WHERE \"Luv2_item_trans\".\"no_trans\" = \"Luv2_it_out_temp_detail\".\"no\" and \"Luv2_item_trans\".\"linenum\" = \"Luv2_it_out_temp_detail\".\"linenum\" and \"Luv2_item_trans\".\"tipe\"='67'
                    ) and \"Luv2_it_out_temp_detail\".\"id_user\"='" . $userId . "' 
                ");
                $this->alert('success', 'Data synchrone succesfully', [
                    'position' => 'top-right',
                    'timer' => 3000,
                    'toast' => true,
                    'timerProgressBar' => true,
                ]);
                ItOutTemp::where('id_user', $userId)->delete();
                $this->dispatch('disableButton');
                $this->dispatch('tosyncItems');
                $this->dispatch('updateITReq', $insertData);
            } 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('updateITReq')]
    public function toupdateITReq($data)
    {
        foreach ($data as $item) {
            $comment = $item['comments'];
            $parts = explode('/', $comment);

            if (count($parts) > 1) {
                $code = $parts[1];

                $itReqOut = ITReqOut::where('no', $code)->first();

                if ($itReqOut) {
                    $itReqOut->entry = $item['no'];

                    $itReqOut->save();
                } else {
                    // Handle case where no ITReqOut is found
                    // Optionally, log or display an error message
                }
            } else {
                // Handle cases where the comment doesn't have the expected format
                // Optionally, log or display an error message
            }
        }
    }


    #[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()
    {
        sleep(1);
        return redirect()->route('it.itout');
    }
}
