<?php

namespace App\Http\Controllers\User;

use Carbon\Carbon;
use App\Models\User;
use App\Models\Pages;
use App\Jobs\MailSend;
use App\Models\Holiday;
use App\Models\Setting;
use App\Models\AddSpace;
use App\Models\Apptitle;
use App\Models\Currency;
use App\Models\Packages;
use Stripe\PaymentIntent;
use App\Models\Footertext;
use App\Models\Seosetting;
use Jenssegers\Agent\Agent;
use App\Models\Announcement;
use Illuminate\Http\Request;
use Stripe\Checkout\Session;
use App\Models\RefundComment;
use App\Models\AllTransactions;
use Torann\GeoIP\Facades\GeoIP;
use App\Models\CustomerPackages;
use App\Models\EmployeeActivity;
use App\Models\SocialAuthSetting;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\Customer;
use Illuminate\Support\Facades\Auth;
use Srmklive\PayPal\Services\PayPal;
use Illuminate\Support\Facades\Validator;
use App\Notifications\PaidTicketNotifications;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Models\Role;

class PaymentController extends Controller
{

    public function index()
    {
        // if (setting('paidTicketsEnable') == 'on' && setting('paidTicketType') == 'perPackage') {

        // $packages = Packages::all();
        // $data['packages'] = $packages;

        $title = Apptitle::first();
        $data['title'] = $title;

        $footertext = Footertext::first();
        $data['footertext'] = $footertext;

        $seopage = Seosetting::first();
        $data['seopage'] = $seopage;

        $socialAuthSettings = SocialAuthSetting::first();
        $data['socialAuthSettings'] = $socialAuthSettings;

        $post = Pages::all();
        $data['page'] = $post;

        $now = now();
        $announcement = Announcement::whereDate('enddate', '>=', $now->toDateString())->whereDate('startdate', '<=', $now->toDateString())->get();
        $data['announcement'] = $announcement;

        $announcements = Announcement::whereNotNull('announcementday')->get();
        $data['announcements'] = $announcements;

        // $holidays = Holiday::whereDate('startdate', '<=', $now->toDateString())->whereDate('enddate', '>=', $now->toDateString())->get();
        // $data['holidays'] =  $holidays;

        $now = now();
        $currentYear = $now->year;
        $activeHolidays = Holiday::where('status', 1)->get();


        $data['holidays'] = $activeHolidays->filter(function ($holiday) use ($now, $currentYear) {
            $holidayStart = Carbon::parse($holiday->startdate);
            $holidayEnd = Carbon::parse($holiday->enddate);
            if ($holiday->is_fixed) {
                return $holidayStart->month === $now->month && $holidayStart->day === $now->day;
            }
            return $holidayStart->isSameDay($now);
        });


        return $data;

        // abort(404);
    }


    public function transactions()
    {

        $data['addspace'] = AddSpace::where('status', 1)->get();
        $now = now();
        $announcement = Announcement::whereDate('enddate', '>=', $now->toDateString())->whereDate('startdate', '<=', $now->toDateString())->get();
        $data['announcement'] = $announcement;

        $announcements = Announcement::whereNotNull('announcementday')->get();
        $data['announcements'] = $announcements;

        $now = now();
        $currentYear = $now->year;
        $activeHolidays = Holiday::where('status', 1)->get();


        $data['holidays'] = $activeHolidays->filter(function ($holiday) use ($now, $currentYear) {
            $holidayStart = Carbon::parse($holiday->startdate);
            $holidayEnd = Carbon::parse($holiday->enddate);
            if ($holiday->is_fixed) {
                return $holidayStart->month === $now->month && $holidayStart->day === $now->day;
            }
            return $holidayStart->isSameDay($now);
        });

        $customInvoices = AllTransactions::where('cust_id', Auth::guard('customer')->user()->id)->latest('updated_at');

        $searchTerm = $request['filter'] ?? null;
        $perPage    = $request['per_page'] ?? 15;
        $page       = $request['page'] ?? 1;

        if ($searchTerm) {
            $customInvoices->where(function ($query) use ($searchTerm) {
                $columns = Schema::getColumnListing('all_transactions');
                foreach ($columns as $column) {
                    $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                }
            });
        }

        $items = $customInvoices->paginate($perPage);

        $items->getCollection()->each(fn($trans) => $trans->encrypted_id = Crypt::encrypt($trans->id));

        $data['queryList'] = $items;

        $quotations = AllTransactions::where('cust_id', Auth::guard('customer')->user()->id)->whereIn('status', ['pending', 'cancelled'])->latest('created_at')->get();
        $data['quotations'] = $quotations;


        $code = Auth::guard('customer')->user() ? Auth::guard('customer')->user()->currency : 'USD';
        $currency = Currency::where('code', $code)->where('status', 1)->first();
        if (!$currency) {
            $currency = Currency::where('code', 'USD')->where('status', 1)->first();
        }
        $symbol = config('currencies.' . $currency->code);
        $data['symbol'] = $symbol;
        $data['usercurrency'] = $currency;

        $unviewedQuotations = $quotations->where('cust_viewed', '!=', 1)->where('status', 'pending');
        $data['unviewedQuotations'] = $unviewedQuotations;

        return $data;
    }

