<?php

namespace App\Livewire\Returnsale;

use App\Livewire\Returnsale\Table as ReturnsaleTable;
use App\Mail\MyTestMail;
use App\Models\Cart;
use App\Models\DetailInvoice;
use App\Models\Invoice;
use App\Models\Item;
use App\Models\ItemPrice;
use App\Models\ItemPriceListDisc;
use App\Models\ItemPriceListDiscQty;
use App\Models\ItemTrans;
use App\Models\Member;
use App\Models\Sales;
use App\Models\Settings;
use App\Models\User;
use App\Models\Warehouse;
use Carbon\Carbon;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
use Livewire\Attributes\On;
use Livewire\Attributes\Rule;
use Livewire\Component;
use Jantinnerezo\LivewireAlert\LivewireAlert;
use Mike42\Escpos\PrintConnectors\WindowsPrintConnector;
use Mike42\Escpos\CapabilityProfile;
use Mike42\Escpos\Printer;



class Inputreturn extends Component
{
    use LivewireAlert;

    public $selectedItems;
    public $selectedItemsDetails;
    public $selectedItemsPrice;
    public $member;
    public $payment = null;
    public $totalAmount = 0;
    public $change = null;
    public $type;
    public $transfer;
    public $cash = null;
    public $namaBank;
    public $namaPemegangKartu;
    public $inputs = [];
    public $i = 1;
    public $totalPrice = 0;
    public $cashier;
    public $invoice;
    public $sales;
    public $oldinvoice;
    public $itemReturnDetails;
    public $storeitem = [];
    public $oldPrice;
    public $newItem;
    public $refreshKey = 0;
    public $voucherCashback;
    public $message;
    public $voucherApplied = false;
    public $totalForPay;
    public $isCashback = false;
    public $searchvoucher = '';
    public $noreturn = '';




    #[Rule('min:4', message: 'Nomor Kartu must be 4 digits.')]
    #[Rule('max:4', message: 'Nomor Kartu must be 4 digits.')]
    public $nomorKartu;

    #[Rule('required', message: 'The payment option is required.')]
    public $paymentOption = 'cash';


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

