<?php

namespace App\Livewire\Pos\It\ItReqIn;

use App\Mail\ItRequestMail;
use App\Models\Settings;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Attributes\On;
use Livewire\Component;

class ItreqDetail extends Component
{
    use LivewireAlert;


    public $no;
    public $details;
    public $qty;
    public $quantities = [];
    public $updatedDetails = [];
    public $noit;
    public $isloading = false;


    public function mount($it)
    {
        $this->noit = $it;
        $this->details = DB::table('Luv2_it_req_detail')
            ->Join('Luv2_it_req', 'Luv2_it_req_detail.no', '=', 'Luv2_it_req.no')
            ->Join('Luv2_item', 'Luv2_it_req_detail.item_code', '=', 'Luv2_item.code')
            ->select('Luv2_item.code', 'Luv2_item.barcode', 'Luv2_item.name', DB::raw('SUM("Luv2_it_req_detail"."qty") as "qty"'), DB::raw('SUM("Luv2_it_req_detail"."qty_receive") as "qty_receive"'))
            ->where('Luv2_it_req.no', $it)
            ->groupBy('Luv2_item.code')
            ->get();
        foreach ($this->details as $detail) {
            $this->quantities[] = $detail->qty_receive;
        }
        $this->no = DB::table('Luv2_it_req')
            ->where('no', $it)->first();
    }

    #[On('toRedirect')]
    public function close()
    {
        return redirect()->route('it.itreq');
    }

    // public function updateQuantity($index, $code)
    // {
    //     $it = $this->no;
    //     $no = $it->no;

    //     $detail = DB::table('Luv2_it_req_detail')->where('no', $no)->where('item_code', $code)->first();
    //     if ($detail) {
    //         // Update qty_receive
    //         DB::table('Luv2_it_req_detail')
    //             ->where('no', $no)
    //             ->where('item_code', $code)
    //             ->update(['qty_receive' => $this->quantities[$index]]);
    //     }
    //     $details = DB::table('Luv2_it_req_detail')->where('no', $no)->get();
    //     $hasDifference = false;

    //     foreach ($details as $detail) {
    //         if ($detail->qty != $detail->qty_receive) {
    //             $hasDifference = true;
    //             break; // If there's a difference, no need to continue looping
    //         }
    //     }
    //     $msg = 'Qty receive ' . $detail->item_code . ' change from ' . $detail->qty . ' to ' . $this->quantities[$index];

    //     if ($hasDifference) {
    //         DB::table('Luv2_it_req')->where('no', $no)
    //             ->update(['status' => 'Difference']);
    //         $this->alert('info', 'Quantity receive has changed', [
    //             'position' => 'top-right',
    //             'timer' => 6000,
    //             'toast' => true,
    //             'text' => $msg,
    //             'width' => '400',
    //             'timerProgressBar' => true,
    //         ]);
    //     } else {
    //         DB::table('Luv2_it_req')->where('no', $no)
    //             ->update(['status' => 'Same']);
    //     }


    //     // dd($detail, $this->quantities[$index]);

    // }

    public function updateQuantity($index, $code)
    {
        $it = $this->no;
        $no = $it->no;

        $detail = DB::table('Luv2_it_req_detail')->where('no', $no)->where('item_code', $code)->first();
        if ($detail) {
            $detail->qty_receive = $this->quantities[$index];
        }

        $this->updatedDetails[$index] = $detail;

    }

    public function save()
    {
        $it = $this->no;
        $no = $it->no;
        DB::beginTransaction();

        try {
            // Update the database with the changes stored in $updatedDetails
            foreach ($this->updatedDetails as $index => $detail) {
                if ($detail) {
                    DB::table('Luv2_it_req_detail')
                        ->where('no', $no)
                        ->where('item_code', $detail->item_code)
                        ->update(['qty_receive' => $detail->qty_receive]);
                }
            }

            // Retrieve the details where qty is different from qty_receive
            $hasDifference = DB::table('Luv2_it_req_detail')
                ->where('no', $no)
                ->whereColumn('qty', '!=', 'qty_receive')
                ->exists();

            // Update the status based on whether there are differences
            $status = $hasDifference ? 'Difference' : 'Same';

            // Update the status in the Luv2_it_req table
            DB::table('Luv2_it_req')
                ->where('no', $no)
                ->update([
                    'status' => $status,
                    'sign' => 'Y'
                ]);

            // Commit the transaction
            DB::commit();


            if ($hasDifference) {
                // Display a success message
                $this->alert('success', 'Changes saved successfully, Wait for sending Email!', [
                    'position' => 'top-right',
                    'timer' => 6000,
                    'toast' => true,
                    'width' => '400',
                    'timerProgressBar' => true,
                ]);
                $this->dispatch('sendEmailItReq');
            } else {
                // Display a success message
                $this->alert('success', 'Changes saved successfully, Wait for Synchrone!', [
                    'position' => 'top-right',
                    'timer' => 6000,
                    'toast' => true,
                    'width' => '400',
                    'timerProgressBar' => true,
                ]);
                $this->dispatch('sendSAPItReq');
            }
        } catch (\Exception $e) {
            DB::rollBack();
            Log::debug($e);
            $this->alert('error', 'An error occurred. Changes could not be saved.', [
                'position' => 'top-right',
                'timer' => 6000,
                'toast' => true,
                'width' => '400',
                'timerProgressBar' => true,
            ]);
        }
    }