    public function quotations(Request $request)
    {
        $now = now();
        $announcement = Announcement::whereDate('enddate', '>=', $now->toDateString())->whereDate('startdate', '<=', $now->toDateString())->get();
        $data['announcement'] = $announcement;

        $announcements = Announcement::whereNotNull('announcementday')->get();
        $data['announcements'] = $announcements;

        $data['addspace'] = AddSpace::where('status', 1)->get();

        $now = now();
        $currentYear = $now->year;
        $activeHolidays = Holiday::where('status', 1)->get();


        $data['holidays'] = $activeHolidays->filter(function ($holiday) use ($now, $currentYear) {
            $holidayStart = Carbon::parse($holiday->startdate);
            $holidayEnd = Carbon::parse($holiday->enddate);
            if ($holiday->is_fixed) {
                return $holidayStart->month === $now->month && $holidayStart->day === $now->day;
            }
            return $holidayStart->isSameDay($now);
        });



        $code = Auth::guard('customer')->user() ? Auth::guard('customer')->user()->currency : 'USD';
        $currency = Currency::where('code', $code)->where('status', 1)->first();
        if (!$currency) {
            $currency = Currency::where('code', 'USD')->where('status', 1)->first();
        }
        $data['usercurrency'] = $currency;
        $data['currencyposition'] = $currency->position;
        $symbol = config('currencies.' . $currency->code);
        $data['symbol'] = $symbol;

        $customInvoices = AllTransactions::where('cust_id', Auth::guard('customer')->user()->id)->whereIn('status', ['pending', 'cancelled'])
            ->with(['customInvoiceElements', 'customer'])
            ->latest('updated_at');

        $searchTerm = $request['filter'] ?? null;
        $perPage    = $request['per_page'] ?? 15;
        $page       = $request['page'] ?? 1;

        if ($searchTerm) {
            $customInvoices->where(function ($query) use ($searchTerm) {
                $columns = Schema::getColumnListing('all_transactions');
                foreach ($columns as $column) {
                    $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                }
            });
        }

        $items = $customInvoices->paginate($perPage);

        $items->getCollection()->each(fn($trans) => $trans->encrypted_id = Crypt::encrypt($trans->id));

        $data['queryList'] = $items;


        $unviewedQuotations = $customInvoices->where('cust_viewed', '!=', 1)->where('status', 'pending');
        $data['unviewedQuotations'] = $unviewedQuotations;

        return $data;
    }