    public function mount($item)
    {
        $this->itemReturnDetails = $item['item'];
        $cartItems = Cart::where('id_user', auth()->user()->id)
            ->whereRaw('CAST(qty AS INTEGER) > 0')
            ->get()
            ->toArray();

        $this->newItem = $cartItems;
        $this->totalAmount = -$item['overalPrice'];
    }

    
    public function store()
    {
        $user = Auth::user();
        $item = $this->itemReturnDetails;
        $invoice = $item[0]['invoice'];
        $datainvoiceexist = Invoice::where('no', $invoice)->first();
        $this->oldinvoice = $datainvoiceexist;
        $this->member = Member::where('code', $datainvoiceexist->id_member)->first();
        $this->sales = Sales::where('code', $datainvoiceexist->id_sales)->first();
        $huruf = 'RS';
        // Date
        $tanggal = Carbon::now()->isoFormat('YYMMDDHHmm');

        // Count invoices created today
        $countinvoice = DB::table('Luv2_invoice')
            ->where('id_user', $user->id)
            ->whereDate('created_at', Carbon::today())
            ->count();
        $countinvoice += 1;

        // set max 999 to count inv
        $countinvoice = min($countinvoice, 999);
        // set default 3 digit count inv
        $countinvoice = str_pad($countinvoice, 3, '0', STR_PAD_LEFT);
        $code = $user->code;

        $invoicereturn = $huruf . $code . $tanggal . $countinvoice;
        $maxId = Invoice::max('id');
        $invoiceData = [
            'id' => $maxId + 1,
            'id_user' => $user->id,
            'no' => $invoicereturn,
            'id_member' => $datainvoiceexist->id_member,
            'payment' => '',
            'paid' => '',
            'change' => '',
            'must_paid' => $this->totalAmount,
            'date' => Carbon::now(),
            'note' =>  '',
            'promo' => '0',
            'cashback' => 'N',
            'subtotal' => $this->totalAmount,
            'no_inv' => $datainvoiceexist->no,
            'cardcode' => $datainvoiceexist->cardcode,
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ];
        if ($datainvoiceexist->payment == 'Multi') {
            $invoiceNote = json_decode($datainvoiceexist->note, true);
            $cash = $invoiceNote['cash'] ?? 0; // Assuming default value of cash is 0 if not set
            $transfer = $invoiceNote['transfer'] ?? 0; // Assuming default value of transfer is 0 if not set
            $type = $invoiceNote['type'];
            $bank = $invoiceNote['nama_bank'];
            $pemegangkartu = $invoiceNote['nama_pemegang_kartu'];
            $nomorkartu = $invoiceNote['nomor_kartu'];

            if (abs($this->totalAmount) > $cash) {
                $remainingAmountTransfer = $this->totalAmount + $cash;
                $note = [
                    'type' => $type,
                    'nama_bank' => $bank,
                    'nama_pemegang_kartu' => $pemegangkartu,
                    'cash' => -$cash,
                    'transfer' => $remainingAmountTransfer,
                    'nomor_kartu' => $nomorkartu,
                ];

                $invoiceData['note'] = json_encode($note);
            } else {
                $note = [
                    'type' => $type,
                    'nama_bank' => $bank,
                    'nama_pemegang_kartu' => $pemegangkartu,
                    'cash' => $this->totalAmount,
                    'transfer' => 0,
                    'nomor_kartu' => $nomorkartu,
                ];

                $invoiceData['note'] = json_encode($note);
            }
        }
        Invoice::create($invoiceData);
        $newInvoice = Invoice::where('no', $invoicereturn)->first();
        $cashier = User::where('id', $newInvoice->id_user)->first();
        $this->invoice = $newInvoice;
        $this->cashier = $cashier;
        $user = Auth::user();
        $wh = Warehouse::where('code', $user->whs_code)->first();
        $id_pricelist = $wh->id_pricelist;
        $totalSubtotal = 0;
        $totalDiscount = 0;
        $totalQty = 0;

        foreach ($this->itemReturnDetails as $itemz) {
            $items = DetailInvoice::where('invoice', $itemz['invoice'])->first();
            $item = ItemPrice::where('id_pricelist', $id_pricelist)->where('item_code', $itemz['code'])->first();
            $nprice = $item->price;
            DetailInvoice::insert([
                'code' => $itemz['code'],
                'barcode' => $itemz['barcode'],
                'name' => $itemz['name'],
                'price' => $itemz['price'],
                'qty' => -$itemz['qty'],
                'nprice' => $nprice,
                'disc' => $itemz['disc'],
                'invoice' => $newInvoice->no,
                'id_member' => isset($itemz['id_member']) && !is_null($itemz['id_member']) ? $itemz['id_member'] : null,
                'id_user' => $cashier->id,
                'id_sales' => $items->id_sales,
                'total_price' => -$itemz['qty'] * $itemz['price'],
                'created_at' => $newInvoice->created_at,
                'status' => 1,
            ]);
            // Calculate and add subtotal for each item
            $dataReturn = DetailInvoice::where('invoice', $newInvoice->no)
                ->where('code', $itemz['code'])
                ->first();
            if ($dataReturn->disc == '1') {
                $subtotal = $itemz['price'] * -$itemz['qty'];
            } else {
                $subtotal = $nprice * -$itemz['qty'];
            }
            $totalSubtotal += $subtotal;
        }
        $createdCartItems = [];
        foreach ($this->newItem as $input) {
            $items = DetailInvoice::where('invoice', $datainvoiceexist->no)->first();
            $item = ItemPrice::where('id_pricelist', $id_pricelist)->where('item_code', $input['code'])->first();
            $selectitem = Item::where('code', $input['code'])->first();
            $barcode = $selectitem->barcode;
            $nprice = $item->price;
            $price = $input['price'];

            $disc = ($price != $nprice) ? 1 : 0;

            DetailInvoice::insert([
                'code' => $input['code'],
                'barcode' => $barcode,
                'name' => $input['name'],
                'price' => $input['price'],
                'nprice' => $nprice,
                'qty' => $input['qty'],
                'invoice' => $newInvoice->no,
                'id_member' => isset($items->id_member) && !is_null($items->id_member) ? $items->id_member : null,
                'id_user' => $cashier->id,
                'id_sales' => $items->id_sales,
                'total_price' => $input['price'] * $input['qty'],
                'created_at' => $newInvoice->created_at,
                'status' => 0,
                'disc' => $disc,

            ]);
            $cartData = DetailInvoice::where('code', $input['code'])
                ->where('invoice', $newInvoice->no)
                ->first();

            $createdCartItems[] = [
                'name' => $cartData->name,
                'price' => $cartData->price,
                'qty' => $cartData->qty,
                'discount' => $cartData->disc,

            ];

            // Calculate and add discount for each item
            $discount = ($nprice - $input['price']);
            $totalDiscount += $discount;

            // Calculate and add qty for each item
            $qty = $input['qty'] > 0 ? $input['qty'] : 0;
            $totalQty += $qty;

            $sales = $items->id_sales;
        }
        $newInvoice = Invoice::where('no', $invoicereturn)->first();
        $newInvoice->update([
            'disc_total' => $totalDiscount,
            'id_sales' => $sales,
            'total_qty' => $totalQty,
        ]);

        $this->storeitem = $createdCartItems;
        $user = Auth::user();
        $warehouse = Warehouse::where('code', $user->whs_code)->first();
        foreach ($this->newItem as $key => $input) {
            $item = Item::where('code', $input['code'])->where('inventory', 'Y')->first();
            if ($item) {
                $transData = [
                    'no_trans' => $newInvoice->no, //invoice
                    'whs_code' => $warehouse->code,
                    'item_code' => $input['code'],
                    'tipe' => '13',
                    'date' => Carbon::now(),
                    'qty' => -$input['qty'],
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                    'linenum' => $key, 
                ];
                ItemTrans::insert($transData);
            }
        }
        foreach ($this->itemReturnDetails as $key => $selectedItem) {
            $item = Item::where('code', $selectedItem['code'])->where('inventory', 'Y')->first();
            if ($item) {
                $transData = [
                    'no_trans' => $newInvoice->no, //invoice
                    'whs_code' => $warehouse->code,
                    'item_code' => $selectedItem['code'],
                    'tipe' => '14',
                    'date' => Carbon::now(),
                    'qty' => $selectedItem['qty'],
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                    'linenum' => $key, 
                ];
                ItemTrans::insert($transData);
            }
        }

        $this->selectedItems = [];
        $this->dispatch('syncreturn', $newInvoice->no);
        $this->print();
        $this->dispatch('closeModalReturn');
        $this->dispatch('clearSelectedAfterReturn', data: $this->selectedItems)->to(ReturnsaleTable::class);
        $this->alert('success', 'Return data created succesfully', [
            'position' => 'top-end',
            'timer' => 3000,
            'toast' => true,
            'timerProgressBar' => true,
        ]);
        $this->reset();
        $this->dispatch('SendEmailReturn', data: $newInvoice);
        Cart::where('id_user', auth()->user()->id)
            ->delete();
        $this->dispatch('Finish');
    }

    #[On('SendEmailReturn')]
    public function sendEmailReturn($data)
    {
        $user = Auth::user();
        $toko = Settings::where('wh_code', $user->whs_code)->first();
        $email = $toko->email_finance;
        Mail::to($email)->send(new MyTestMail($data, $toko));
    }

