<?php

namespace App\Livewire\Cashier;

use App\Models\Auths;
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 Illuminate\Support\Str;
use Livewire\Attributes\On;
use Livewire\Component;
use App\Livewire\Forms\CartForm;
use App\Models\Cart;

class ProcessDiscount extends Component
{
    public $no = '';
    public $name = '';
    public $carts = [];
    public $products = [];
    public $searchitem = '';
    public $selectedProduct;
    public $isEnter = false;
    public $selectedCode;
    public $selectedIndex;
    public $overalPrice = 0;
    public $defaultOveralPrice = 0;
    public $itembrand;
    public $increment = 1;
    public $item;
    public $recorditem;
    public $discountMoreThanOne = false;
    public $isSuggestion = false;
    public $suggestion = [];
    public $suggestionName;
    public $fulfilled = false;
    public $refreshKey = 0;
    public $promoExclude = false;


    public CartForm $form;


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

        $setting = Settings::first();
        $whs = Warehouse::where('code', $setting->wh_code)->first();
        $pricelist = $whs->id_pricelist;
        $no = $this->no['no'] ?? '';

        if (strlen($this->searchitem) >= 1) {
            // Extract pack values from the $this->carts array
            $existingPacks = array_column($this->carts, 'pack');

            $results = DB::table('Luv2_item')
                ->leftJoin('Luv2_item_pricelist', function ($join) use ($pricelist) {
                    $join->on('Luv2_item.code', '=', 'Luv2_item_pricelist.item_code')
                        ->where('Luv2_item_pricelist.id_pricelist', '=', $pricelist);
                })
                ->select('Luv2_item.*', 'Luv2_item_pricelist.price')
                ->where(function ($query) {
                    $query->where('Luv2_item.code', 'ILIKE', '%' . $this->searchitem . '%')
                        ->orWhere('Luv2_item.barcode', 'LIKE', '%' . $this->searchitem . '%')
                        ->orWhere('Luv2_item.name', 'ILIKE', '%' . $this->searchitem . '%');
                })
                ->whereExists(function ($query) use ($no, $existingPacks) {
                    $query->select(DB::raw(1))
                        ->from('Luv2_promo_item')
                        ->whereColumn('Luv2_promo_item.item_code', 'Luv2_item.code')
                        ->where('Luv2_promo_item.no', '=', $no)
                        ->whereNotIn('Luv2_promo_item.pack', $existingPacks);
                })
                ->limit(10)
                ->get();

            $this->products = $results;
        }