    public function customInvoice(Request $request)
    {

        $data['addspace'] = AddSpace::where('status', 1)->get();
        $now = now();
        $announcement = Announcement::whereDate('enddate', '>=', $now->toDateString())->whereDate('startdate', '<=', $now->toDateString())->get();
        $data['announcement'] = $announcement;

        $announcements = Announcement::whereNotNull('announcementday')->get();
        $data['announcements'] = $announcements;


        $now = now();
        $currentYear = $now->year;
        $activeHolidays = Holiday::where('status', 1)->get();


        $data['holidays'] = $activeHolidays->filter(function ($holiday) use ($now, $currentYear) {
            $holidayStart = Carbon::parse($holiday->startdate);
            $holidayEnd = Carbon::parse($holiday->enddate);
            if ($holiday->is_fixed) {
                return $holidayStart->month === $now->month && $holidayStart->day === $now->day;
            }
            return $holidayStart->isSameDay($now);
        });

        $quotations = AllTransactions::where('cust_id', Auth::guard('customer')->user()->id)->whereIn('status', ['pending', 'cancelled'])->latest('created_at')->get();
        $data['quotations'] = $quotations;

        $unviewedQuotations = $quotations->where('cust_viewed', '!=', 1)->where('status', 'pending');
        $data['unviewedQuotations'] = $unviewedQuotations;


        $customInvoices = AllTransactions::where('cust_id', Auth::guard('customer')->user()->id)->where('status', 'paid')
            ->with(['customInvoiceElements', 'customer'])
            ->latest('updated_at');

        $searchTerm = $request['filter'] ?? null;
        $perPage    = $request['per_page'] ?? 15;
        $page       = $request['page'] ?? 1;

        if ($searchTerm) {
            $customInvoices->where(function ($query) use ($searchTerm) {
                $columns = Schema::getColumnListing('all_transactions');
                foreach ($columns as $column) {
                    $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                }
            });
        }

        $items = $customInvoices->paginate($perPage);
        $items->getCollection()->each(fn($trans) => $trans->encrypted_id = Crypt::encrypt($trans->id));

        $data['queryList'] = $items;

        $code = Auth::guard('customer')->user() ? Auth::guard('customer')->user()->currency : 'USD';


        $currency = Currency::where('code', $code)->where('status', 1)->first();
        if (!$currency) {
            $currency = Currency::where('code', 'USD')->where('status', 1)->first();
        }
        $data['usercurrency'] = $currency;

        $symbol = config('currencies.' . $currency->code);
        $data['symbol'] = $symbol;

        $data['usercurrency'] = $currency;

        return $data;
    }

    public function getInvoiceDetails($id)
    {
        if (Auth::guard('customer')->user()) {


            $transaction = AllTransactions::where('id', decrypt($id))->with(['customInvoiceElements', 'allInvoices'])->first();
            $data['transaction'] = $transaction;

            $data['setting'] = [
                'date_format' => setting('date_format'),
                'time_format' => setting('time_format'),
                'invoiceCancelDays' => setting('invoiceCancelDays'),
                'autoInvoiceCancelEnable' => setting('autoInvoiceCancelEnable'),
            ];

            $data['customer'] = Customer::find($transaction->cust_id);

            $data['admin'] = Auth::user();

            // $user = User::with('usetting')->find(Auth::user()->id);
            // $role = Role::where('name', $user->getRoleNames()[0])->get();
            // foreach ($role as $roles) {
            //     $data['permissions'] = $roles->getPermissionNames();
            // }

            $currency = $transaction->currency;
            $data['symbol'] = config('currencies.' . $currency);
            $code = Auth::guard('customer')->user() ? Auth::guard('customer')->user()->currency : 'USD';


            $currency = Currency::where('code', $code)->where('status', 1)->first();
            if (!$currency) {
                $currency = Currency::where('code', 'USD')->where('status', 1)->first();
                $code = 'USD';
            }
            $data['usercurrency'] = $currency;

            $data['usersymbol'] = config('currencies.' . $code);

            if ($transaction->cust_id == Auth::guard('customer')->user()->id) {
                $transaction->cust_viewed = 1;
                $transaction->save();
                $data['transaction'] =  $transaction;

                return $data;
            }
        }
        abort(404);
    }

