<?php

namespace App\Livewire\Returnsale;

use Livewire\Component;
use App\Models\Auths;
use App\Models\Cart;
use App\Models\Item;
use App\Models\ItemPrice;
use App\Models\Settings;
use App\Models\Warehouse;
use Carbon\Carbon;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Attributes\On;


class CheapestItem extends Component
{
    use LivewireAlert;


    public $searchcheapest = '';
    public $selectedProduct;
    public $products = [];
    public $isEnter = false;
    public $selectedCode;
    public $selectedIndex;
    public $carts = [];
    public $cheapestCart;
    public $cartArray;
    public $updatedCartArray;
    public $updatedCheapestCart;
    public $removedItem;
    public $isLimit = false;
    public $selectedCheapest;
    public $cartData;

    public function render()
    {
        $results = [];

        if (strlen($this->searchcheapest) >= 1) {
            $results = DB::table('Luv2_item')->where(function ($query) {
                $query->where('code', 'ILIKE', '%' . $this->searchcheapest . '%')
                    ->orWhere('barcode', 'LIKE', '%' . $this->searchcheapest . '%')
                    ->orWhere('name', 'ILIKE', '%' . $this->searchcheapest . '%');
            })->limit(10)->get();
            $this->products = $results;
        }

        $no = '';

        if (!session()->has('Promo-GWP-CheapestItemNONAKTIF' . auth()->user()->id) && session()->has('Promo-GWP-CheapestItem' . auth()->user()->id)) {
            $no = session('Promo-GWP-CheapestItem' . auth()->user()->id);
        }
        if (session()->has('Promo-GWP-ValueCheapest' . auth()->user()->id)) {
            $no = session('Promo-GWP-ValueCheapest' . auth()->user()->id);
        }


        $cartArray = $this->cartData;

        // Get the minimum price from the cart items
        $minPrice = collect($cartArray)->min('itemprice');

        // Filter to get all items with the minimum price
        $cheapestCart = collect($cartArray)->filter(function ($cart) use ($minPrice) {
            return $cart['itemprice'] == $minPrice;
        })->values();

        $this->cheapestCart = $cheapestCart;
        $this->cartArray = $cartArray;

        return view('livewire.returnsale.cheapest-item');
    }


    public function check()
    {
        dd($this->updatedCheapestCart, $this->updatedCartArray);
    }

    public function updatedSearchcheapest()
    {
        $this->selectedProduct = null;
    }

    public function selectProductByName()
    {
        $product = Item::where('barcode', $this->searchcheapest)
            ->where('sales', 'Y')
            ->where('active', 'Y')
            ->first();

        if ($product) {
            if ($this->isLimit) {
                $this->reachLimit();
            } else {
                $selectedItem = null; // Initialize variable to store the selected item

                if ($this->carts) {
                    // Check if product code is in the list of selected cheapest items and capture the matching item
                    $selectedItem = collect($this->updatedCheapestCart)->first(function ($item) use ($product) {
                        return $product->code === ($item['code'] ?? $item['itemcode']);
                    });
                    $this->selectedCheapest = $selectedItem;
                } else {
                    // If not using updatedCartArray, check against cheapestCart
                    $selectedItem = collect($this->cheapestCart)->first(function ($item) use ($product) {
                        return $product->code === ($item['code'] ?? $item['itemcode']);
                    });

                    $this->selectedCheapest = $selectedItem;
                }
                if ($selectedItem) {
                    $this->toProduct($product);
                } else {
                    $this->notTheCheapest();
                }
            }
        } else {
            $this->noProduct();
        }
    }

    #[On('toIsEnter')]
    public function trueIsEnter()
    {
        $this->isEnter = true;
        $this->dispatch('toSave');
    }

    // public function selectProductByClick($itemCode)
    // {
    //     $product = DB::table('Luv2_item')->where('code', $itemCode)
    //         ->where('sales', 'Y')
    //         ->where('active', 'Y')
    //         ->first();
    //     if ($product) {
    //         if ($this->isLimit) {
    //             $this->reachLimit();
    //         } else {
    //             if ($this->carts) {
    //                 $isCheapest = $product->code === ($this->updatedCheapestCart['code'] ?? $this->updatedCheapestCart['itemcode']);
    //             } else {
    //                 $isCheapest = $product->code === $this->cheapestCart['code'];
    //             }
    //             if ($isCheapest) {
    //                 $this->toProduct($product);
    //             } else {
    //                 $this->notTheCheapest();
    //             }
    //         }
    //     } else {
    //         $this->noProduct();
    //     }
    // }