    #[On('Finish')]
    public function selesai()
    {
        sleep(4);
        return redirect()->route('welcome.returnsale');
    }

    #[On('syncreturn')]
    public function syncreturn($code)
    {
        $user = Auth::user();
        $setting = Settings::where('wh_code', $user->whs_code)->first();
        $url = $setting->url;
        $detailinvoicememo = DetailInvoice::where('invoice', $code)->where('status', 1)->get();
        $detailinvoicear = DetailInvoice::where('invoice', $code)->where('status', 0)->get();

        $invoice = Invoice::where('no', $code)->first();
        $date = date_create($invoice->date);
        $formattedDate = date_format($date, 'Y-m-d');
        $currentDate = Carbon::now()->format('Y-m-d');
        $getsales = DetailInvoice::where('invoice', $code)->first();
        $idsales = $getsales->id_sales;

        if ($invoice->payment === "Multi") {
            $note = json_decode($invoice['note'], true);
            $cash = $note['cash'];
            $card = $note['transfer'];
            $cashAccount = $setting->cashacc;
            $transferAccount = $setting->cardacc;
        } elseif ($invoice->payment === "Card") {
            $note = json_decode($invoice['note'], true);
            $cash = 0;
            $card = $note['transfer'];
            $cashAccount = '';
            $transferAccount = $setting->cardacc;
        } elseif ($invoice->payment === "Cash") {
            $cash = $invoice->must_paid;
            $card = 0;
            $cashAccount = $setting->cashacc;
            $transferAccount = '';
        } elseif ($invoice->payment === "Qris") {
            $cash = 0;
            $card = $invoice->must_paid;
            $cashAccount = '';
            $transferAccount = $setting->cardacc;
        } elseif ($invoice->payment === "") { //mzdihilangkan
            $cash = 0;
            $card = 0;
            $cashAccount = $setting->cashacc;
            $transferAccount = $setting->cardacc;
        }


        foreach ($detailinvoicememo as $data) {
            $syncItemsmemo[] =
                [
                    'ItemCode' => $data->code,
                    'Quantity' => ltrim($data->qty, '-'),
                    'UnitPrice' => $data->nprice,
                    'LineTotal' => ltrim($data->total_price, '-'),
                    'WhsCode' => $setting->wh_code,
                    'Cost1' => $setting->cost1,
                    'Cost2' => $setting->cost2,
                    'Cost3' => $setting->cost3,
                    'Cost4' => $setting->cost4,
                    'Cost5' => $setting->cost5
                    // 'WhsCode' => "RCSM",
                    // 'SBU' => "Galaxy",
                ];
        }
        foreach ($detailinvoicear as $data) {
            $syncItemsar[] =
                [
                    'ItemCode' => $data->code,
                    'Quantity' => $data->qty,
                    'UnitPrice' => $data->nprice,
                    'LineTotal' => $data->total_price,
                    'WhsCode' => $setting->wh_code,
                    'Cost1' => $setting->cost1,
                    'Cost2' => $setting->cost2,
                    'Cost3' => $setting->cost3,
                    'Cost4' => $setting->cost4,
                    'Cost5' => $setting->cost5                    // 'WhsCode' => "RCSM",
                    // 'SBU' => "Galaxy",
                ];
        }
        $commentcode = $user->whs_code . '/' . $code . '/' . $user->name;
        $datamemo = [
            "CardCode" => $invoice->cardcode,
            "CntctCode" => "0",
            "NumAtCard" => "0",
            "DocDate" => $formattedDate,
            "DocDueDate" => $formattedDate,
            "TaxDate" => $formattedDate,
            "SlpCode" => $idsales,
            "Comments" => $commentcode,
            "BPLId" => $setting->bpl_id,
            "DocType" => "C",
            "Lines" => $syncItemsmemo,
        ];

        if ($invoice->subtotal <= 0) { //mzditambahkan jika rs
            $data = [
                "CardCode" => $invoice->cardcode,
                "CntctCode" => "0",
                "NumAtCard" => "0",
                "DocDate" => $formattedDate,
                "DocDueDate" => $formattedDate,
                "TaxDate" => $formattedDate,
                "SlpCode" => $idsales,
                "Comments" => $commentcode,
                "BPLId" => $setting->bpl_id,
                "Lines" => $syncItemsar,
                "CreditMemo" => $datamemo,
            ];
        } else {
            $data = [
                "CardCode" => $invoice->cardcode,
                "CntctCode" => "0",
                "NumAtCard" => "0",
                "DocDate" => $formattedDate,
                "DocDueDate" => $formattedDate,
                "TaxDate" => $formattedDate,
                "SlpCode" => $idsales,
                "Comments" => $commentcode,
                "BPLId" => $setting->bpl_id,
                "CashAccount" => $cashAccount,
                "CashSum" => $cash,
                "TransferAccount" => $transferAccount,
                "TransferSum" => $card,
                "TransferDate" => $currentDate,
                "DocType" => "C",
                "Lines" => $syncItemsar,
                "CreditMemo" => $datamemo,
            ];
        }

        $response = Http::post($url . '/api/search', [
            "Select" => "\"Comments\"",
            "From" => "OINV",
            "Where" => "\"Comments\"='" . $commentcode . "' AND \"CANCELED\"='N' LIMIT 1",
        ]);

        $responseBody = $response->getBody()->getContents();
        $responseData = json_decode($responseBody, true);
        if ($responseData[0]['Comments'] == $commentcode) {
            $invoice = Invoice::where('no', $code)->first();
            $invoice->sync = 'Y';
            $invoice->save();
            $this->alert('info', 'Invoice already exists on SAP', [
                'position' => 'top-end',
                'timer' => 5000,
                'toast' => true,
                'timerProgressBar' => true,
            ]);
        } else {
            try {
                $user = Auth::user();
                $setting = Settings::where('wh_code', $user->whs_code)->first();
                $url = $setting->url;
                $client = new Client();
                $route = ($invoice->subtotal <= 0) ? '/api/addarexchange' : '/api/addarexchangepayment'; //mzdiubah jika rs

                $response = $client->post($url . $route, [
                    'headers' => [
                        'Content-Type' => 'application/json',
                    ],
                    'json' => $data,
                ]);


                $responseBody = $response->getBody()->getContents();
                $responseData = json_decode($responseBody, true);
                $errorCode = $responseData['ErrorCode'];
                if ($errorCode !== 0) {
                    $this->alert('warning', $responseData['Message'], [
                        'position' => 'top-end',
                        'timer' => 5000,
                        'toast' => true,
                        'timerProgressBar' => true,
                    ]);
                } else {
                    $invoice = Invoice::where('no', $code)->first();
                    $invoice->sync = 'Y';
                    $invoice->save();
                    $this->alert('success', $responseData['Message'], [
                        'position' => 'top-end',
                        'timer' => 5000,
                        'toast' => true,
                        'timerProgressBar' => true,
                    ]);
                    // $this->creditmemo($code, $commentcode, $datamemo);
                }
            } catch (\Exception $e) {
                $this->alert('error', 'No Internet Connection to Sync', [
                    'position' => 'top-end',
                    'timer' => 5000,
                    'toast' => true,
                    'timerProgressBar' => true,
                ]);
            }
        }
    }
    public function updatedCash()
    {
        $cashWithoutDots = str_replace('.', '', $this->cash);
        $cashFloat = (float) $cashWithoutDots;
        $this->transfer = $this->totalAmount - $cashFloat;
    }

