<?php

namespace App\Livewire\Returnsale;

use App\Livewire\Cashier\Invoice;
use App\Livewire\Cashier\Transaction;
use App\Livewire\Forms\CartForm;
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 Illuminate\Support\Facades\Log;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Attributes\On;
use Illuminate\Support\Str;
use Livewire\Component;

class Newitem extends Component
{
    use LivewireAlert;

    public $searchitem = '';
    public $selectedProduct;
    public $products = [];
    public $isEnter = false;
    public $selectedCode;
    public $selectedIndex;
    public $carts = [];
    public $overalPrice = 0;
    public $defaultOveralPrice = 0;
    public $itembrand;
    public $increment = 0;
    public $item;
    public $recorditem;
    public $discountMoreThanOne = false;

    public CartForm $form;

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

        $setting = Settings::first();
        $whs = Warehouse::where('code', $setting->wh_code)->first();
        $pricelist = $whs->id_pricelist;
        $fields = DB::getSchemaBuilder()->getColumnListing('Luv2_item');
        $brand = in_array('U_IDU_Brand', $fields);

        if (strlen($this->searchitem) >= 1) {
            $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 . '%');
                })
                ->when($brand, function ($query) {
                    $query->where(function ($query) {
                        $query->whereIn('Luv2_item.U_IDU_Brand', $this->itembrand)
                            ->orWhere('Luv2_item.U_IDU_Brand', '=', '')
                            ->orWhereNull('Luv2_item.U_IDU_Brand');
                    });
                })
                ->limit(10)
                ->get();

            $this->products = $results;
        }


        $carts = Cart::where('id_user', auth()->user()->id)->get();


        return view('livewire.returnsale.newitem', [
            'products' => $results,
            'carts' => $carts,
        ]);
    }

    #[On('changeOveralPrice')]
    public function updateOveralPrice($overalPrice, $item)
    {
        $fields = DB::getSchemaBuilder()->getColumnListing('Luv2_item');
        $brand = in_array('U_IDU_Brand', $fields);
        $this->item = array_values($item);
        foreach ($this->item as $key => $singleItem) {
            $this->recorditem[$key] = DB::table('Luv2_item')->where('code', $singleItem['code'])->first();
            if ($brand) {
                $this->itembrand[$key] = $this->recorditem[$key]->U_IDU_Brand;
            }
        }
        $this->overalPrice = $overalPrice;
        $this->defaultOveralPrice = $overalPrice;
    }

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

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

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

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

    public function byClick($itemCode)
    {
        Log::info('byClick called with itemCode: ' . $itemCode);

        $product = DB::table('Luv2_item')->where('code', $itemCode)
            ->where('sales', 'Y')
            ->where('active', 'Y')
            ->first();
        if ($product) {
            $this->toProduct($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->toProduct($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 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();
        $dataDisc = DB::table('Luv2_promo')
            ->where('deleted', 'N')
            ->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->itemResource($product, $prices, $dataDisc, $pricelist);

        $this->addToCarts($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->dispatch('clearSearch');
    }

    public function addToCarts($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 {
            if (!$this->discountMoreThanOne) {
                $this->calculateOveralPrice();
            }
        }
    }

    #[On('checkCartValue')]
    public function checkCartValue()
    {
        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) {
                session(['Promo-GWP-ValueFreeItemFulfil' . auth()->user()->id => $session]);
            } elseif ($promo->tipe == 5 && $promo->benefit == 2) {
                if (session()->has('Promo-GWP-ValueCheapestFulfil' . auth()->user()->id)) {
                    // Already fulfilled, do nothing
                } else {
                    $this->dispatch('openModalCheapest', $this->carts)->to(Table::class);
                }
            } elseif ($promo->tipe == 5 && $promo->benefit == 3) {
                session(['Promo-Voucher-ValueFulfil' . auth()->user()->id => $session]);
            }
        }
    }


    #[On('toActiveNcheckGWPValue')]
    public function activencheckgwpvalue()
    {
        $currentDate = Carbon::now()->toDateString();

        // Assuming $this->carts is your in-memory cart array
        $carts = $this->carts;
        $promoVoucherExists = false;

        foreach ($carts as $cartItem) {
            $promocheck = DB::table('Luv2_promo')->where('no', $cartItem['promo'])->first();
            if ($promocheck) {
                if ($promocheck->tipe == 4 && $promocheck->benefit == 3) {
                    $promoVoucherExists = true;
                    break;
                }
            } else {
                $promoVoucherExists = false;
            }
        }

        if ($promoVoucherExists) {
            $promo = DB::table('Luv2_promo')
                ->whereDate('from_date', '<=', $currentDate)
                ->whereDate('to_date', '>=', $currentDate)
                ->where('tipe', 5)
                ->get();
        } else {
            $promo = DB::table('Luv2_promo')
                ->whereDate('from_date', '<=', $currentDate)
                ->whereDate('to_date', '>=', $currentDate)
                ->where(function ($query) {
                    $query->where('tipe', 5)
                        ->orWhere(function ($query) {
                            $query->where('tipe', 6)
                                ->where('benefit', 2);
                        });
                })
                ->get();
        }

        if (empty($promo) || $promo->isEmpty()) {
            // Handle the case where $promo is empty
        } else {
            // Handle the case where $promo is not empty
            if ($promo->count() > 1) {
                if (count($carts) >= 1) {
                    $this->dispatch('selectValue', $promo)->to(SelectDiscount::class);
                }
            } else {
                if ($promoVoucherExists) {
                    if ($promo[0]->tipe == 5 && $promo[0]->benefit == 1) {
                        session(['Promo-GWP-ValueFreeItem' . auth()->user()->id => $promo[0]->no]);
                        $this->checkCartValue();
                    } elseif ($promo[0]->tipe == 5 && $promo[0]->benefit == 2) {
                        session(['Promo-GWP-ValueCheapest' . auth()->user()->id => $promo[0]->no]);
                        $this->checkCartValue();
                    } elseif ($promo[0]->tipe == 5 && $promo[0]->benefit == 3) {
                        // no discount again
                    }
                } else {
                    if ($promo[0]->tipe == 5 && $promo[0]->benefit == 1) {
                        session(['Promo-GWP-ValueFreeItem' . auth()->user()->id => $promo[0]->no]);
                        $this->checkCartValue();
                    } elseif ($promo[0]->tipe == 5 && $promo[0]->benefit == 2) {
                        session(['Promo-GWP-ValueCheapest' . auth()->user()->id => $promo[0]->no]);
                        $this->checkCartValue();
                    } elseif ($promo[0]->tipe == 5 && $promo[0]->benefit == 3) {
                        session(['Promo-Voucher-Value' . auth()->user()->id => $promo[0]->no]);
                        $this->checkCartValue();
                    }
                }
            }
        }
    }


    public function calculateOveralPrice()
    {
        $this->overalPrice = 0;
        foreach ($this->carts as $cartItem) {
            $this->overalPrice -= $cartItem['itemprice'] * $cartItem['itemqty'];
        }

        $this->overalPrice += $this->defaultOveralPrice;
    }

    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'] . ' )';
                            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]);
                            $this->dispatch('openModalCheapest', $this->carts)->to(Table::class);
                        } 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->calculateOveralPrice();
        }
        $this->dispatch('cart-created');
    }


    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;
    }


    #[On('selectedValueData')]
    public function selectedValueData($data)
    {
        $promo = DB::table('Luv2_promo')->where('no', $data)->first();
        if ($promo->tipe == 5 && $promo->benefit == 1) {
            session(['Promo-GWP-ValueFreeItem' . auth()->user()->id => $promo->no]);
        } elseif ($promo->tipe == 5 && $promo->benefit == 2) {
            session(['Promo-GWP-ValueCheapest' . auth()->user()->id => $promo->no]);
        } elseif ($promo->tipe == 6 && $promo->benefit == 2) {
            session(['Promo-Voucher-Value' . auth()->user()->id => $promo->no]);
        }
    }

    #[On('selectedDiscountData')]
    public function toProductAfterSelectDiscount($product, $prices, $dataDisc, $pricelist)
    {
        $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 {
        $item = $this->itemResource($product, $prices, $dataDisc, $pricelist);
        $this->addToCarts($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->dispatch('clearSearch');
    }

    public function itemResource($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 selectDiscount($product, $prices, $dataDisc, $pricelist)
    {
        $this->dispatch('selectDiscount', $product, $prices, $dataDisc, $pricelist)->to(SelectDiscount::class);
    }

    #[On('clearDiscount')]
    public function clearDiscount()
    {
        session()->forget('Promo-GWP-FreeItem' . auth()->user()->id);
        session()->forget('Promo-GWP-CheapestItem' . auth()->user()->id);

        session()->forget('StatusPromo');
    }


    #[On('toSave')]
    public function save()
    {
        // dd($this->item);
        $user = Auth::user();
        $authorization = Auths::where('menu', 'Transaction')
            ->where('modul', 'Sales')->first(); // Fetch the specific authorization

        $hasPermission = $user->authorizations
            ->filter(function ($authorization) {
                return strpos($authorization->auth, 'C') !== false;
            })
            ->contains('id_auth', $authorization->id);
        if ($hasPermission) {
            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();
            }
            foreach ($this->item as $cartItem) {
                $this->form->itemname = $cartItem['name'];
                $this->form->itemcode = $cartItem['code'];
                $this->form->itemqty = -$cartItem['qty'];
                $this->form->itemprice = $cartItem['price'];
                $this->form->nprice = $cartItem['nprice'];
                $this->form->promo = $cartItem['promo'];
                $this->form->promotipe = $cartItem['promo_tipe'];
                $this->form->pack = $cartItem['pack'];
                $this->form->discount = $cartItem['disc'];
                $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();
        }

        $data = [
            'item' => $this->item,
            'overalPrice' => $this->overalPrice,
        ];
        // $this->dispatch('dataReturn', $data)->to(Returntable::class);
        $this->products = [];
        $this->carts = [];
        $this->clearses();
        $this->dispatch('isData', $data)->to(Table::class);
        $this->dispatch('newData', $data)->to(Returntable::class);
    }

    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();
            }



            $this->overalPrice = 0;
            foreach ($this->carts as $cartItem) {
                $this->overalPrice -= $cartItem['itemprice'] * $cartItem['itemqty'];
            }

            $this->overalPrice += $this->defaultOveralPrice;
        }
    }

    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('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');
    }


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

    #[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');
    }




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

            if ($newQty != $originalQty) {
                $qtyDifference = $newQty - $originalQty;
                $priceChange = $cart['nprice'] * $qtyDifference;
                $this->carts[$index]['itemprice'] = $cart['nprice'] * $newQty;
                $this->overalPrice -= $priceChange;
                $this->carts[$index]['itemqty'] = $newQty;
                $this->carts[$index]['oldqty'] = $newQty;
            }
        }
    }

    #[On('clearses')]
    public function clearses()
    {
        session()->forget('Promo-GWP-CheapestItemNONAKTIF' . auth()->user()->id);
        session()->forget('Promo-GWP-ValueCheapest' . auth()->user()->id);
        session()->forget('Promo-GWP-ValueFreeItem' . auth()->user()->id);
        session()->forget('Promo-GWP-ValueCheapestFulfil' . auth()->user()->id);
        session()->forget('Promo-Voucher-QTY' . auth()->user()->id);
        session()->forget('Promo-Voucher-Value' . auth()->user()->id);
        session()->forget('Promo-Voucher-ValueFulfil' . auth()->user()->id);
        session()->forget('Promo-GWP-FreeItem' . auth()->user()->id);
        session()->forget('Promo-GWP-CheapestItem' . auth()->user()->id);
        session()->forget('Promo-GWP-ValueFreeItemFulfil' . auth()->user()->id);
        session()->forget('PromoBundlingFulfill' . auth()->user()->id);
        session()->forget('PromoSudahAda' . auth()->user()->id);
        session()->forget('member');
    }

    #[On('openModalSelect')]
    public function bringDispatch()
    {
        $this->dispatch('openModalSelect')->to(Table::class);
    }

    #[On('updateTheCarts')]
    public function updateTheCarts($data)
    {
        foreach ($data as $newItem) {
            $found = false;
            foreach ($this->carts as &$cartItem) {
                if ($cartItem['id'] == $newItem['id']) {
                    $cartItem = array_merge($cartItem, $newItem);
                    $found = true;
                    break;
                }
            }
            if (!$found) {
                $this->carts[] = $newItem;
            }
        }
        $this->calculateOveralPrice();
    }
}