    public function selectProductByClick($itemCode)
    {
        $product = DB::table('Luv2_item')->where('code', $itemCode)
            ->where('sales', 'Y')
            ->where('active', 'Y')
            ->first();

        if ($product) {
            if ($this->isLimit) {
                $this->reachLimit();
            } else {
                $selectedItem = null; // Initialize variable to store the selected item

                if ($this->carts) {
                    // Check if product code is in the list of selected cheapest items and capture the matching item
                    $selectedItem = collect($this->updatedCheapestCart)->first(function ($item) use ($product) {
                        return $product->code === ($item['code'] ?? $item['itemcode']);
                    });
                    $this->selectedCheapest = $selectedItem;
                } else {
                    // If not using updatedCartArray, check against cheapestCart
                    $selectedItem = collect($this->cheapestCart)->first(function ($item) use ($product) {
                        return $product->code === ($item['code'] ?? $item['itemcode']);
                    });

                    $this->selectedCheapest = $selectedItem;
                }
                if ($selectedItem) {
                    $this->toProduct($product);
                } else {
                    $this->notTheCheapest();
                }
            }
        } else {
            $this->noProduct();
        }
    }


    public function selectProduct($index)
    {
        $this->selectedIndex = $index;
        $this->selectedCode = $this->products[$index]->code;

        $product = DB::table('Luv2_item')
            ->where('code', $this->selectedCode)
            ->where('sales', 'Y')
            ->where('active', 'Y')
            ->first();

        if ($product) {
            if ($this->isLimit) {
                $this->reachLimit();
            } else {
                if ($this->carts) {
                    $isCheapest = $product->code === ($this->updatedCheapestCart['code'] ?? $this->updatedCheapestCart['itemcode']);
                } else {
                    $isCheapest = $product->code === $this->cheapestCart['code'];
                }
                if ($isCheapest) {
                    $this->selectedProduct = $product;
                    $this->toProduct($product);
                } else {
                    $this->notTheCheapest();
                }
            }
        } else {
            $this->noProduct();
        }

        $this->selectedCode = null;
        $this->selectedIndex = null;
        $this->isEnter = true;
        // $this->dispatch('toSave');
    }

    public function notTheCheapest()
    {
        $this->alert('warning', 'Item is not the cheapest on the Cart !', [
            'position' => 'top-center',
            'timer' => 3000,
            'toast' => true,
            'text' => 'Please enter the cheapest item on cart !',
            'width' => '800',
            'timerProgressBar' => true,
        ]);
        $this->products = [];
        $this->searchcheapest = '';
    }

    public function reachLimit()
    {
        $this->alert('warning', 'You have reached the limit for this promo.', [
            'position' => 'top-center',
            'timer' => 3000,
            'toast' => true,
            'width' => '800',
            'timerProgressBar' => true,
        ]);
        $this->products = [];
        $this->searchcheapest = '';
    }

    public function noProduct()
    {
        $productcheck = Item::where('barcode', $this->searchcheapest)
            ->first();
        if ($productcheck) {
            if ($productcheck->active == 'N') {
                $this->alert('warning', 'Item Is Not Active', [
                    'position' => 'top-center',
                    'timer' => 3000,
                    'toast' => true,
                    'text' => 'Please enter active item !',
                    'width' => '800',
                    'timerProgressBar' => true,
                ]);
            } else {
                $this->alert('warning', 'Item Is Non Sales', [
                    'position' => 'top-center',
                    'timer' => 3000,
                    'toast' => true,
                    'text' => 'Please enter sales item !',
                    'width' => '800',
                    'timerProgressBar' => true,
                ]);
            }
        } else {
            $this->alert('warning', 'Item Not Found', [
                'position' => 'top-center',
                'timer' => 3000,
                'toast' => true,
                'text' => 'Please enter valid item barcode !',
                'width' => '800',
                'timerProgressBar' => true,
            ]);
        }
    }

    // public function toProduct($product)
    // {
    //     $user = Auth::user();
    //     $setting = Settings::first();
    //     $whs = Warehouse::where('code', $setting->wh_code)->first();
    //     $pricelist = $whs->id_pricelist;

