<?php

namespace App\Livewire\Returnsale;

use App\Models\DetailInvoice;
use App\Models\ItemPrice;
use App\Models\Member;
use App\Models\Sales;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\On;
use Livewire\Component;
use Symfony\Component\Console\Input\Input;

class Table extends Component
{
    public $selectedCarts;
    public $member;
    public $sales;
    public $invoice;
    public $datas;
    public $selectedItems = [];
    public $selectedItemsPrice;
    public $selectedItemsDetails;
    public $itemReturnDetails;
    public $selectAll = false;
    public $bulkDisabled = true;
    public $showInputReturn = false;
    public $modalOpen = false;
    public $isData = false;
    public $data;
    public $openmodalDisc = false;
    public $isCheapestReturn = false;
    public $cartData;

    #[On('clearSelectedAfterReturn')]
    public function selectedItemsAfterReturn($data)
    {
        $this->selectedItems = $data;
        $this->showInputReturn = false;
        $this->selectedCarts = [];
    }
    #[On('selectedCartsReceived')]
    public function selectedCartsReceived($data, $datas)
    {
        $this->selectedCarts = $data;
        $this->selectedItems = $datas;
    }

    #[On('isData')]
    public function isData($data)
    {
        $this->data = $data;
        $this->isData = true;
    }


    #[On('afterSubmitItem')]
    public function removeItem($item, $overalPrice)
    {
        if (!empty($this->selectedCarts)) {
            $itemCodesAndPacks = array_map(function ($itm) {
                return ['code' => $itm['code'], 'pack' => $itm['pack']];
            }, $item);

            $this->selectedCarts = array_filter($this->selectedCarts, function ($cartItem) use ($itemCodesAndPacks) {
                foreach ($itemCodesAndPacks as $codePack) {
                    if ($cartItem['code'] === $codePack['code'] && $cartItem['pack'] === $codePack['pack']) {
                        return false;
                    }
                }
                return true;
            });

            $this->selectedCarts = array_values($this->selectedCarts);

            $this->dispatch('changeOveralPrice', $overalPrice, $item)->to(Newitem::class);

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


    public function render()
    {
        return view('livewire.returnsale.table');
    }

    public function showSelected($invoice)
    {

        $show = DetailInvoice::query()
            ->where('invoice', $invoice)
            ->whereNotIn('code', $this->selectedItems)
            ->get();

        $prices = $show->pluck('price', 'id')->toArray();

        $this->selectedItems = [];
    }

    public function updatedSelectAll($value)
    {
        if ($value) {
            $this->selectedItems = collect($this->selectedCarts)->pluck('id')->toArray();
            $this->showInputReturn = false;
        } else {
            $this->selectedItems = [];
            $this->showInputReturn = false;
        }
    }

    #[On('updateTotalPrice')]
    public function updatedSelectedItems($data)
    {
        if (!empty($this->selectedItems)) {

            $this->selectedItemsPrice = $data;
        } else {
            $this->selectedItemsPrice = 0;
            $this->showInputReturn = false;
        }
    }

    public function openModal()
    {
        // Decode the JSON strings to extract the 'code' and 'pack' values
        $selectedItemsArray = collect($this->selectedItems)->map(function ($item) {
            $decodedItem = json_decode($item, true);
            return [
                'code' => $decodedItem['code'],
                'pack' => $decodedItem['pack']
            ];
        })->all();

        $selectedItems = collect($this->selectedCarts)
            ->filter(function ($cartItem) use ($selectedItemsArray) {
                foreach ($selectedItemsArray as $item) {
                    if ($cartItem['code'] == $item['code'] && $cartItem['pack'] == $item['pack']) {
                        return true;
                    }
                }
                return false;
            })
            ->all();

        $selectedItemsPrice = collect($this->selectedCarts)
            ->whereIn('code', $this->selectedItems)
            ->pluck('price')
            ->sum();

        // foreach ($selectedItems as &$item) {

        //     $filteredProducts = DB::table('Luv2_item')
        //         ->join('Luv2_item_pricelist', 'Luv2_item.code', '=', 'Luv2_item_pricelist.item_code')
        //         ->where('Luv2_item_pricelist.id_pricelist', '1') // Replace 'your_price_list' with the desired price list
        //         ->where('Luv2_item_pricelist.price', '<=', $selectedItemsPrice)
        //         ->select('Luv2_item.*')
        //         ->get();

        //     $item['filteredProducts'] = $filteredProducts;
        //     foreach ($item['filteredProducts'] as &$filteredProduct) {
        //         $itemPrice = ItemPrice::where('item_code', $filteredProduct->code)->first();
        //         $filteredProduct->itemPrice = $itemPrice;
        //     }
        // }

        $this->dispatch('openModalWithSelectedData', $selectedItems, $selectedItemsPrice);
    }

    #[On('afterSelect')]
    public function openInput($data, $datas)
    {
        $selectedItemsDetails = collect($this->selectedCarts)
            ->whereIn('code', $this->selectedItems)
            ->all();
        $this->selectedItemsDetails = $selectedItemsDetails;
        $selectedItemsPrice = $data;
        //Get Member
        $selectedItemMembers = collect($this->selectedCarts)
            ->whereIn('code', $this->selectedItems)
            ->first();

        $this->itemReturnDetails = $datas;

        $itemReturnDetails = $this->itemReturnDetails;

        $this->member = Member::where('code', $selectedItemMembers['id_member'])->first();
        $this->sales = Sales::where('code', $selectedItemMembers['id_sales'])->first();
        $sales = $this->sales;
        $this->invoice = $selectedItemMembers['invoice'];
        $invoice = $this->invoice;
        if ($this->member === null) {
            $member = '';
        } else {
            $member = $this->member;
        }
        // foreach ($selectedItemsDetails as &$item) {

        //     $filteredProducts = DB::table('Luv2_item')
        //         ->join('Luv2_item_pricelist', 'Luv2_item.code', '=', 'Luv2_item_pricelist.item_code')
        //         ->where('Luv2_item_pricelist.id_pricelist', '1')
        //         ->where('Luv2_item_pricelist.price', '<=', $selectedItemsPrice)
        //         ->select('Luv2_item.*')
        //         ->get();

        //     $item['filteredProducts'] = $filteredProducts;
        //     foreach ($item['filteredProducts'] as &$filteredProduct) {
        //         $itemPrice = ItemPrice::where('item_code', $filteredProduct->code)->first();
        //         $filteredProduct->itemPrice = $itemPrice;
        //     }
        // }
        $this->showInputReturn = true;
        $this->dispatch('openInputWithSelectedData', $selectedItemsDetails, $selectedItemsPrice, $member, $sales, $invoice, $itemReturnDetails);
    }

    #[On('openthemodal')]
    public function F1Open()
    {
        $this->modalOpen = true;
        $this->dispatch('openModal');
    }

    public function modalDiscOpen()
    {
        $this->openmodalDisc = true;
    }

    #[On('closeModalDisctoTransaction')]
    public function closeModalSelect()
    {
        $this->openmodalDisc = false;
    }

    #[On('openModalSelect')]
    public function openModalSelect()
    {
        $this->openmodalDisc = true;
        $this->dispatch('openTheModal');
    }

    #[On('openModalCheapest')]
    public function toModalCheapest($data)
    {
        $this->cartData = $data;
        $this->isCheapestReturn = true;
        $this->dispatch('openModalCheapestReturn');
    }
}