    public function updatedPayment()
    {
        $paymentWithoutDots = str_replace('.', '', $this->payment);
        $paymentFloat = (float) $paymentWithoutDots;
        $this->change = $paymentFloat - $this->totalAmount;
    }
    public function storewithmoney()
    {

        $user = Auth::user();
        $setting = Settings::where('wh_code', $user->whs_code)->first();
        $whs = Warehouse::where('code', $setting->wh_code)->first();
        $pricelist = $whs->id_pricelist;
        $item = $this->itemReturnDetails;
        $paymentWithoutDots = str_replace('.', '', $this->payment);
        $paymentFloat = (float) $paymentWithoutDots;
        $invoice = $item[0]['invoice'];
        $datainvoiceexist = Invoice::where('no', $invoice)->first();
        $this->oldinvoice = $datainvoiceexist;
        $this->member = Member::where('code', $datainvoiceexist->id_member)->first();
        $this->sales = Sales::where('code', $datainvoiceexist->id_sales)->first();
        $pembayaran = $this->paymentOption;
        $totalAmount = $this->totalAmount;
        $payment = $paymentFloat;
        $change = $this->change;
        $huruf = 'RS';
        // Date
        $tanggal = Carbon::now()->isoFormat('YYMMDDHHmm');

        // Count invoices created today
        $countinvoice = DB::table('Luv2_invoice')
            ->where('id_user', $user->id)
            ->whereDate('created_at', Carbon::today())
            ->count();
        $countinvoice += 1;

        // set max 999 to count inv
        $countinvoice = min($countinvoice, 999);
        // set default 3 digit count inv
        $countinvoice = str_pad($countinvoice, 3, '0', STR_PAD_LEFT);
        $code = $user->code;
        $invoicereturn = $huruf . $code . $tanggal . $countinvoice;
        if ($this->paymentOption == 'card' && $this->paymentOption == 'multi') {
            $this->validate();
        }
        $maxId = Invoice::max('id');
        $invoiceData = [
            'id' => $maxId + 1,
            'id_user' => $user->id,
            'id_member' => $datainvoiceexist->id_member,
            'no' => $invoicereturn,
            'payment' => ucwords($pembayaran),
            'paid' => ($pembayaran === 'card' || $pembayaran === 'multi') ? $totalAmount : ($pembayaran === 'qris' ? $totalAmount : $payment),
            'must_paid' => abs($this->totalAmount),
            'change' => $change,
            'date' => Carbon::now(),
            'cardcode' => $datainvoiceexist->cardcode,
            'no_inv' => $datainvoiceexist->no,
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),

        ];
        if ($pembayaran === 'multi' || $pembayaran === 'card') {
            $cashWithoutDots = str_replace('.', '', $this->cash);
            $cashFloat = (float) $cashWithoutDots;
            $note = [
                'type' => $this->type ?? 'Credit',
                'nama_bank' => $this->namaBank,
                'nama_pemegang_kartu' => $this->namaPemegangKartu,
                'cash' => ($pembayaran === 'multi') ? $cashWithoutDots : null,
                'transfer' => ($pembayaran === 'multi') ? ($totalAmount - $cashFloat) : ($pembayaran === 'card' ? $totalAmount : null), // Set 'transfer' based on the condition
                'nomor_kartu' => $this->nomorKartu,
            ];

            $invoiceData['note'] = json_encode($note);
        }
        if (session()->has('Promo-Voucher-QTY' . auth()->user()->id) || session()->has('Promo-Voucher-ValueFulfil' . auth()->user()->id)) {
            $this->randomVoc();
            $now = Carbon::now();
            $formattedDateTime = $now->format('ymdHis');
            $promo = DB::table('Luv2_promo')
                ->where('deleted', 'N')
                ->where(function ($query) {
                    $query->where('no', session('Promo-Voucher-QTY' . auth()->user()->id))
                        ->orWhere('no', session('Promo-Voucher-Value' . auth()->user()->id));
                })
                ->first();
            // Insert the record into the 'Luv2_promo' table
            DB::table('Luv2_promo')->insert([
                'no' => $formattedDateTime,
                'id_pricelist' => $pricelist,
                'name' => 'Voucher Cashback ( ' . $promo->no . ' )',
                'from_date' => $promo->voucher_from_date,
                'to_date' => $promo->voucher_to_date,
                'id_company' => $setting->id_company,
                'date' => $now,
                'voucher_from_date' => $promo->voucher_from_date,
                'voucher_to_date' => $promo->voucher_to_date,
                'voucher' => $promo->voucher,
                'invoice' => $invoiceData['no'],
                'sync' => 'N',
                'tipe' => 6,
            ]);
            DB::table('Luv2_promo_voucher')->insert([
                'no' => $formattedDateTime,
                'id_company' => $setting->id_company,
                'voucher' => $this->random,
                'value' => $promo->voucher,
            ]);
        }
        Invoice::insert($invoiceData);
        $newInvoice = Invoice::where('no', $invoiceData['no'])->first();
        $cashier = User::where('id', $newInvoice->id_user)->first();
        $this->invoice = $newInvoice;
        $this->cashier = $cashier;
        $user = Auth::user();
        $wh = Warehouse::where('code', $user->whs_code)->first();
        $id_pricelist = $wh->id_pricelist;
        $totalSubtotal = 0;
        $totalDiscount = 0;
        $totalQty = 0;