    public function customInvoicePay($id)
    {
        $transaction = AllTransactions::where('invoiceId', decrypt($id))->with(['customInvoiceElements', 'allInvoices'])->where('ticket_type', 'customInvoice')->first();
        if ($transaction) {
            $data['transaction'] =  $transaction;

            $now = now();
            $announcement = Announcement::whereDate('enddate', '>=', $now->toDateString())->whereDate('startdate', '<=', $now->toDateString())->get();
            $data['announcement'] = $announcement;

            $announcements = Announcement::whereNotNull('announcementday')->get();
            $data['announcements'] = $announcements;

            $now = now();
            $currentYear = $now->year;
            $activeHolidays = Holiday::where('status', 1)->get();

            $data['holidays'] = $activeHolidays->filter(function ($holiday) use ($now, $currentYear) {
                $holidayStart = Carbon::parse($holiday->startdate);
                $holidayEnd = Carbon::parse($holiday->enddate);
                if ($holiday->is_fixed) {
                    return $holidayStart->month === $now->month && $holidayStart->day === $now->day;
                }
                return $holidayStart->isSameDay($now);
            });


            $data['setting'] = [
                'date_format' => setting('date_format'),
                'time_format' => setting('time_format'),
                'enablePaypal' => setting('enablePaypal'),
                'enableStripe' => setting('enableStripe'),
            ];

            $currency = $transaction->currency;
            $data['symbol'] = config('currencies.' . $currency);

            $code = Auth::guard('customer')->user() ? Auth::guard('customer')->user()->currency : 'USD';

            $currency = Currency::where('code', $code)->where('status', 1)->first();
            if (!$currency) {
                $currency = Currency::where('code', 'USD')->where('status', 1)->first();
                $code = 'USD';
            }
            $data['usercurrency'] = $currency;

            $data['usersymbol'] = config('currencies.' . $code);

            return $data;
        }
        abort(404);
    }

    public function invoiceCheckout(Request $request)
    {

        $validator = Validator::make($request->all(), [
            'paymentMethod' => 'required',
        ]);

        if ($validator->passes()) {
            $invoiceDetails = AllTransactions::where('invoiceId', decrypt($request->invoiceId))->first();

            $amount = (float) preg_replace('/[^0-9.]/', '', getCurrencyPerTicket($invoiceDetails->amount));


            $custCurrency = Currency::where('code', Auth::guard('customer')->user()->currency)->where('status', 1)->first();
            if (!$custCurrency) {
                $custCurrency = Currency::where('code', 'USD')->where('status', 1)->first();
            }
        
            if ($request->paymentMethod == 'stripe') {
                if (setting('enableStripe') == 'on' && setting('stripeKey') != null && setting('stripeSecret') != null) {
                    \Stripe\Stripe::setApiKey(setting('stripeSecret'));

                    $success_url = 'detail/customer/invoicePayment/StripeSuccess' . '?&session_id={CHECKOUT_SESSION_ID}&invoiceDetails=' . $invoiceDetails->id;
                    $checkoutSession = \Stripe\Checkout\Session::create([
                        'payment_method_types' => ['card'],
                        'line_items' => [
                            [
                                'price_data' => [
                                    'currency' => $custCurrency->code,
                                    'unit_amount' => $amount * 100,
                                    'product_data' => [
                                        'name' => 'Ticket',
                                    ],
                                ],
                                'quantity' => 1,
                            ],
                        ],
                        'mode' => 'payment',
                        'success_url' => url($success_url),
                        'cancel_url' => url('detail/customer/invoicePayment/StripeError/' . encrypt($request->invoiceId)),   // Your cancel URL
                    ]);

                    return response()->json(['session_id' => $checkoutSession->url], 200);
                } else {
                    return response()->json(['error' => lang('Payment gateway is not enabled or Invalid payment key, Please contact administrator')],);
                }
            } elseif ($request->paymentMethod == 'paypal') {
                if (setting('enablePaypal') == 'on' && setting('paypalKey') != null && setting('paypalSecret') != null) {
                    $configPaypal = Setting::paypal();
                    $provider = new PayPal($configPaypal);

                    $paypalToken = $provider->getAccessToken();
                    $success_url = 'detail/customer/invoicePayment/PaypalSuccess?invoiceDetails=' . urlencode(json_encode($invoiceDetails->id));

                    $response = $provider->createOrder([
                        "intent" => "CAPTURE",
                        "application_context" => [
                            "return_url" => url($success_url),
                            "cancel_url" => url('detail/customer/invoicePayment/PaypalError/' . encrypt($request->invoiceId)),
                        ],
                        "purchase_units" => [
                            0 => [
                                "amount" => [
                                    "currency_code" => $custCurrency->code,
                                    "value" => "$amount"
                                ]
                            ]
                        ]
                    ]);

                    if (isset($response['id']) && $response['id'] != null && $response['status'] == 'CREATED') {
                        foreach ($response['links'] as $links) {
                            if ($links['rel'] == 'approve') {
                                return response()->json(['paypalLink' => $links['href']], 200);
                            }
                        }
                    } else {
                        return response()->json(['paypalError' => $response['error']['message'] ?? 'Something went wrong.'], 200);
                    }
                } else {
                    return response()->json(['error' => lang('Payment gateway is not enabled or Invalid payment key, Please contact administrator')],);
                }
            }
        }
        return response()->json(['error' => lang('Please select a payment gateway to continue.')]);
    }