    //     // if (session('discountmemb') == 1) { //dinonaktifkandulu
    //     //     // Apply discount for member
    //     //     $pricelist = $setting->member_pricelist;
    //     // }
    //     $this->selectedProduct = $product;
    //     $itemCode = $product->code;
    //     $prices = ItemPrice::where('item_code', $itemCode)->where('id_pricelist', $pricelist)->first();

    //     $this->form->itemname = $product->name . ' ( FREE ITEM )';
    //     $this->form->itemcode = $product->code;
    //     $this->form->itemqty = 1;
    //     $this->form->itemprice = 0;
    //     $this->form->nprice = $prices->price;
    //     $this->form->promo = 0;
    //     $this->form->promotipe = 0;
    //     $this->form->pack = 0;
    //     $this->form->discount = $prices->price;
    //     $this->form->benefit = 'Cheapest';

    //     $this->searchcheapest = $product->code; // Update the searchcheapest field with the selected product's code
    //     $this->dispatch('updateTotalAmount')->to(Invoice::class);
    // }

    public function toProduct($product)
    {
        $user = Auth::user();
        $setting = Settings::first();
        $whs = Warehouse::where('code', $setting->wh_code)->first();
        $pricelist = $whs->id_pricelist;

        $this->selectedProduct = $product;
        $itemCode = $product->code;
        $currentDate = Carbon::now()->toDateString();

        $prices = ItemPrice::where('item_code', $itemCode)->where('id_pricelist', $pricelist)->first();
        $existingCartIndex = null;
        foreach ($this->carts as $index => $cart) {
            if ($cart['itemcode'] == $itemCode) {
                $existingCartIndex = $index;
                break;
            }
        }

        // if ($existingCartIndex !== null) {
        //     $this->updateItemQty($existingCartIndex, $this->carts[$existingCartIndex]['itemqty'] + 1);
        // } else {
        // Find the cheapest item in the cart
        if ($this->carts) {
            $cheapestCart = $this->selectedCheapest['id'];
        } else {
            $cheapestCart = $this->selectedCheapest['id'];
        }

        // Add item to cart
        $item = [
            'id' => $this->selectedCheapest['id'],
            'itemname' => $product->name . ' ( FREE ITEM )',
            'itemcode' => $product->code,
            'itemqty' => 1,
            'oldqty' => 1,
            'itemprice' => $prices->price,
            'nprice' => $prices->price,
            'promo' => 0,
            'promotipe' => 0,
            'pack' => 0,
            'discount' => $prices->price,
            'benefit' => 'Cheapest'
        ];

        if ($this->carts) {
            // Remove the cheapest item from the cartArray
            $this->updatedCartArray = array_filter($this->updatedCartArray, function ($cart) use ($cheapestCart) {
                if ($cart['id'] === $cheapestCart) {
                    $this->removedItem = $cart; // Save the removed item to $this->removedItem
                    return false; // Remove this item from the array
                }
                return true;
            });
        } else {
            // Remove the cheapest item from the cartArray
            $this->updatedCartArray = array_filter($this->cartArray, function ($cart) use ($cheapestCart) {
                if ($cart['id'] === $cheapestCart) {
                    $this->removedItem = $cart; // Save the removed item to $this->removedItem
                    return false; // Remove this item from the array
                }
                return true;
            });
        }

        $this->updatedCartArray = array_values($this->updatedCartArray); // Re-index
        $minPrice = collect($this->updatedCartArray)->min('itemprice');
        $this->updatedCheapestCart = collect($this->updatedCartArray)->filter(function ($cart) use ($minPrice) {
            return $cart['itemprice'] == $minPrice;
        })->values()->all();


        $this->carts[] = $item;

        $this->searchcheapest = '';

        $this->checkLimit();
        // }
    }

    public function checkLimit()
    {
        if (!session()->has('Promo-GWP-CheapestItemNONAKTIF' . auth()->user()->id) && session()->has('Promo-GWP-CheapestItem' . auth()->user()->id)) {
            $no = session('Promo-GWP-CheapestItem' . auth()->user()->id);
        }
        if (session()->has('Promo-GWP-ValueCheapest' . auth()->user()->id)) {
            $no = session('Promo-GWP-ValueCheapest' . auth()->user()->id);
        }

        if ($no) {
            $promo = DB::table('Luv2_promo')->where('no', $no)->first();

            $cheapestQty = $promo->cheapest_qty ?? 1;
            $cheapestQty = $cheapestQty === '' ? 1 : $cheapestQty;

            if ($promo && count($this->carts) == $cheapestQty) {
                $this->isLimit = true;
            } else {
                $this->isLimit = false;
            }
        }
    }