        foreach ($this->itemReturnDetails as $itemz) {
            $items = DetailInvoice::where('invoice', $itemz['invoice'])->first();
            $item = ItemPrice::where('id_pricelist', $id_pricelist)->where('item_code', $itemz['code'])->first();
            $nprice = $item->price;
            DetailInvoice::insert([
                'code' => $itemz['code'],
                'barcode' => $itemz['barcode'],
                'name' => $itemz['name'],
                'price' => $itemz['price'],
                'qty' => -$itemz['qty'],
                'nprice' => $nprice,
                'disc' => $itemz['disc'],
                'invoice' => $newInvoice->no,
                'id_member' => isset($itemz['id_member']) && !is_null($itemz['id_member']) ? $itemz['id_member'] : null,
                'id_user' => $cashier->id,
                'id_sales' => $items->id_sales,
                'total_price' => -$itemz['qty'] * $itemz['price'],
                'created_at' => $newInvoice->created_at,
                'updated_at' => $newInvoice->created_at,
                'status' => 1,
            ]);
            // Calculate and add subtotal for each item
            $dataReturn = DetailInvoice::where('invoice', $newInvoice->no)
                ->where('code', $itemz['code'])
                ->first();
            if ($dataReturn->disc == '1') {
                $subtotal = $itemz['price'] * -$itemz['qty'];
            } else {
                $subtotal = $nprice * -$itemz['qty'];
            }
            $totalSubtotal += $subtotal;
        }
        $createdCartItems = [];
        foreach ($this->newItem as $input) {
            $items = DetailInvoice::where('invoice', $datainvoiceexist->no)->first();
            $item = ItemPrice::where('id_pricelist', $id_pricelist)->where('item_code', $input['code'])->first();
            $selectitem = Item::where('code', $input['code'])->first();
            $barcode = $selectitem->barcode;
            $nprice = $item->price;
            $price = $input['price'];

            $disc = ($price != $nprice) ? 1 : 0;

            DetailInvoice::insert([
                'code' => $input['code'],
                'barcode' => $barcode,
                'name' => $input['name'],
                'price' => $input['price'],
                'qty' => $input['qty'],
                'nprice' => $nprice,
                'invoice' => $newInvoice->no,
                'id_member' => isset($items->id_member) && !is_null($items->id_member) ? $items->id_member : null,
                'id_user' => $cashier->id,
                'id_sales' => $items->id_sales,
                'total_price' => $input['price'] * $input['qty'],
                'created_at' => $newInvoice->created_at,
                'updated_at' => $newInvoice->created_at,
                'status' => 0,
                'disc' => $disc, // Include 'disc' in the insert statement

            ]);
            $cartData = DetailInvoice::where('code', $input['code'])
                ->where('invoice', $newInvoice->no)
                ->first();
            $createdCartItems[] = [
                'name' => $cartData->name,
                'price' => $cartData->price,
                'nprice' => $cartData->nprice,
                'qty' => $cartData->qty,
                'disc' => $cartData->disc,
            ];
            // Calculate and add subtotal for each item
            $subtotal = $nprice * $input['qty'];
            $totalSubtotal += $subtotal;

            // Calculate and add discount for each item
            $discount = ($nprice - $input['price']);
            $totalDiscount += $discount;

            // Calculate and add qty for each item
            $qty = $input['qty'] > 0 ? $input['qty'] : 0;
            $totalQty += $qty;

            $sales = $items->id_sales;
        }
        $newInvoice = Invoice::where('no', $invoicereturn)->first();
        if ($this->isCashback) {
            $invoice->update([
                'cashback' => $this->voucherCashback->voucher_code,
                'subtotal' => $totalSubtotal,
                'disc_total' => $totalDiscount,
                'id_sales' => $sales,
                'total_qty' => $totalQty,
            ]);

            //update voucher terpakai
            DB::table('Luv2_promo_voucher')
                ->where('voucher', $this->voucherCashback->voucher_code)
                ->update([
                    'used' => 'Y',
                ]);
        } else {
            $newInvoice->update([
                'subtotal' => $totalSubtotal,
                'disc_total' => $totalDiscount,
                'id_sales' => $sales,
                'total_qty' => $totalQty,
            ]);
        }