    public function invoiceStripeSuccess(Request $request)
    {

        if (Auth::guard('customer')->user()) {

            \Stripe\Stripe::setApiKey(setting('stripeSecret'));

            $session_id = $request->session_id;
            $session = Session::retrieve($session_id);


            if ($session->payment_status == "paid" && $session->status == "complete") {
                $paymentIntent = PaymentIntent::retrieve($session->payment_intent);


                $paymentMethod = \Stripe\PaymentMethod::retrieve($paymentIntent->payment_method);

                $billilngAddress = $paymentMethod->billing_details->address;
                $city = $billilngAddress->city;
                $country = $billilngAddress->country;
                $postalCode = $billilngAddress->postal_code;
                $state = $billilngAddress->state;

                $transactionId = $paymentIntent->id;
                $currency = strtoupper($paymentIntent->currency);
                $symbol = config('currencies.' . $currency);

                $transaction = AllTransactions::find($request->invoiceDetails);


                $originalPrice = (float) preg_replace('/[^0-9.]/', '', getCurrencyPerTicket($transaction->amount));
                $transaction->currency = $currency;
                $transaction->customerAmount = $symbol . ' ' . $originalPrice;
                $transaction->transaction_id = $transactionId;
                $transaction->payment_method = 'Stripe';
                $transaction->payment_date = now();
                $transaction->status = 'paid';
                $transaction->city = $city;
                $transaction->state = $state;
                $transaction->country = $country;
                $transaction->postal_code = $postalCode;

                $transaction->save();

                foreach ($transaction->customInvoiceElements as $elements) {
                    $elements->customerPrice = getCurrencyPerTicket($elements->price);
                    $elements->save();
                }

                return redirect(url('customer/custom-invoice/' . encrypt($transaction->id)))->withHeaders([
                    'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
                    'Pragma' => 'no-cache',
                    'Expires' => 'Sat, 01 Jan 2000 00:00:00 GMT',
                ])->with('success', lang('Payment successfull.', 'alerts'));
            }
            return redirect(url('customer/'))->with('error', lang('There was an error. Please initiate payment after a while.', 'alerts'));
        }
    }

