<?php

namespace App\Livewire\Cashier;

use App\Livewire\Forms\CartForm;
use App\Models\Cart;
use App\Models\ItemPrice;
use App\Models\Sales;
use App\Models\Settings;
use App\Models\Warehouse;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Livewire\Component;
use Livewire\Attributes\On;

class Table extends Component
{
    use LivewireAlert;

    public $selectedSales = null;
    public $isSalesModalVisible = false;
    public $isDropdownVisible = false;
    public $isDropdownsalesVisible = false;
    public $searchsales = "";
    public $modalOpen = false;
    public $isSuggestion = false;
    public $suggestionName;
    public $suggestion = [];
    public $sales = [];
    public $isCarts = [];
    public $selectedCode;
    public $selectedIndex;
    public $refreshKey = 0;
    public CartForm $form;

    // protected $listeners = ['successSyncNotification' => 'notifySuccess'];

    // public function notifySuccess($responseData)
    // {
    //     Log::info('Success Sync Notification', ['responseData' => $responseData]);
    //     $this->alert('success', $responseData['Message'], [
    //         'position' => 'top-end',
    //         'timer' => 5000,
    //         'toast' => true,
    //         'timerProgressBar' => true,
    //     ]);
    // }

    #[On('cart-created')]
    public function updateCart() {}
    #[On('selectedSalesChangedAfterModal')]
    public function updatedSearchsalesafterModal($selectedSales)
    {
        $this->searchsales = $selectedSales['name'];
    }
    #[On('selectedSalesChanged')]
    public function updateSelectedSales($selectedSales)
    {
        $this->selectedSales = $selectedSales;
    }

    #[On('selectedSalesafterInvoice')]
    public function updatedSelectedSales()
    {
        $this->selectedSales = null;
        $this->searchsales = "";
    }

    public function deleteLatestCart()
    {
        $latestCart = Cart::latest()->first();

        if ($latestCart) {
            $latestCart->delete();
        }
        $this->dispatch('updatePrice');
    }

    #[On('reRender')]
    public function refreshKey()
    {
        $this->refreshKey++;
    }

    public function render()
    {
        $sales = [];
        $carts = [];
        $user = Auth::user();
        if (strlen($this->searchsales) >= 1) {
            $sales = DB::table('Luv2_salesemp')->where('name', 'ILIKE', '%' . $this->searchsales . '%')->limit(10)->get();
            $this->sales = $sales;
        }
        $cartData = Cart::where('id_user', $user->id)
            ->orderBy('grouping', 'desc')
            ->orderBy('promo', 'desc')
            ->orderBy('pack', 'asc')
            ->get();

        foreach ($cartData as $cart) {
            $promptPacks = DB::table('Luv2_promo_item')
                ->where('no', $cart->promo)
                ->where('item_code', $cart->code)
                ->pluck('pack')
                ->toArray();

            if ($promptPacks) {
                $maxPack = max($promptPacks);
                if ($cart->pack < $maxPack) {
                    $maxpack = 'N';
                } else {
                    $maxpack = 'Y';
                }
            } else {
                $maxpack = 'Y';
            }

            $carts[] = [
                'id' => $cart->id,
                'code' => $cart->code,
                'name' => $cart->name,
                'price' => $cart->price,
                'qty' => $cart->qty,
                'created_at' => $cart->created_at,
                'updated_at' => $cart->updated_at,
                'total_price' => $cart->total_price,
                'id_member' => $cart->id_member,
                'id_sales' => $cart->id_sales,
                'id_user' => $cart->id_user,
                'id_item' => $cart->id_item,
                'nprice' => $cart->nprice,
                'discount' => $cart->discount,
                'barcode' => $cart->barcode,
                'sandbox' => $cart->sandbox,
                'promo' => $cart->promo,
                'promo_tipe' => $cart->promo_tipe,
                'pack' => $cart->pack,
                'benefit' => $cart->benefit,
                'maxpack' => $maxpack,
            ];
        }

        $this->isCarts = $carts;

        return view('livewire.cashier.table', [
            'carts' => $carts,
            'sales' => $sales,
            'carttotal' => Cart::where('id_user', $user->id)->get(),

        ]);
    }