        return view('livewire.cashier.process-discount');
    }


    #[On('toModalProcessDiscount')]
    public function openTheModalDiscount($no, $carts)
    {

        $this->no = $no;
        $this->name = $no['name'];
        // Check if itemname in carts is empty
        if (empty($carts['itemname'])) {
            // dd('asd');
            // Fetch the latest cart item from the database
            $carts = Cart::where('promo', $no['no'])
                ->where('code', $this->no['item_code'])
                ->where('id_user', auth()->user()->id)
                ->orderBy('created_at', 'desc')
                ->first();

            if ($carts) {
                $carts = (object) [
                    'itemname' => $carts->name,
                    'itemprice' => $carts->price,
                    'itemcode' => $this->no['item_code'],
                    'itemqty' => $carts->qty,
                    'discount' => $carts->discount,
                    'promo' => $carts->promo,
                    'promotipe' => $carts->promo_tipe,
                    'pack' => $carts->pack,
                    'nprice' => $carts->nprice,
                ];
            }
        }

        $this->carts = [
            [
                "id" => 1,
                "itemname" => $carts->itemname ?? $carts['itemname'], 
                "itemprice" => $carts->itemprice ?? $carts['itemprice'], 
                "itemcode" => $carts->itemcode ?? $this->no['item_code'], 
                "itemqty" => 1, 
                "discount" => $carts->discount ?? $carts['discount'], 
                "promo" => $carts->promo ?? $carts['promo'], 
                "promotipe" => $carts->promotipe ?? $carts['promotipe'], 
                "pack" => $carts->pack ?? $carts['pack'], 
                "benefit" => $no['benefit'],
                "nprice" => $carts->nprice ?? $carts['nprice'], 
            ]
        ];

        $this->dispatch('openModalProcessDiscount')->to(Transaction::class);
    }

    public function updatedSearchitem()
    {
        $this->selectedProduct = null;
        $this->products = [];
        $this->refreshKey++;
    }

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

        if ($product) {
            $this->toProductDiscount($product);
            // $this->dispatch('toIsEnter');
        } else {
            $this->noProduct();
        }
    }

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

    public function byClick($itemCode)
    {

        $product = DB::table('Luv2_item')->where('code', $itemCode)
            ->where('sales', 'Y')
            ->where('active', 'Y')
            ->first();
        if ($product) {
            $this->toProductDiscount($product);
        } 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) {
            $this->selectedProduct = $product;
            $this->toProductDiscount($product);
        }

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

    public function noProduct()
    {
        $productcheck = Item::where('barcode', $this->searchitem)
            ->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 toProductDiscount($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();
        $dataDisc = DB::table('Luv2_promo')
            ->where('deleted', 'N')
            ->where('Luv2_promo.no', $this->no)
            ->join('Luv2_promo_item', 'Luv2_promo.no', '=', 'Luv2_promo_item.no')
            ->whereDate('from_date', '<=', $currentDate)
            ->whereDate('to_date', '>=', $currentDate)
            ->where('item_code', $itemCode)
            ->select(
                'Luv2_promo.no',
                'Luv2_promo.name',
                'Luv2_promo.from_date',
                'Luv2_promo.to_date',
                'Luv2_promo.voucher_from_date',
                'Luv2_promo.voucher_to_date',
                'Luv2_promo.tipe',
                'Luv2_promo.benefit',
                'Luv2_promo.disc',
                'Luv2_promo.disc_price',
                'Luv2_promo_item.id_company',
                'Luv2_promo_item.item_code',
                'Luv2_promo_item.pack',
                'Luv2_promo_item.disc',
                'Luv2_promo_item.disc_price',
            )
            ->groupBy('Luv2_promo.no', 'Luv2_promo.name', 'Luv2_promo.from_date', 'Luv2_promo.to_date', 'Luv2_promo.voucher_from_date', 'Luv2_promo.voucher_to_date', 'Luv2_promo.tipe', 'Luv2_promo.benefit', 'Luv2_promo.benefit', 'Luv2_promo.disc', 'Luv2_promo.disc_price', 'Luv2_promo_item.id_company', 'Luv2_promo_item.item_code', 'Luv2_promo_item.pack', 'Luv2_promo_item.disc', 'Luv2_promo_item.disc_price', )
            ->get();
        $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 {
        $item = $this->itemResourceDiscount($product, $prices, $dataDisc, $pricelist);

        $this->addToCartsDiscount($item);

        // }

        if (session()->has('Promo-GWP-ValueFreeItem' . auth()->user()->id) || session()->has('Promo-GWP-ValueCheapest' . auth()->user()->id) || session()->has('Promo-Voucher-Value' . auth()->user()->id)) {
            $this->dispatch('checkCartValue');
        } else {
            // $this->dispatch('toActiveNcheckGWPValue');
        }

        $this->searchitem = '';
    }

    public function addToCartsDiscount($item)
    {
        $existingCart = array_filter($this->carts, function ($cartItem) use ($item) {
            return $cartItem['itemcode'] == $item['itemcode'] && $cartItem['promotipe'] == $item['promotipe'];
        });

        $existingCart = reset($existingCart);
        if (!empty($existingCart)) {
            if ($existingCart['promotipe'] == 3) {
                $checkcart = array_filter($this->carts, function ($cartItem) use ($item) {
                    return $cartItem['itemcode'] == $item['itemcode'] &&
                        $cartItem['promo'] == $item['promo'] &&
                        $cartItem['promotipe'] == 3;
                });

                $checkcart = reset($checkcart);

                if ($checkcart) {
                    $firstAvailablePack = $this->checkAvailablePacks($item['itemcode'], $item['promo'], $item['promotipe']);
                    if ($firstAvailablePack) {

                        $item['pack'] = $firstAvailablePack;
                    }
                }
            } elseif ($existingCart['promotipe'] == 4) {
                $checkcart = array_filter($this->carts, function ($cartItem) use ($item) {
                    return $cartItem['itemcode'] == $item['itemcode'] &&
                        $cartItem['promo'] == $item['promo'] &&
                        $cartItem['promotipe'] == 4;
                });

                $checkcart = reset($checkcart);
                if ($checkcart) {
                    $firstAvailablePack = $this->checkAvailablePacks($item['itemcode'], $item['promo'], $item['promotipe']);
                    if ($firstAvailablePack) {
                        $item['pack'] = $firstAvailablePack;
                    }
                }
            }
        } else {
            $firstAvailablePack = $this->checkAvailablePacks($item['itemcode'], $item['promo'], $item['promotipe']);
            if ($firstAvailablePack) {
                $item['pack'] = $firstAvailablePack;
            }
        }
        if ($this->discountMoreThanOne) {
        } else {
            $this->carts[] = $item;
        }
        if ($item['promo'] != 0) {
            $this->updatePriceBundle($item['promo']);
        } else {
        }
    }

    public function updatePriceBundle($nopromo)
    {
        // Get promo details
        $promo = DB::table('Luv2_promo')->where('no', $nopromo)->first();

        if (!$promo) {
            return; // If promo doesn't exist, exit the function
        }

        // Filter cart items based on promo
        $cart = array_filter($this->carts, function ($cartItem) use ($nopromo) {
            return $cartItem['promo'] == $nopromo;
        });

        $cart = array_values($cart); // Re-index array
        $fulfilled = true;

        // Check if promo is an unlimited bundle
        if ($promo->tipe == 7 && $promo->benefit == 1) {
            $checkbundle = DB::table('Luv2_promo_bundling_qty')
                ->where('no', $promo->no)
                ->orderBy('qty', 'asc')
                ->first();

            if ($checkbundle && count($cart) >= $checkbundle->qty) {
                // Bundle fulfilled
            } else {
                $fulfilled = false;
            }
        } else {
            // Non-unlimited bundles
            $syaratString = $promo->qty_pack;
            $syarat = intval($syaratString);
            $requiredPacks = range(1, $syarat);

            foreach ($requiredPacks as $requiredPack) {
                $packExistsInCart = false;

                foreach ($cart as $cartItem) {
                    if ($cartItem['pack'] == $requiredPack) {
                        $packExistsInCart = true;
                        break;
                    }
                }

                if (!$packExistsInCart) {
                    $fulfilled = false;
                    break;
                }
            }
        }
        if ($fulfilled) {
            $promo = DB::table('Luv2_promo')->where('no', $nopromo)->where('deleted', 'N')->first();

            if (!$promo) {
                return; // If promo is deleted or doesn't exist, exit the function
            }

            $cart = array_filter($this->carts, function ($cartItem) use ($nopromo) {
                return $cartItem['promo'] == $nopromo;
            });

            $cart = array_values($cart);
            $totalPrice = array_sum(array_column($cart, 'itemprice'));
            if ($promo->tipe == 7) {
                if ($promo->benefit == 1) {
                    $cartcount = count($cart);
                    $qtyDiscs = DB::table('Luv2_promo_bundling_qty')
                        ->where('no', $promo->no)
                        ->where('qty', '>=', $cartcount)
                        ->orderBy('qty', 'asc')
                        ->get();

                    $firstApplicableQty = $qtyDiscs->firstWhere('qty', '>=', $cartcount);

                    if ($firstApplicableQty) {
                        $benefitDisc = $firstApplicableQty->disc;
                        foreach ($cart as &$crt) {
                            if (!str_contains($crt['itemname'], '( Pack Unlimited )')) {
                                $crt['itemname'] .= ' ( Pack Unlimited )';
                            }

                            $discountAmount = ($benefitDisc / 100) * $crt['nprice'];
                            $crt['itemprice'] = $crt['nprice'] - $discountAmount;
                            $crt['discount'] = $benefitDisc;
                            $crt['total_price'] = $crt['itemprice'] * $crt['itemqty'];
                        }
                    }
                }
            } else {
                foreach ($cart as &$crt) {
                    if ($promo->tipe == 3) { // Bundling
                        if ($promo->benefit == 1) { // Bundle discount
                            $benefitDisc = $promo->disc;
                            $discountAmount = ($benefitDisc / 100) * $crt['itemprice'];
                            $crt['itemname'] .= ' ( Pack ' . $crt['pack'] . ' )';
                            $crt['itemprice'] -= $discountAmount;
                            $crt['discount'] = $benefitDisc;
                            $crt['total_price'] = $crt['itemprice'] * $crt['itemqty'];
                        } elseif ($promo->benefit == 2) { // Bundle special price
                            $benefitPrice = $promo->disc_price;
                            $benefitDecimal = ($totalPrice - $benefitPrice) / $totalPrice;
                            $benefitDiscountforSpecialPrice = $crt['itemprice'] * $benefitDecimal;
                            $crt['itemprice'] -= $benefitDiscountforSpecialPrice;
                            $crt['discount'] = $benefitDiscountforSpecialPrice;
                            $crt['total_price'] = $crt['itemprice'] * $crt['itemqty'];
                        }

                        // Session management
                        session(['PromoBundlingFulfill' . auth()->user()->id => $promo->no]);
                    } elseif ($promo->tipe == 4) { // Free item or cheapest item
                        if ($promo->benefit == 1) {
                            $crt['itemname'] .= ' ( Pack ' . $crt['pack'] . ' )';
                            $this->fulfilled = true;
                            session(['Promo-GWP-FreeItem' . auth()->user()->id => $promo->no]);
                        } elseif ($promo->benefit == 2) {
                            $crt['itemname'] .= ' ( Pack ' . $crt['pack'] . ' )';
                            session(['Promo-GWP-CheapestItem' . auth()->user()->id => $promo->no]);
                            session(['PromoTingkat' . auth()->user()->id => $promo->no]);

                            $this->fulfilled = true;
                        } elseif ($promo->benefit == 3) {
                            session(['Promo-Voucher-QTY' . auth()->user()->id => $promo->no]);
                        }
                    }
                }
            }

            // Assuming `$this->carts` is an array of arrays or objects, update them accordingly
            foreach ($cart as $updatedCartItem) {
                foreach ($this->carts as &$originalCartItem) {
                    if ($originalCartItem['id'] == $updatedCartItem['id']) {
                        $originalCartItem = array_merge($originalCartItem, $updatedCartItem);
                        break;
                    }
                }
            }
        }
        if (!$this->discountMoreThanOne) {
        }
        $this->dispatch('cart-created');
    }

    private function itemResourceDiscount($product, $prices, $dataDisc, $pricelist)
    {
        $productCode = is_array($product) ? $product['code'] : $product->code;
        $productName = is_array($product) ? $product['name'] : $product->name;

        $this->increment++;

        $prices = ItemPrice::where('item_code', $productCode)
            ->where('id_pricelist', $pricelist)
            ->first();

        $productPrice = $prices->price;
        $item = [
            'id' => $this->increment,
            'itemname' => $productName,
            'itemcode' => $productCode,
            'itemqty' => 1,
            'oldqty' => 1,
            'itemprice' => $productPrice,
            'nprice' => $productPrice,
            'promo' => 0,
            'promotipe' => 0,
            'pack' => 0,
            'discount' => 0,
            'benefit' => 'N',
        ];


        $arrayDataDisc = is_array($dataDisc) ? true : false;

        if ($arrayDataDisc) {
            $dataDiscEmpty = empty($dataDisc);
        } else {
            $dataDiscEmpty = $dataDisc->isEmpty();
        }

        // Handle discounts if any are provided
        if (!$dataDiscEmpty) {
            $dataDiscCollection = collect($dataDisc);
            $countDataDisc = $dataDiscCollection->pluck('no')->unique()->count();
            if ($countDataDisc > 1) {
                $this->discountMoreThanOne = true;
                $this->selectDiscount($product, $prices, $dataDisc, $pricelist);
            } else {
                $this->discountMoreThanOne = false;
                if ($arrayDataDisc) {
                    $dataDiscNo = $dataDisc['no'];
                    $dataDiscDisc = $dataDisc['disc'];
                    $discountType = $dataDisc['tipe'];
                    $dataDiscDiscPrice = $dataDisc['disc_price'];
                    $dataDiscPack = $dataDisc['pack'];
                    $dataDiscBenefit = $dataDisc['benefit'];
                } else {
                    $dataDiscNo = $dataDisc[0]->no;
                    $dataDiscDisc = $dataDisc[0]->disc;
                    $discountType = $dataDisc[0]->tipe;
                    $dataDiscDiscPrice = $dataDisc[0]->disc_price;
                    $dataDiscPack = $dataDisc[0]->pack;
                    $dataDiscBenefit = $dataDisc[0]->benefit;
                }


                if ($discountType == 1) {
                    // Percentage discount
                    $discountPercentage = $dataDiscDisc;
                    $discountedPrice = $productPrice * (1 - $discountPercentage / 100);
                    $item['itemprice'] = $discountedPrice;
                    $item['promo'] = $dataDiscNo;
                    $item['promotipe'] = $discountType;
                    $item['discount'] = $productPrice - $discountedPrice;
                    $item['benefit'] = $dataDiscBenefit;
                } elseif ($discountType == 2) {
                    // Fixed discount price
                    $discountPrice = $dataDiscDiscPrice;
                    $item['itemprice'] = $discountPrice;
                    $item['promo'] = $dataDiscNo;
                    $item['promotipe'] = $discountType;
                    $item['discount'] = $productPrice - $discountPrice;
                    $item['benefit'] = $dataDiscBenefit;
                } elseif ($discountType == 3) {
                    $checkcart = collect($this->carts)->firstWhere('promo', $dataDiscNo);

                    if ($checkcart) {
                        $packInCarts = collect($this->carts)
                            ->where('promo', $dataDiscNo)
                            ->pluck('pack')
                            ->toArray();

                        $filteredDataDisc = $dataDisc->filter(function ($item) use ($packInCarts) {
                            return !in_array($item->pack, $packInCarts);
                        });

                        $pack = $filteredDataDisc->isNotEmpty() ? $filteredDataDisc->first()->pack : $dataDiscPack;
                    } else {
                        $pack = $dataDiscPack;
                    }

                    $item['promo'] = $dataDiscNo;
                    $item['promotipe'] = $discountType;
                    $item['pack'] = $pack;
                    $item['benefit'] = $dataDiscBenefit;
                } elseif ($discountType == 4) {
                    $item['promo'] = $dataDiscNo;
                    $item['promotipe'] = $discountType;
                    $item['discount'] = $dataDiscDisc;
                    $item['pack'] = $dataDiscPack;
                    $item['benefit'] = $dataDiscBenefit;
                } elseif ($discountType == 5) {
                    $item['promo'] = $dataDiscNo;
                    $item['promotipe'] = $discountType;
                    $item['discount'] = $dataDiscDisc;
                    $item['pack'] = $dataDiscPack;
                    $item['benefit'] = $dataDiscBenefit;
                }
            }
        } else {
        }

        if (session()->has('Promo-GWP-FreeItem' . auth()->user()->id) || session()->has('Promo-GWP-ValueFreeItemFulfil' . auth()->user()->id)) {
            $promoGWPFreeItem = session('Promo-GWP-FreeItem' . auth()->user()->id) ?? session('Promo-GWP-ValueFreeItemFulfil' . auth()->user()->id);
            $freeItems = DB::table('Luv2_promo_item_gwp')->where('no', $promoGWPFreeItem)->pluck('item_code')->toArray();
            if (in_array($item['itemcode'], $freeItems)) {
                session(['StatusPromo' => 'Diskon nih']);
                $dataDiscountGWP = DB::table('Luv2_promo_item_gwp')->where('no', $promoGWPFreeItem)->where('item_code', $item['itemcode'])->first();
                $product = DB::table('Luv2_item')->where('code', $item['itemcode'])->first();
                if ($dataDiscountGWP->disc_price == 0 && $dataDiscountGWP->disc == 0) {
                    $item['itemname'] = $product->name . ' ( FREE ITEM )';
                    $item['itemprice'] = 0;
                    $item['discount'] = -($item['nprice']);
                    $item['promo'] = 0;
                    $item['promotipe'] = 0;
                    $item['pack'] = 0;
                    $item['benefit'] = 'Free';

                    $this->dispatch('clearDiscount');
                } elseif ($dataDiscountGWP->disc == 0) {
                    $item['itemname'] = $product->name . ' ( Special Price )';
                    $item['itemprice'] = $dataDiscountGWP->disc_price;
                    $item['discount'] = $item['nprice'] - $dataDiscountGWP->disc_price;
                    $item['promo'] = 0;
                    $item['promotipe'] = 0;
                    $item['pack'] = 0;
                    $item['benefit'] = 'GWP Special Price';

                    $this->dispatch('clearDiscount');
                } else {
                    $discountPercentage = $dataDiscountGWP->disc; // Example discount percentage
                    $discountedPrice = $item['nprice'] * (1 - $discountPercentage / 100);
                    $item['itemname'] = $product->name . ' ( Disc Special Price )';
                    $item['itemprice'] = $discountedPrice;
                    $item['discount'] = $item['nprice'] - $discountedPrice;
                    $item['promo'] = 0;
                    $item['promotipe'] = 0;
                    $item['pack'] = 0;
                    $item['benefit'] = 'GWP Special Price';

                    $this->dispatch('clearDiscount');
                }
            } else {
                session(['StatusPromo' => 'Enggak Diskon nih']);

                // Do something if $this->form->itemcode does not exist in $freeItems
                // For example:
                // echo "Item code does not exist in free items array";
            }
        } elseif (session()->has('PromoBundlingFulfill' . auth()->user()->id)) {
            $item['promo'] = 0;
            $item['promotipe'] = 0;
            $item['pack'] = 0;
            // dd('kesini beda item dia', $this->form);
        }

        return $item;
    }

    public function checkAvailablePacks($itemCode, $promoCode, $promoTipe)
    {
        $checkCartPacks = array_filter($this->carts, function ($cartItem) use ($promoCode, $promoTipe) {
            return $cartItem['promo'] == $promoCode && $cartItem['promotipe'] == $promoTipe;
        });

        $checkCartPacks = array_column($checkCartPacks, 'pack');

        $availablePacks = DB::table('Luv2_promo_item')
            ->where('no', $promoCode)
            ->where('item_code', $itemCode)
            ->whereNotIn('pack', $checkCartPacks)
            ->pluck('pack')
            ->toArray();

        sort($availablePacks);

        $firstAvailablePack = reset($availablePacks);

        return $firstAvailablePack;
    }

    public function deleteFromCarts($index)
    {
        $itemdeleted = $this->carts[$index];
        if (isset($this->carts[$index])) {
            $cart = $this->carts[$index];
            unset($this->carts[$index]);
            $this->carts = array_values($this->carts);
            if ($itemdeleted['promo'] != 0) {
                $this->updatePriceBundleafterDelete($itemdeleted);
            }
            if (session()->has('Promo-GWP-ValueFreeItemFulfil' . auth()->user()->id) || session()->has('Promo-GWP-ValueCheapestFulfil' . auth()->user()->id) || session()->has('Promo-Voucher-ValueFulfil' . auth()->user()->id)) {
                $this->checkCartValueafterDelete();
            }
            if (session()->has('PromoBundlingFulfill' . auth()->user()->id)) {
                $this->checkCartValueafterDeleteBundling();
            }
        }
    }

    public function updatePriceBundleafterDelete($cart)
    {
        $nopromo = $cart['promo'];

        $cartItems = array_filter($this->carts, function ($item) use ($nopromo) {
            return $item['promo'] == $nopromo;
        });

        $checkbundle = DB::table('Luv2_promo_item')->where('no', $nopromo)->get();
        $fulfilled = true;

        foreach ($checkbundle as $bundleItem) {
            if (!in_array($bundleItem->pack, array_column($cartItems, 'pack'))) {
                $fulfilled = false;
                break;
            }
        }

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

            if ($promo->tipe == 7) {
                if ($promo->benefit == 1) {
                    $cartcount = count($cartItems);

                    $qtyDiscs = DB::table('Luv2_promo_bundling_qty')->where('no', $promo->no)
                        ->orderBy('qty', 'desc')
                        ->get();

                    $firstApplicableQty = null;
                    foreach ($qtyDiscs as $qtyDisc) {
                        if ($cartcount >= $qtyDisc->qty) {
                            $firstApplicableQty = $qtyDisc->qty;
                            break;
                        }
                    }

                    if ($firstApplicableQty !== null) {
                        $applicableQtyDisc = $qtyDiscs->firstWhere('qty', $firstApplicableQty);

                        if ($applicableQtyDisc) {
                            $benefitDisc = $applicableQtyDisc->disc;
                            foreach ($cartItems as &$crt) {
                                if (!Str::contains($crt['itemname'], '( Pack Unlimited )')) {
                                    $crt['itemname'] .= ' ( Pack Unlimited )';
                                }
                                $discountAmount = ($applicableQtyDisc->disc / 100) * $crt['nprice'];

                                $crt['price'] = $crt['nprice'] - $discountAmount;
                                $crt['discount'] = $benefitDisc;
                                $crt['total_price'] = $crt['price'] * $crt['itemqty'];

                                // Update the cart item in $this->carts
                                $this->updateCartItem($crt);
                            }
                        }
                    } else {
                        foreach ($cartItems as &$crt) {
                            $item = Item::where('code', $crt['itemcode'])->first();
                            $crt['itemname'] = $item->name;
                            $crt['price'] = $crt['nprice'];
                            $crt['total_price'] = $crt['price'] * $crt['itemqty'];

                            // Update the cart item in $this->carts
                            $this->updateCartItem($crt);
                        }
                    }
                }
            }
        } else {
            $promo = DB::table('Luv2_promo')->where('no', $nopromo)->where('deleted', 'N')->first();

            if ($promo->tipe == 7 && $promo->benefit == 1) {
                // Additional logic if needed
            } else {
                foreach ($cartItems as &$crt) {
                    $item = Item::where('code', $crt['itemcode'])->first();
                    $crt['itemname'] = $item->name;
                    $crt['price'] = $crt['nprice'];
                    $crt['discount'] = 0;
                    $crt['total_price'] = $crt['price'] * $crt['itemqty'];

                    // Update the cart item in $this->carts
                    $this->updateCartItem($crt);
                }

                if ($promo->tipe == 4) {
                    if ($promo->benefit == 1) { // Free item
                        $freeItems = DB::table('Luv2_promo_item_gwp')->where('no', $promo->no)->pluck('item_code')->toArray();

                        foreach ($cartItems as &$crt) {
                            $item = Item::where('code', $crt['itemcode'])->first();
                            $crt['itemname'] = $item->name;
                            $crt['price'] = $crt['nprice'];
                            $crt['discount'] = 0;
                            $crt['total_price'] = $crt['price'] * $crt['itemqty'];

                            // Update the cart item in $this->carts
                            $this->updateCartItem($crt);
                        }

                        $this->carts = array_filter($this->carts, function ($cart) use ($freeItems) {
                            return !in_array($cart['itemcode'], $freeItems) || $cart['benefit'] !== 'Free';
                        });

                        session()->forget('Promo-GWP-FreeItem' . auth()->user()->id);
                    } elseif ($promo->benefit == 2) { // Cheapest item
                        foreach ($cartItems as &$crt) {
                            $item = Item::where('code', $crt['itemcode'])->first();
                            $crt['itemname'] = $item->name;
                            $crt['price'] = $crt['nprice'];
                            $crt['discount'] = 0;
                            $crt['total_price'] = $crt['price'] * $crt['itemqty'];

                            // Update the cart item in $this->carts
                            $this->updateCartItem($crt);
                        }

                        $this->carts = array_filter($this->carts, function ($cart) {
                            return $cart['benefit'] !== 'Cheapest';
                        });

                        session()->forget('Promo-GWP-CheapestItem' . auth()->user()->id);
                        session()->forget('PromoTingkat' . auth()->user()->id);
                        session()->forget('Promo-GWP-CheapestItemNONAKTIF' . auth()->user()->id);
                    } elseif ($promo->benefit == 3) {
                        session()->forget('Promo-Voucher-QTY' . auth()->user()->id);
                    }
                }
            }
        }

        $this->dispatch('cart-created');
    }

    public function checkCartValueafterDeleteBundling()
    {
        if (session()->has('PromoBundlingFulfill' . auth()->user()->id)) {
            $session = session('PromoBundlingFulfill' . auth()->user()->id);
        }

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

        // Filter the cart items that match the promo and belong to the current user
        $cart = array_filter($this->carts, function ($cartItem) use ($session) {
            return $cartItem['promo'] == $session;
        });

        $cartCount = count($cart);

        if ($cartCount < $promo->qty_pack) {
            session()->forget('PromoBundlingFulfill' . auth()->user()->id);

            foreach ($cart as &$item) {
                $product = DB::table('Luv2_item')->where('code', $item['code'])->first();
                $item['name'] = $product->name;
                $item['price'] = $product->nprice;
                $item['total_price'] = $product->nprice * $item['itemqty'];
            }

            // Update $this->carts with the modified items
            $this->carts = array_map(function ($cartItem) use ($cart) {
                return in_array($cartItem, $cart) ? $cartItem : $cartItem;
            }, $this->carts);
        }

        $this->dispatch('cart-created');
    }

    #[On('checkCartValueafterDelete')]
    public function checkCartValueafterDelete()
    {
        if (session()->has('Promo-GWP-ValueFreeItem' . auth()->user()->id)) {
            $session = session('Promo-GWP-ValueFreeItem' . auth()->user()->id);
        } elseif (session()->has('Promo-GWP-ValueCheapest' . auth()->user()->id)) {
            $session = session('Promo-GWP-ValueCheapest' . auth()->user()->id);
        } elseif (session()->has('Promo-Voucher-Value' . auth()->user()->id)) {
            $session = session('Promo-Voucher-Value' . auth()->user()->id);
        }

        $promo = DB::table('Luv2_promo')->where('no', $session)->first();
        $cart = array_filter($this->carts, function ($cartItem) {
            return $cartItem['promo'] == 0 && $cartItem['benefit'] != 'GWP Special Price';
        });

        $cartTotalPrice = array_reduce($cart, function ($sum, $cartItem) {
            return $sum + ($cartItem['itemqty'] * $cartItem['itemprice']);
        }, 0);

        if ($cartTotalPrice < $promo->value_pack) {
            if ($promo->tipe == 5 && $promo->benefit == 1) {
                $freeItems = DB::table('Luv2_promo_item_gwp')->where('no', $promo->no)->pluck('item_code')->toArray();

                // Filter out free items from $this->carts
                $this->carts = array_filter($this->carts, function ($cartItem) use ($freeItems) {
                    return !in_array($cartItem['itemcode'], $freeItems) ||
                        !in_array($cartItem['benefit'], ['Free', 'GWP Special Price']);
                });

                session()->forget('Promo-GWP-ValueFreeItemFulfil' . auth()->user()->id);
            } elseif ($promo->tipe == 5 && $promo->benefit == 2) {
                // Filter out the cheapest items from $this->carts
                $this->carts = array_filter($this->carts, function ($cartItem) {
                    return $cartItem['benefit'] != 'Cheapest';
                });

                session()->forget('Promo-GWP-ValueCheapestFulfil' . auth()->user()->id);
            } elseif ($promo->tipe == 5 && $promo->benefit == 3) {
                session()->forget('Promo-Voucher-ValueFulfil' . auth()->user()->id);
            }
        }

        $this->dispatch('cart-created');
    }
    private function updateCartItem($updatedItem)
    {
        foreach ($this->carts as &$cart) {
            if ($cart['id'] === $updatedItem['id']) {
                $cart = $updatedItem;
                break;
            }
        }
    }

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

        $hasPermission = $user->authorizations
            ->filter(function ($authorization) {
                return strpos($authorization->auth, 'C') !== false;
            })
            ->contains('id_auth', $authorization->id);
        if ($hasPermission) {
            if (session()->has('Promo-GWP-CheapestItem' . auth()->user()->id) || session()->has('Promo-GWP-ValueCheapestFulfil' . auth()->user()->id)) {
                $this->processCheapestItem();
            }

            foreach ($this->carts as $cartItem) {
                $this->form->itemname = $cartItem['itemname'];
                $this->form->itemcode = $cartItem['itemcode'];
                $this->form->itemqty = $cartItem['itemqty'];
                $this->form->itemprice = $cartItem['itemprice'];
                $this->form->nprice = $cartItem['nprice'];
                $this->form->promo = $cartItem['promo'];
                $this->form->promotipe = $cartItem['promotipe'];
                $this->form->pack = $cartItem['pack'];
                $this->form->discount = $cartItem['discount'];
                $this->form->benefit = $cartItem['benefit'];

                $cart = $this->form->store();

            }

            $this->reset(['searchitem', 'selectedProduct']);
            $this->dispatch('cart-created', $cart->id)->to(Table::class);
            $this->dispatch('updatePrice')->to(Transaction::class);
            // $this->form->reset();
        }


        $this->products = [];
        $this->carts = [];
        $this->dispatch('clearsesii');

    }

    public function processCheapestItem()
    {
        $promo = DB::table('Luv2_promo')->where('no', $this->no['no'])->first();
        if ($promo) {
            $limit = $promo->cheapest_qty;
            // Sort the carts by item price in ascending order
            usort($this->carts, function ($a, $b) {
                return $a['itemprice'] <=> $b['itemprice'];
            });

            // Change the price of the cheapest items to 0 based on the limit
            for ($i = 0; $i < $limit && $i < count($this->carts); $i++) {
                $this->carts[$i]['itemprice'] = 0;
                $this->carts[$i]['itemname'] .= ' ( FREE ITEM )';

            }
        }
    }

    #[On('trueSuggestionToProcDisc')]
    public function trueSuggestionToProcDisc()
    {
        $this->isSuggestion = true;
        $nopromo = $this->no['no'] ?? 0;
        $promo_tipe = $this->no['tipe'] ?? 0;
        $promo = DB::table('Luv2_promo')->where('no', $nopromo)->get();

        // Use $this->carts instead of querying the Cart model
        $cart = collect($this->carts);
        $cartPacks = $cart->pluck('pack');

        $checkbundle = DB::table('Luv2_promo_item')
            ->join('Luv2_promo', 'Luv2_promo_item.no', '=', 'Luv2_promo.no')
            ->where('Luv2_promo_item.no', $nopromo)
            ->where('Luv2_promo.tipe', $promo_tipe)
            ->whereNotIn('pack', $cartPacks)
            ->orderByRaw('RANDOM()') // Order by random
            ->get();

        $fulfilled = true;
        $unfulfilledItems = [];

        foreach ($checkbundle as $bundleItem) {
            if (!$cartPacks->contains($bundleItem->pack)) {
                $fulfilled = false;
                $unfulfilledItems[] = $bundleItem;
            }
        }

        $unfulfilledItemsCollect = collect($unfulfilledItems);
        $unfulfilledItemDetails = [];

        foreach ($unfulfilledItemsCollect->unique('pack') as $item) {
            $itemDetails = DB::table('Luv2_item')->where('code', $item->item_code)->first();

            // Check if the item details exist and the pack is not in the cart
            if ($itemDetails && !$cartPacks->contains($item->pack)) {
                $itemDetails->no = $item->no; // Add the 'no' field to the item details
                $itemDetails->pack = $item->pack;
                $unfulfilledItemDetails[] = $itemDetails;
            }
        }

        $this->suggestion = $unfulfilledItemDetails;


    }

    // public function  mount()
    // {
    //     $this->suggestion = [
    //         ['no' => 1, 'code' => 'P001', 'name' => 'Product 1', 'pack' => 'Pack 1', 'barcode' => '1234567890'],
    //         ['no' => 2, 'code' => 'P002', 'name' => 'Product 2', 'pack' => 'Pack 2', 'barcode' => '0987654321'],
    //     ];
    // }

    public function addSuggestion($itemcode)
    {
        $product = DB::table('Luv2_item')->where('code', $itemcode)
            ->where('sales', 'Y')
            ->where('active', 'Y')
            ->first();
        $this->isEnter = true;
        $this->dispatch('toAddProductSuggestionsDiscount', $product);
    }

    public function addSuggestionFirst($itemcode)
    {
        $product = DB::table('Luv2_item')
            ->where('code', $itemcode)
            ->where('sales', 'Y')
            ->where('active', 'Y')
            ->first();
        $this->isEnter = true;
        $this->dispatch('toAddProductSuggestionsDiscount', $product);
    }


    #[On('toAddProductSuggestionsDiscount')]
    public function toaddproduct($product)
    {
        $objectProduct = (object) $product;

        $this->toProductDiscount($objectProduct);
    }

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

    #[On('clearsesii')]
    public function clearses()
    {
        session()->forget('Promo-GWP-CheapestItemNONAKTIF' . auth()->user()->id);
        session()->forget('Promo-GWP-CheapestItem' . auth()->user()->id);
        session()->forget('PromoSudahAda' . auth()->user()->id);

    }

}