    public function invoicePaypalSuccess(Request $request)
    {

        $configPaypal = Setting::paypal();
        $provider = new PayPal($configPaypal);

        $provider->getAccessToken();

        $response = $provider->capturePaymentOrder($request['token']);


        if (isset($response['status']) && $response['status'] == 'COMPLETED' && $response['id'] != null) {

            $purchaseUnits = $response['purchase_units'][0];

            $capture =  $purchaseUnits['payments']['captures'][0];
            $transactionId = $capture['id'];
            $currency = $capture['amount']['currency_code'];
            $symbol = config('currencies.' . $currency);

            $address = $purchaseUnits['shipping']['address'];
            $state = $address['address_line_1'];
            $city = $address['admin_area_2'];
            $postalCode = $address['postal_code'];
            $country  = $address['country_code'];

            $transaction = AllTransactions::find($request->invoiceDetails);

            $originalPrice = (float) preg_replace('/[^0-9.]/', '', getCurrencyPerTicket($transaction->amount));
            $transaction->currency = $currency;
            $transaction->customerAmount = $symbol . ' ' . $originalPrice;
            $transaction->transaction_id = $transactionId;
            $transaction->payment_method = 'Paypal';
            $transaction->payment_date = now();
            $transaction->status = 'paid';
            $transaction->city = $city;
            $transaction->state = $state;
            $transaction->country = $country;
            $transaction->postal_code = $postalCode;
            $transaction->save();

            foreach ($transaction->customInvoiceElements as $elements) {
                $elements->customerPrice = getCurrencyPerTicket($elements->price);
                $elements->save();
            }

            return redirect(url('customer/custom-invoice/' . encrypt($transaction->id)))->with('success', lang('Payment successfull.', 'alerts'));
        }
    }

    public function invoiceStripeError(Request $request, $id)
    {
        $id = decrypt($id);
        $transaction = AllTransactions::where('invoiceId', decrypt($id))->where('ticket_type', 'customInvoice')->first();
        if ($transaction) {
            return redirect(url('customer/custom-invoice/pay/' . $id))->withHeaders([
                'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
                'Pragma' => 'no-cache',
                'Expires' => 'Sat, 01 Jan 2000 00:00:00 GMT',
            ])->with('error', lang('Cancelled Payment.', 'alerts'));
        }
        abort(404);
    }

    public function invoicePaypalError(Request $request, $id)
    {
        $id = decrypt($id);
        $transaction = AllTransactions::where('invoiceId', decrypt($id))->where('ticket_type', 'customInvoice')->first();
        if ($transaction) {

            return redirect(url('customer/custom-invoice/pay/' . $id))->withHeaders([
                'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
                'Pragma' => 'no-cache',
                'Expires' => 'Sat, 01 Jan 2000 00:00:00 GMT',
            ])->with('error', lang('Cancelled Payment.', 'alerts'));
        }
        abort(404);
    }