        $this->storeitem = $createdCartItems;
        $this->noreturn = $newInvoice->no;
        $user = Auth::user();
        $warehouse = Warehouse::where('code', $user->whs_code)->first();
        foreach ($this->inputs as $key => $input) {
            $item = Item::where('code', $input['code'])->where('inventory', 'Y')->first();
            if ($item) {
                $transData = [
                    'no_trans' => $newInvoice->no, //invoice
                    'whs_code' => $warehouse->code,
                    'item_code' => $input['itemCode'],
                    'tipe' => '13',
                    'date' => Carbon::now(),
                    'qty' => -$input['itemQty'],
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                    'linenum' => $key, 
                ];
                ItemTrans::insert($transData);
            }
        }
        foreach ($this->itemReturnDetails as $key => $selectedItem) {
            $item = Item::where('code', $selectedItem['code'])->where('inventory', 'Y')->first();
            if ($item) {
                $transData = [
                    'no_trans' => $newInvoice->no, //invoice
                    'whs_code' => $warehouse->code,
                    'item_code' => $selectedItem['code'],
                    'tipe' => '14',
                    'date' => Carbon::now(),
                    'qty' => $selectedItem['qty'],
                    'created_at' => Carbon::now(),
                    'updated_at' => Carbon::now(),
                    'linenum' => $key, 

                ];
                ItemTrans::insert($transData);
            }
        }
        $this->selectedItems = [];
        $this->printwithmoney();
        $this->dispatch('syncreturn', $newInvoice->no);
        $this->dispatch('closeModalReturn');
        $this->dispatch('clearSelectedAfterReturn', data: $this->selectedItems)->to(ReturnsaleTable::class);
        $this->alert('success', 'Return data created succesfully', [
            'position' => 'top-end',
            'timer' => 3000,
            'toast' => true,
            'timerProgressBar' => true,
        ]);
        $this->reset();
        if ($this->isCashback) {
            $this->dispatch('syncVoucherUsed', $this->voucherCashback->voucher);
        }
        $this->isCashback = false;
        $this->totalAmount = 0;
        $this->voucherCashback = [];
        Cart::where('id_user', auth()->user()->id)
            ->delete();
        $this->dispatch('Finish');
    }

    public function print()
    {
        $user = Auth::user();
        $setting = Settings::where('wh_code', $user->whs_code)->first();
        $printer = $setting->printer_name;
        try {
            $profile = CapabilityProfile::load("default");
            $connector = new WindowsPrintConnector($printer);
            $printer = new Printer($connector, $profile);

            $cashier = Auth::user()->name;
            // Set the font size
            $printer->setTextSize(1, 1);

            // $cashier = $this->cashier;
            $now = Carbon::now();

            // Format the current date and time
            $formattedDateTime = $now->format('d/m/Y H:i:s');

            // Set the justification
            $toko = $setting->wh_name;
            $address = $setting->address;
            $phone = "Telp : " . $setting->phone;
            $manager = "Cashier   : " . $cashier;
            $billNo = "Bill No   : " . $this->oldinvoice->no;
            $returNo = "Return No : " . $this->invoice->no;
            $date = "Date      : " . $formattedDateTime;
            if (!isset($this->sales->position) || $this->sales->position === '') {
                $handledBy = "Handled by : " . $this->sales->name;
            } else {
                $handledBy = "Handled by : " . $this->sales->position;
            }
            // Define your item list (replace this with your actual item data)
            $itemsreturn = [];

            foreach ($this->itemReturnDetails as $cartItem) {
                $name = str_pad(substr($cartItem['name'], 0, 15), 15); // Truncate or pad to 15 characters
                $itemsreturn[] = [
                    'name' => $name,
                    'qty' => $cartItem['qty'],
                    'price' => $cartItem['price'],
                ];
            }

            $items = [];

            foreach ($this->storeitem as $cartItem) {
                $name = str_pad(substr($cartItem['name'], 0, 15), 15); // Truncate or pad to 15 characters
                $items[] = [
                    'name' => $name,
                    'qty' => $cartItem['qty'],
                    'price' => $cartItem['price'],

                ];
            }

            $subTotalreturn = array_reduce($itemsreturn, function ($carry, $item) {
                return $carry + $item['price'] * $item['qty'];
            }, 0);

            $subTotalitems = array_reduce($items, function ($carry, $item) {
                return $carry + $item['price'] * $item['qty'];
            }, 0);

            // Start the receipt
            $printer->setJustification(Printer::JUSTIFY_CENTER);
            $printer->text("$toko\n$phone\n$address\n");
            $printer->text("---------------------------------------\n");
            $printer->setJustification(0);
            $printer->text("$manager\n$billNo\n$returNo\n$date\n");
            $printer->text("---------------------------------------\n");

            $printer->setJustification(Printer::JUSTIFY_CENTER);
            $printer->text(" *ITEM RETURN* \n");
            $printer->setJustification(0);

            // Print the table
            $printer->setJustification(Printer::JUSTIFY_LEFT);
            $printer->text("Item               Qty        Price\n");
            $printer->text("---------------------------------------\n");

            foreach ($itemsreturn as $item) {
                $printer->text(sprintf(
                    "%-15s %5d   %12s\n",
                    $item['name'],
                    $item['qty'],
                    number_format($item['price'] * $item['qty'], 2)
                ));
            }

            // Print totals

            $printer->setJustification(0);
            $padding = 14; // Number of spaces before the text
            $printer->text("---------------------------------------\n");
            $subTotal = "SubTotal  : " . number_format($subTotalreturn, 2);


            // Add padding before the text to ensure it starts at character 12
            $rightAlignedSubtotal = str_repeat(' ', $padding) . $subTotal;
            $printer->text("$rightAlignedSubtotal\n");
            $printer->text("---------------------------------------\n");

            $printer->setJustification(Printer::JUSTIFY_CENTER);
            $printer->text(" *ITEMS* \n");
            $printer->setJustification(0);

            // Print the table
            $printer->setJustification(Printer::JUSTIFY_LEFT);
            $printer->text("Item               Qty        Price\n");
            $printer->text("---------------------------------------\n");

            foreach ($items as $item) {
                $printer->text(sprintf(
                    "%-15s %5d   %12s\n",
                    $item['name'],
                    $item['qty'],
                    number_format($item['price'] * $item['qty'], 2)
                ));
            }

            // Print totals

            $printer->setJustification(0);
            $padding = 14; // Number of spaces before the text
            $printer->text("---------------------------------------\n");
            $subTotals = "SubTotal  : " . number_format($subTotalitems, 2);

            // Add padding before the text to ensure it starts at character 12
            $rightAlignedSubtotal = str_repeat(' ', $padding) . $subTotals;
            $printer->text("$rightAlignedSubtotal\n");
            $printer->text("---------------------------------------\n");

            // Handled by
            $printer->text("---------------------------------------\n");
            $printer->text("$handledBy\n");

            // Thank you message
            $printer->setJustification(Printer::JUSTIFY_CENTER);
            $printer->text("---------------------------------------\n");
            $footer = $setting->receipt_footer;
            $lines = explode('\n', $footer);

            foreach ($lines as $line) {
                $printer->text($line . "\n");
            }

            $printer->text("THANK YOU\n\n\n\n"); // Send a form feed character

            $printer->text("( _ _ _ _ _ _ _ _ _ _ _ )");

            $printer->feed(2); // Adjust the number of lines as needed

            // Cut the receipt
            $printer->cut();

            // Close the printer
            $printer->close();
        } catch (Exception $e) {
            // Handle the printing error here, you can log the error or display a message
            $this->dispatch('printernotfound');
        }
    }

    public function printwithmoney()
    {
        $iteminvoice = Invoice::where('no', $this->noreturn)->with('detailInvoices')->first();
        $user = Auth::user();
        $setting = Settings::where('wh_code', $user->whs_code)->first();
        $printer = $setting->printer_name;
        try {
            $profile = CapabilityProfile::load("default");
            $connector = new WindowsPrintConnector($printer);
            $printer = new Printer($connector, $profile);

            $cashier = Auth::user()->name;
            // Set the font size
            $printer->setTextSize(1, 1);

            // $cashier = $this->cashier;
            $now = Carbon::now();

            // Format the current date and time
            $formattedDateTime = $now->format('d/m/Y H:i:s');

            // Set the justification
            $toko = $setting->wh_name;
            $address = $setting->address;
            $phone = "Telp : " . $setting->phone;
            $manager = "Cashier   : " . $cashier;
            $billNo = "Bill No   : " . $this->oldinvoice->no;
            $returNo = "Return No : " . $this->invoice->no;
            $date = "Date      : " . $formattedDateTime;
            if (!isset($this->sales->position) || $this->sales->position === '') {
                $handledBy = "Handled by : " . $this->sales->name;
            } else {
                $handledBy = "Handled by : " . $this->sales->position;
            }
            // Define your item list (replace this with your actual item data)
            if ($this->invoice->payment === "Multi") {
                $note = json_decode($this->invoice['note'], true);
                // Check if the 'cash' key exists in the decoded note data
                $cash = $note['cash'];
                $card = $note['transfer'];
                $change = 0;
            }
            if ($this->invoice->payment === "Card") {
                $note = json_decode($this->invoice['note'], true);
                // Check if the 'cash' key exists in the decoded note data
                $cash = 0;
                $card = $note['transfer'];
                $change = $this->invoice->change;
            }
            if ($this->invoice->payment === "Cash") {
                $cash = $this->invoice->paid;
                $card = 0;
                $change = $this->invoice->change;
            }
            if ($this->invoice->payment === "Qris") {
                $cash = 0;
                $card = $this->invoice->must_paid;
                $change = 0;
            }
            $itemsreturn = [];

            foreach ($this->itemReturnDetails as $cartItem) {
                $name = str_pad(substr($cartItem['name'], 0, 15), 15); // Truncate or pad to 15 characters
                $itemsreturn[] = [
                    'name' => $name,
                    'qty' => abs($cartItem['qty']),
                    'price' => $cartItem['price'],
                ];
            }

            $items = [];

            foreach ($iteminvoice->detailInvoices as $cartItem) {
                if ($cartItem['qty'] >= 0) {
                    $name = str_pad(substr($cartItem['name'], 0, 15), 15); // Truncate or pad to 15 characters
                    $items[] = [
                        'name' => $name,
                        'qty' => abs($cartItem['qty']),
                        'price' => $cartItem['price'],
                    ];
                }
            }

            $subTotalreturn = array_reduce($itemsreturn, function ($carry, $item) {
                return $carry + $item['price'] * $item['qty'];
            }, 0);

            $subTotalitems = array_reduce($items, function ($carry, $item) {
                return $carry + $item['price'] * $item['qty'];
            }, 0);

            $grandTotal = $subTotalitems - $subTotalreturn;
            // Start the receipt
            $printer->setJustification(Printer::JUSTIFY_CENTER);
            $printer->text("$toko\n$phone\n$address\n");
            $printer->text("---------------------------------------\n");
            $printer->setJustification(0);
            $printer->text("$manager\n$billNo\n$returNo\n$date\n");
            $printer->text("---------------------------------------\n");

            $printer->setJustification(Printer::JUSTIFY_CENTER);
            $printer->text(" *ITEM RETURN* \n");
            $printer->setJustification(0);

            // Print the table
            $printer->setJustification(Printer::JUSTIFY_LEFT);
            $printer->text("Item               Qty        Price\n");
            $printer->text("---------------------------------------\n");

            foreach ($itemsreturn as $item) {
                $printer->text(sprintf(
                    "%-15s %5d   %12s\n",
                    $item['name'],
                    $item['qty'],
                    number_format($item['price'] * $item['qty'], 2)
                ));
            }

            // Print Information card
            if ($this->invoice->payment === "Card" || $this->invoice->payment === "Multi") {
                $note = json_decode($this->invoice['note'], true);
                $printer->text("---------------------------------------\n");
                $nocard = "Number     : " . $note['nomor_kartu'];
                $name = "Name       : " . $note['nama_pemegang_kartu'];
                $printer->text("$nocard\n");
                $printer->text("$name\n");
            }
            $printer->setJustification(0);
            $padding = 14; // Number of spaces before the text
            $printer->text("---------------------------------------\n");
            $subTotal = "SubTotal  : " . number_format($subTotalreturn, 2);


            // Add padding before the text to ensure it starts at character 12
            $rightAlignedSubtotal = str_repeat(' ', $padding) . $subTotal;
            $printer->text("$rightAlignedSubtotal\n");
            $printer->text("---------------------------------------\n");

            $printer->setJustification(Printer::JUSTIFY_CENTER);
            $printer->text(" *ITEMS* \n");
            $printer->setJustification(0);

            // Print the table
            $printer->setJustification(Printer::JUSTIFY_LEFT);
            $printer->text("Item               Qty        Price\n");
            $printer->text("---------------------------------------\n");

            foreach ($items as $item) {
                $printer->text(sprintf(
                    "%-15s %5d   %12s\n",
                    $item['name'],
                    $item['qty'],
                    number_format($item['price'] * $item['qty'], 2)
                ));
            }

            // Print totals

            $printer->setJustification(0);
            $padding = 14; // Number of spaces before the text
            $printer->text("---------------------------------------\n");
            $subTotals = "SubTotal  : " . number_format($subTotalitems, 2);
            $grandTotal = "GrandTotal: " . number_format($grandTotal, 2);

            // Add padding before the text to ensure it starts at character 12
            $rightAlignedSubtotal = str_repeat(' ', $padding) . $subTotals;
            $rightAlignedGrandTotal = str_repeat(' ', $padding) . $grandTotal;
            $printer->text("$rightAlignedSubtotal\n");
            $printer->text("$rightAlignedGrandTotal\n");
            $changeValue = $this->invoice->change > 0 ? $this->invoice->change : 0;
            $cash = "Cash      : " . number_format($cash, 2);
            $card = "Card      : " . number_format($card, 2);
            $change = "Change    : " . number_format($changeValue, 2);
            // Add padding before the text to ensure it starts at character 12
            $rightAlignedCash = str_repeat(' ', $padding) . $cash;
            $rightAlignedCard = str_repeat(' ', $padding) . $card;
            $rightAlignedChange = str_repeat(' ', $padding) . $change;


            $printer->text("$rightAlignedCard\n");
            $printer->text("$rightAlignedCash\n");
            $printer->text("$rightAlignedChange\n");
            $printer->text("---------------------------------------\n");


            // Handled by
            $printer->text("---------------------------------------\n");
            $printer->text("$handledBy\n");

            // Thank you message
            $printer->setJustification(Printer::JUSTIFY_CENTER);
            $printer->text("---------------------------------------\n");
            $footer = $setting->receipt_footer;
            $lines = explode('\n', $footer);

            foreach ($lines as $line) {
                $printer->text($line . "\n");
            }

            $printer->text("THANK YOU\n\n\n\n"); // Send a form feed character

            $printer->text("( _ _ _ _ _ _ _ _ _ _ _ )");

            $printer->feed(2); // Adjust the number of lines as needed

            // Cut the receipt
            $printer->cut();

            // Close the printer
            $printer->close();
        } catch (Exception $e) {
            // dd($e);
            // Handle the printing error here, you can log the error or display a message
            $this->dispatch('printernotfound');
        }
    }

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

    public function applyVoucher()
    {
        $voucher = DB::table('Luv2_promo_voucher')->where('voucher', $this->searchvoucher)->first();
        if ($voucher) {
            $joinedVoucher = DB::table('Luv2_promo_voucher')
                ->join('Luv2_promo', 'Luv2_promo.no', '=', 'Luv2_promo_voucher.no')
                ->where('Luv2_promo_voucher.no', $voucher->no)
                ->where('Luv2_promo_voucher.voucher', $this->searchvoucher)
                ->select(
                    'Luv2_promo_voucher.voucher as voucher_code',
                    'Luv2_promo_voucher.value',
                    'Luv2_promo_voucher.used',
                    'Luv2_promo.*'
                )
                ->first();
            $this->voucherCashback = $joinedVoucher;
            if ($joinedVoucher) {
                $voucherToDate = Carbon::parse($joinedVoucher->voucher_to_date);
                if ($joinedVoucher->used == 'N') {
                    if ($voucherToDate->isPast()) {
                        $this->message = 'Voucher has expired!';
                    } else {
                        if (!$this->voucherApplied) {
                            $this->dispatch('updatetotalAmount', $joinedVoucher);
                        } else {
                            $this->message = 'You cant applied same voucher twice !';
                        }
                    }
                } else {
                    $this->message = 'Voucher is already used!';
                }
            } else {
                $this->message = 'Input a valid voucher !';
            }
        } else {
            $this->message = 'Input a valid voucher !';
        }
    }

    public function updatedsearchvoucher()
    {
        $this->voucherCashback = [];
        $this->message = '';
        $this->voucherApplied = false;
        $user = Auth::user();
        $carts = Cart::where('id_user', $user->id)->get();
        $this->totalAmount = $carts->sum('total_price');
    }

    #[On('updatetotalAmount')]
    public function updatedtotalAmount($data)
    {
        $cashWithoutDots = str_replace('.', '', $this->cash);
        $cashFloat = (float) $cashWithoutDots;
        $vouchervalue = (float) $data['value'];
        $this->totalAmount = $this->totalAmount - $vouchervalue;
        $this->transfer = $this->totalAmount - $cashFloat;
        $this->isCashback = true;
        $this->voucherApplied = true;
    }
}