    #[On('clear')]
    public function afterSaveItem()
    {
        sleep(3);
        return redirect()->route('it.it_req_detail', $this->noit);
    }

    public function render()
    {
        return view('livewire.pos.it.itreqin.itreq-detail');
    }

    public function signITReq()
    {
        $it = $this->no;
        $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' => auth()->user()->id,
        ];

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

        foreach ($this->details as $key => $item) {
            DB::table('Luv2_it_in_detail')->insert([
                'no' => $it->no,
                'item_code' => $item->code,
                'qty' => $item->qty,
                'linenum' => $key + 1,
            ]);
        }

        DB::table('Luv2_it_req')->where('no', $it->no)
            ->update(['sign' => 'Y']);

        $this->alert('success', 'It Request Sign succesfully', [
            'position' => 'top-right',
            'timer' => 3000,
            'toast' => true,
            'width' => '400',
            'timerProgressBar' => true,
        ]);

        $this->dispatch('sleep');
    }

    #[On('sleep')]
    public function waiting()
    {
        sleep(2);
        $this->isloading = true;

        $this->dispatch('toRedirect');
    }

    #[On('sendEmailItReq')]
    public function sendEmail()
    {
        $this->isloading = true;
        $this->dispatch('toSendEmail');
    }

    #[On('sendSAPItReq')]
    public function toSAP()
    {
        $this->isloading = true;
        $this->dispatch('toSAP');
    }

    #[On('toSAP')]
    public function syncITReq()
    {

        $user = Auth::user();
        $setting = Settings::where('wh_code', $user->whs_code)->first();

        $detail = DB::table('Luv2_it_req_detail')->where('no', $this->noit)->get();
        $itreq = DB::table('Luv2_it_req')->where('no', $this->noit)->first();
        $lines = [];
        foreach ($detail as $item) {
            $lines[] = [
                'BaseEntry' => $itreq->entry,
                'BaseLine' => $item->linenum,
                'ItemCode' => $item->item_code,
                'Quantity' => $item->qty,
                'WhsCode' => $itreq->whs_code,
                'FromWhsCode' => $itreq->whs_code_from
            ];
        }
        $data = [
            'DocDate' => $itreq->date,
            'Filler' => $itreq->whs_code_from,
            'ToWhsCode' => $itreq->whs_code,
            'Comments' => $itreq->comments,
            'Lines' => $lines,
        ];

        try {
            $client = new Client();
            $response = $client->post($setting->url . '/api/addit', [
                'headers' => [
                    'Content-Type' => 'application/json',
                ],
                'json' => $data,
            ]);

            $responseBody = $response->getBody()->getContents();
            $responseData = json_decode($responseBody, true);
            $errorCode = $responseData['ErrorCode'];
            if ($errorCode !== 0) {
                Log::debug($responseData['Message']);
                $this->alert('warning', $responseData['Message'], [
                    'position' => 'top-end',
                    'timer' => 5000,
                    'toast' => true,
                    'timerProgressBar' => true,
                ]);
            } else {
                DB::table('Luv2_it_req')->where('no', $this->noit)->update(['sync' => 'Y']);
                Log::debug($responseData['Message']);
                $this->alert('success', $responseData['Message'], [
                    'position' => 'top-end',
                    'timer' => 5000,
                    'toast' => true,
                    'timerProgressBar' => true,
                ]);
            }
        } catch (\Exception $e) {
            Log::debug($responseData['Message']);
            $this->alert('error', 'No Internet Connection to Sync', [
                'position' => 'top-end',
                'timer' => 5000,
                'toast' => true,
                'timerProgressBar' => true,
            ]);
        }
        $this->dispatch('sleep');
    }

    #[On('toSendEmail')]
    public function sendEmailItReq()
    {
        $user = Auth::user();
        $toko = Settings::where('wh_code', $user->whs_code)->first();
        $email = $toko->email_sandbox;
        $itemSelisih = DB::table('Luv2_it_req_detail as detail')
            ->join('Luv2_it_req', 'detail.no', '=', 'Luv2_it_req.no')
            ->join('Luv2_item', 'detail.item_code', '=', 'Luv2_item.code')
            ->select(
                'Luv2_item.code',
                'Luv2_item.barcode',
                'Luv2_item.name',
                DB::raw('SUM(detail.qty) as qty'),
                DB::raw('SUM(detail.qty_receive) as qty_receive')
            )
            ->where('Luv2_it_req.no', $this->noit)
            ->groupBy('Luv2_item.code')
            ->havingRaw('SUM(detail.qty) <> SUM(detail.qty_receive)')
            ->get();
        $header = $this->no;
        Mail::to($email)->send(new ItRequestMail($itemSelisih, $header));
        $this->alert('success', 'Email sent!', [
            'position' => 'top-right',
            'timer' => 3000,
            'toast' => true,
            'width' => '400',
            'timerProgressBar' => true,
        ]);
        $this->dispatch('sleep');
    }
}