    public function refunds()
    {
        if (setting('enableRefund')) {


            $data['addspace'] = AddSpace::where('status', 1)->get();

            $now = now();
            $announcement = Announcement::whereDate('enddate', '>=', $now->toDateString())->whereDate('startdate', '<=', $now->toDateString())->get();
            $data['announcement'] = $announcement;

            $announcements = Announcement::whereNotNull('announcementday')->get();
            $data['announcements'] = $announcements;

            // $holidays = Holiday::whereDate('startdate', '<=', $now->toDateString())->whereDate('enddate', '>=', $now->toDateString())->get();
            // $data['holidays'] =  $holidays;

            $now = now();
            $currentYear = $now->year;
            $activeHolidays = Holiday::where('status', 1)->get();


            $data['holidays'] = $activeHolidays->filter(function ($holiday) use ($now, $currentYear) {
                $holidayStart = Carbon::parse($holiday->startdate);
                $holidayEnd = Carbon::parse($holiday->enddate);
                if ($holiday->is_fixed) {
                    return $holidayStart->month === $now->month && $holidayStart->day === $now->day;
                }
                return $holidayStart->isSameDay($now);
            });


            $refundDays = setting('refundDays');

            // Calculate the start date
            $startDate = Carbon::now()->subDays($refundDays);

            // for the user to select items for th refund
            $code = Auth::guard('customer')->user() ? Auth::guard('customer')->user()->currency : 'USD';
            $currency = Currency::where('code', $code)->where('status', 1)->first();
            if (!$currency) {
                $currency = Currency::where('code', 'USD')->where('status', 1)->first();
            }
            $symbol = config('currencies.' . $currency->code);
            $data['symbol'] = $symbol;


            $quotations = AllTransactions::where('cust_id', Auth::guard('customer')->user()->id)->whereIn('status', ['pending', 'cancelled'])->latest('created_at')->get();
            $data['quotations'] = $quotations;

            $unviewedQuotations = $quotations->where('cust_viewed', '!=', 1)->where('status', 'pending');
            $data['unviewedQuotations'] = $unviewedQuotations;

            $data['setting'] = ['date_format' => setting('date_format'), 'default_timezone' => setting('default_timezone'), 'enableRefund' => setting('enableRefund')];

            $refunds = AllTransactions::where('cust_id', Auth::guard('customer')->user()->id)
                ->whereIn('status', ['refunded', 'refundpending', 'refundRejected'])
                ->with('customInvoiceElements', 'customer')
                ->latest('updated_at');

            $searchTerm = $request['filter'] ?? null;
            $perPage = $request['per_page'] ?? 15;
            $page = $request['page'] ?? 1;

            if ($searchTerm) {
                $refunds->where(function ($query) use ($searchTerm) {
                    $columns = Schema::getColumnListing('all_transactions');
                    foreach ($columns as $column) {
                        $query->orWhere($column, 'LIKE', "%{$searchTerm}%");
                    }
                });
            }

            // Paginate the results
            $items = $refunds->paginate($perPage);

            // Encrypt each transaction's ID
            $items->getCollection()->each(function ($transaction) {
                $transaction->encrypted_id = Crypt::encrypt($transaction->id);
                return $transaction;
            });

            // Add the paginated items to the response data
            $data['queryList'] = $items;



            $data['usercurrency'] = $currency;

            $alltransactions = AllTransactions::where('cust_id', Auth::guard('customer')->user()->id)->whereNotIn('status', ['refunded', 'refundpending', 'refundRejected'])->whereIn('status', ['paid', 'completed'])->whereBetween('updated_at', [$startDate, Carbon::now()])->get();
            $data['RefundableItem'] = $alltransactions;

            return $data;
        }
        abort(404);
    }

    public function refundStatusView($id)
    {

        $now = now();
        $announcement = Announcement::whereDate('enddate', '>=', $now->toDateString())->whereDate('startdate', '<=', $now->toDateString())->get();
        $data['announcement'] = $announcement;

        $announcements = Announcement::whereNotNull('announcementday')->get();
        $data['announcements'] = $announcements;

        $now = now();
        $currentYear = $now->year;
        $activeHolidays = Holiday::where('status', 1)->get();

        $data['setting'] = ['date_format' => setting('date_format'),'time_format' => setting('time_format'), 'default_timezone' => setting('default_timezone')];

        $user = auth()->guard('customer')->user();
        $data['timezonedata'] = $user->timezone != "null" ? $user->timezone : setting('default_timezone');

        $data['holidays'] = $activeHolidays->filter(function ($holiday) use ($now, $currentYear) {
            $holidayStart = Carbon::parse($holiday->startdate);
            $holidayEnd = Carbon::parse($holiday->enddate);
            if ($holiday->is_fixed) {
                return $holidayStart->month === $now->month && $holidayStart->day === $now->day;
            }
            return $holidayStart->isSameDay($now);
        });

        $refundItem = AllTransactions::with('customer', 'refundComments')->where('id', decrypt($id))->whereIn('status', ['refunded', 'refundpending', 'refundRejected'])->where('cust_id', Auth::guard('customer')->user()->id)->first();
        if ($refundItem) {
            $data['refundItem'] = $refundItem;

            return $data;
        }
        abort(404);
    }