    public function sameCart($cartId, $qty)
    {
        $cart = Cart::find($cartId);
        $sessionmember = session('discountmemb');
        $memberId = $cart->member_id;
        $now = now();
        $user = Auth::user();
        $setting = Settings::where('wh_code', $user->whs_code)->first();
        $whs = Warehouse::where('code', $setting->wh_code)->first();
        // if (session('discountmemb') == 1) { //dinonaktifkandulu
        //     $pricelist = $setting->member_pricelist;
        // } else {
        // }
        $pricelist = $whs->id_pricelist;

        if ($cart) {
            $cart->update([
                'qty' => $qty,
                'total_price' => $cart->price * $qty,
            ]);
            $itemPriceDiscounts = DB::table('Luv2_promo_item_qty')
                ->where('no', $cart->promo)
                ->orderBy('qty', 'asc')
                ->get();
            $discqty = DB::table('Luv2_promo_item_qty')
                ->where('no', $cart->promo)
                ->orderBy('qty', 'asc')
                ->first();
            $pricedisc = DB::table('Luv2_promo_item')
                ->where('no', $cart->promo)
                ->first();
            foreach ($itemPriceDiscounts as $itemPriceDiscount) {
                if ($cart->qty >= $itemPriceDiscount->qty) {
                    $price = $itemPriceDiscount->disc_price;
                    $cart->update([
                        'price' => $price,
                        'qty' => $qty,
                        'total_price' => $price * $qty,
                        'promo' => $itemPriceDiscount->no,
                        'discount' => $discqty->disc
                    ]);
                }
                if ($cart->qty < $discqty->qty) {
                    if ($pricedisc) {
                        $cart->update([
                            'price' => $pricedisc->disc_price,
                            'qty' => $qty,
                            'total_price' => $pricedisc->disc_price * $qty,
                            'promo' => $pricedisc->no,
                            'discount' => 0
                        ]);
                    } else {

                        $prices = ItemPrice::where('item_code', $cart->code)->where('id_pricelist', $pricelist)->first();
                        $cart->update([
                            'price' => $prices->price,
                            'qty' => $qty,
                            'total_price' => $prices->price * $qty,
                            'promo' => '',
                            'discount' => 0
                        ]);
                    }
                }
            }
        }

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

    public function deleteCart($cartId)
    {
        $cart = Cart::findOrFail($cartId);
        $promo = $cart->promo;
        $promo_tipe = $cart->promo_tipe;
        if ($cart) {
            $cart->delete();
            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->dispatch('checkCartValueafterDelete')->to(Transaction::class);
            }
            if (session()->has('PromoBundlingFulfill' . auth()->user()->id)) {
                $this->dispatch('checkCartValueafterDeleteBundling')->to(Transaction::class);
            }
            if ($cart->promo != 0) {
                $promoSudahAda = session('PromoSudahAda' . auth()->user()->id);

                if ($promoSudahAda) {
                    $this->dispatch('checkCartPromoSudahAda', $promoSudahAda);
                }
                $this->dispatch('checkPriceBundle', $cart)->to(Transaction::class);
            }
            $countcarts = Cart::count();
            if ($countcarts == 0) {
                $this->dispatch(event: 'redirectToRefresh');
            }
        }
        $this->dispatch('updatePrice');
    }

    #[On('redirectToRefresh')]
    public function redirectTo()
    {
        return redirect()->route('welcome.dashboard');
    }

    #[On('openModalAfterSkipGWP')]
    public function createInvoice()
    {
        $this->modalOpen = true;
        $this->dispatch('modalInvoiceOpenorClose', $this->modalOpen)->to(Transaction::class);
        $this->dispatch('createInvoice');
    }

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