    public function updateItemQty($index, $newQty)
    {
        $cart = $this->carts[$index] ?? null;
        if ($cart) {
            $originalQty = $cart['oldqty'];
            if ($newQty != $originalQty) {
                $this->carts[$index]['itemqty'] = $newQty;
                $this->carts[$index]['oldqty'] = $newQty;
            }
        }
    }

    public function deleteFromCarts($index)
    {
        if (isset($this->carts[$index])) {
            // Retrieve the cart item to be restored
            $cart = $this->carts[$index];

            // Prepare the restored item
            $restoredItem = [
                'id' => $cart['id'],
                'itemname' => $cart['itemname'],
                'itemcode' => $cart['itemcode'],
                'itemqty' => $cart['itemqty'],
                'itemprice' => $cart['itemprice'],
                'nprice' => $cart['nprice'],
                'promo' => $cart['promo'],
                'promotipe' => $cart['promotipe'],
                'pack' => $cart['pack'],
                'discount' => $cart['discount'],
                'benefit' => $cart['benefit']
            ];

            // Add the item to the cartArray and updatedCartArray
            $this->cartArray[] = $restoredItem;
            $this->updatedCartArray[] = $restoredItem;

            // Remove the item from the carts array
            unset($this->carts[$index]);
            $this->carts = array_values($this->carts); // Re-index

            // Ensure that all items in updatedCartArray contain the 'price' key
            $updatedCartArrayWithPrices = array_filter($this->updatedCartArray, function ($item) {
                return isset($item['itemprice']);
            });

            if (count($updatedCartArrayWithPrices) > 0) {
                // Recalculate the cheapest items in the updatedCartArray
                $minPrice = collect($updatedCartArrayWithPrices)->min('itemprice');

                // Get all items with the minimum price
                $this->updatedCheapestCart = collect($updatedCartArrayWithPrices)->filter(function ($item) use ($minPrice) {
                    return isset($item['itemprice']) && $item['itemprice'] == $minPrice;
                })->values()->all(); // Return an array of all cheapest items
            } else {
                // Handle the case where no items have a price
                $this->updatedCheapestCart = [];
            }

            // Set the removed item to $this->removedItem
            $this->removedItem = $cart;

            // Check the limit (if applicable)
            $this->checkLimit();
        }
    }


    public function save()
    {
        $user = Auth::user();
        $authorization = Auths::where('menu', 'Transaction')
            ->where('modul', 'Sales')->first();

        if ($this->isLimit) {
            $hasPermission = $user->authorizations
                ->filter(function ($authorization) {
                    return strpos($authorization->auth, 'C') !== false;
                })
                ->contains('id_auth', $authorization->id);

            if ($hasPermission) {
                // Update the itemprice for each item in $this->carts
                foreach ($this->carts as &$cartItem) { // Use a reference to modify the original array
                    $cartItem['itemprice'] = 0;
                }

                // Dispatch the updated carts to the Newitem component
                $this->dispatch('updateTheCarts', $this->carts)->to(Newitem::class);

                // Reset search and selected product
                $this->reset(['searchcheapest', 'selectedProduct']);
            }

            if ($this->isEnter) {
                $this->dispatch('closeModalCheapest');
            }

            $this->isEnter = false;
            session(['Promo-GWP-CheapestItemNONAKTIF' . auth()->user()->id => true]);

            if (session()->has('Promo-GWP-ValueCheapest' . auth()->user()->id)) {
                $session = session('Promo-GWP-ValueCheapest' . auth()->user()->id);
                session(['Promo-GWP-ValueCheapestFulfil' . auth()->user()->id => $session]);
            }

            $this->products = [];
            $this->isLimit = false;
            $this->carts = [];
        } else {
            $this->alert('warning', 'Belum memenuhi', [
                'position' => 'top-center',
                'timer' => 3000,
                'toast' => true,
                'text' => '-',
                'width' => '800',
                'timerProgressBar' => true,
            ]);
        }
    }
}