    public function refundPostComment(Request $request)
    {

        if (setting('enableRefund')) {
            $refundItem = AllTransactions::where('id', decrypt($request->data['id']))->first();
            if ($refundItem->status == 'refundpending') {
                $com = $request->data['commentReply'];
                $co = preg_replace('/^(<p><br><\\/p>)+|(<p><br><\\/p>)+$/', '', $com);
                $co = preg_replace('/(<div><br><\/div>)+/', '<br>', $co);
                $co = trim($co);
                $refundComent = RefundComment::create([
                    'cust_id' => Auth::guard('customer')->user()->id,
                    'refund_id' => decrypt($request->data['id']),
                    'comment' => $co,
                ]);
                // $ticketData = [
                //     'username' => $refundItem->customer->username,
                //     'invoice_id' => $refundItem->invoiceId,
                //     'refund_request_page_url' => url('/customer/refundView/' . encrypt($refundItem->id))
                // ];
                $mailUsers = collect();
                $users = User::where('status', '1')->get();
                $permissionName = 'Refund Access';

                $mailUsers = $users->filter(function ($user) use ($permissionName) {
                    // Check if the user has the specific permission
                    return $user->hasPermissionTo($permissionName);
                });

                foreach ($mailUsers as $userss) {
                    $mailData = [
                        'username' => $refundItem->customer->username,
                        'invoice_id' => $refundItem->invoiceId,
                        'refund_request_page_url' => url('/admin/payments/refund-view/' . encrypt($refundItem->id))
                    ];
                    dispatch((new MailSend($userss->email, 'employee_send_refund_comment_from_customer', $mailData)));
                }
                // dispatch((new MailSend($refundItem->customer->email, 'employee_send_refund_comment_from_customer', $ticketData)));

                return response()->json(['success' => true]);
            }
            return response()->json(['error' => true]);
        }
        abort(404);
    }

    public function requestRefund(Request $request)
    {
        if (setting('enableRefund') == 'on') {
            $refundDays = setting('refundDays');

            // Calculate the start date
            $startDate = Carbon::now()->subDays($refundDays);

            $item = AllTransactions::where('cust_id', Auth::guard('customer')->user()->id)->where('id', $request->refundItem)->whereNotIn('status', ['refunded', 'refundpending'])->whereIn('status', ['paid', 'completed'])->whereBetween('updated_at', [$startDate, Carbon::now()])->first();
            if ($item) {
                $this->validate($request, [
                    'reason' => ['required',  function ($attribute, $value, $fail) {
                        // Remove all HTML tags and decode entities like &nbsp;
                        $decodedValue = html_entity_decode(strip_tags($value));
    
                        // Replace non-breaking spaces (\u{A0}) with regular spaces
                        $normalizedValue = str_replace("\u{A0}", ' ', $decodedValue);
    
                        // Trim unwanted tags from the start and end
                        $normalizedValue = preg_replace('/^(<(p|div)><br><\/(p|div)>)+|(<(p|div)><br><\/(p|div)>)+$/', '', $normalizedValue);
                        // Trim spaces and check if the result is empty
                        if (trim($normalizedValue) === '') {
                            $fail('The reason must contain valid text, not just spaces or HTML.');
                        }
                    }]
                ]);

                $item->status = 'refundpending';
                $item->refundReason = $request->reason;
                $item->refundCreatedDate = now();
                $item->update();

                $mailUsers = collect();
                $users = User::where('status', '1')->get();
                $permissionName = 'Refund Access';

                $mailUsers = $users->filter(function ($user) use ($permissionName) {
                    // Check if the user has the specific permission
                    return $user->hasPermissionTo($permissionName);
                });

                foreach ($mailUsers as $userss) {
                    $mailData = [
                        'customer_name' => Auth::guard('customer')->user()->username,
                        'invoice_id' => $item->invoiceId,
                    ];

                    $userss->notify(new PaidTicketNotifications($item));

                    dispatch((new MailSend($userss->email, 'customer_raised_refund_mail_for_admin', $mailData)));
                }
                $ticketData = [
                    'username' => Auth::guard('customer')->user()->username,
                    'invoice_id' => $item->invoiceId,
                ];
                dispatch((new MailSend(Auth::guard('customer')->user()->email, 'customer_raised_refund', $ticketData)));

                return response()->json(['success' => "New Refund Request Raised Successfully"]);
            }
            return response()->json(['error' => 'notFound']);
        } else {
            return response()->json(['error' => 'refundoff']);
        }
    }
}