    public function salesModal()
    {
        $this->isSalesModalVisible = true;
        $this->dispatch('salesModal', $this->isSalesModalVisible);
    }

    public function selectSalesByClick($salesCode)
    {

        $sales = Sales::where('code', $salesCode)
            ->where('active', 'Y')
            ->first();

        if ($sales) {

            $this->searchsales = $sales->name;
            $this->selectedSales = $sales;
            $this->form->sales = $sales->code;

            $this->dispatch('selectedSalesChanged', $this->selectedSales);
            $this->dispatch('selectedSalesChanged', $this->selectedSales)->to(Invoice::class);
            $this->isDropdownsalesVisible = false; // Close the dropdown
            $this->alert('info', 'Sales: ' . $sales->name, [
                'position' => 'top',
                'timer' => 3000,
                'toast' => true,
                'timerProgressBar' => true,
            ]);
        }
    }
    public function updatedSearchsales()
    {
        $this->selectedSales = null; // Clear the selected product when the search field changes
        $this->dispatch('selectedSalesChanged', $this->selectedSales);
        $this->isDropdownsalesVisible = (strlen($this->searchsales) >= 1);
    }

    public function refresh() {}

    #[On('suggestionToTable')]
    public function suggestion($isSuggestion, $suggestionName, $suggestion)
    {
        $this->refresh();

        // dd($isSuggestion, $suggestionName, $suggestion);
        $this->isSuggestion = $isSuggestion;
        $this->suggestionName = $suggestionName;
        $this->suggestion = $suggestion;
    }

    public function addSuggestion($itemCode)
    {
        $this->dispatch('addSuggestion', $itemCode)->to(Transaction::class);
    }

    public function addSuggestionFirst($itemCode)
    {
        $this->dispatch('addSuggestionFirst', $itemCode)->to(Transaction::class);
    }

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

        $sales = Sales::where('code', $this->selectedCode)
            ->where('active', 'Y')
            ->first();

        if ($sales) {

            $this->searchsales = $sales->name;
            $this->selectedSales = $sales;
            $this->form->sales = $sales->code;

            $this->dispatch('selectedSalesChanged', $this->selectedSales);
            $this->dispatch('selectedSalesChanged', $this->selectedSales)->to(Invoice::class);
            $this->isDropdownsalesVisible = false; // Close the dropdown
            // Clear selectedCode and selectedIndex
            $this->selectedCode = null;
            $this->selectedIndex = null;
            $this->alert('info', 'Sales: ' . $sales->name, [
                'position' => 'top',
                'timer' => 3000,
                'toast' => true,
                'timerProgressBar' => true,
            ]);
        }
    }

    #[On('closeSalesModal')]
    public function closeSalesModalDispatch($isSalesModalVisible)
    {
        $this->isSalesModalVisible = $isSalesModalVisible;
    }

    #[On('closeSalesModalIndex')]
    public function closeSalesModalIndexDispatch($isSalesModalVisible)
    {
        $this->isSalesModalVisible = $isSalesModalVisible;
    }

    public function cartEmpty()
    {
        $this->alert('info', 'Cart is empty, please add at least 1 item !', [
            'position' => 'top',
            'timer' => 3000,
            'toast' => true,
            'timerProgressBar' => true,
        ]);
    }
    public function createInvoiceOpen()
    {
        $currentDate = now()->toDateString();
        
        $promoExists = DB::table('Luv2_promo')
            ->whereDate('from_date', '<=', $currentDate)
            ->whereDate('to_date', '>=', $currentDate) 
            ->where('tipe', 5)
            ->where('deleted', 'N')
            ->exists();
        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(event: 'createInvoice');
        } else {
            if($promoExists){
                $this->dispatch('toActiveNcheckGWPValue')->to(Transaction::class); 
            }else{
                $this->dispatch(event: 'createInvoice');
            }
        }
    }
}
