<?php

namespace App\Http\Controllers\Admin;

use App\Models\User;
use App\Models\Order;
use App\Models\BonusClaimLog;
use App\Models\Newsletter;
use Illuminate\Http\Request;
use App\CentralLogics\Helpers;
use Illuminate\Support\Carbon;
use App\Models\BusinessSetting;
use Illuminate\Support\Facades\DB;
use App\Exports\CustomerListExport;
use App\Exports\CustomerOrderExport;
use App\Http\Controllers\Controller;
use App\Services\Courier\CustomerCourierPerformanceService;
use App\Services\Customer\CustomerCodRestrictionService;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Mail;
use Illuminate\Support\Facades\Schema;
use Maatwebsite\Excel\Facades\Excel;
use App\Exports\SubscriberListExport;

class CustomerController extends Controller
{
    private const ONGOING_ORDER_STATUSES = ['pending', 'accepted', 'confirmed', 'processing', 'handover', 'picked_up'];

    public function __construct()
    {
        DB::statement("SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));");
    }

    private function getUserStatusColumn(): ?string
    {
        if (Schema::hasColumn('users', 'status')) {
            return 'status';
        }

        if (Schema::hasColumn('users', 'is_active')) {
            return 'is_active';
        }

        return null;
    }

    private function applyUserStatusFilter($query, ?string $filter)
    {
        if (! in_array($filter, ['active', 'blocked'], true)) {
            return $query;
        }

        $statusColumn = $this->getUserStatusColumn();

        if (! $statusColumn) {
            if ($filter === 'blocked') {
                $query->whereRaw('1 = 0');
            }

            return $query;
        }

        return $query->where($statusColumn, $filter === 'active' ? 1 : 0);
    }

    private function hasOngoingOrders(int $customerId): bool
    {
        return Order::query()
            ->where('user_id', $customerId)
            ->where('is_guest', 0)
            ->whereIn('order_status', self::ONGOING_ORDER_STATUSES)
            ->exists();
    }

    private function hasOngoingTrips(int $customerId): bool
    {
        if (! rental_module_is_ready() || ! class_exists(\Modules\Rental\Entities\Trips::class)) {
            return false;
        }

        $tripModel = \Modules\Rental\Entities\Trips::class;
        $tripTable = (new $tripModel)->getTable();

        $query = $tripModel::query()->where('user_id', $customerId);

        if (Schema::hasColumn($tripTable, 'trip_status')) {
            $query->where(function ($tripQuery) use ($tripTable) {
                $tripQuery->whereIn($tripTable.'.trip_status', ['pending', 'confirmed', 'ongoing']);

                if (Schema::hasColumn($tripTable, 'payment_status')) {
                    $tripQuery->orWhere(function ($completedTripQuery) use ($tripTable) {
                        $completedTripQuery
                            ->where($tripTable.'.trip_status', 'completed')
                            ->where($tripTable.'.payment_status', 'unpaid');
                    });
                }
            });
        }

        return $query->exists();
    }

    public function customer_list(Request $request)
    {
        $zone_id=  $request->zone_id ?? null;
        $filter=  $request->filter ?? null;
        $order_wise=  $request->order_wise ?? null;
        $show_limit=  $request->show_limit ?? null;
        $key = [];
        if ($request->search) {
            $key = explode(' ', $request['search']);
        }

        $order_date_start = null;
        $order_date_end =null;

        $join_date_start =null;
        $join_date_end = null;

        if($request?->order_date){
            list($order_date_start, $order_date_end) = explode(' - ', $request?->order_date);
            $order_date_start = Carbon::createFromFormat('m/d/Y', $order_date_start)->startOfDay();
            $order_date_end = Carbon::createFromFormat('m/d/Y', $order_date_end)->endOfDay();
        }
        if($request?->join_date){
            list($join_date_start, $join_date_end) = explode(' - ', $request?->join_date);
            $join_date_start = Carbon::createFromFormat('m/d/Y', $join_date_start)->startOfDay();
            $join_date_end = Carbon::createFromFormat('m/d/Y', $join_date_end)->endOfDay();
        }




        $customers = User::when(count($key) > 0, function ($query) use ($key) {
            foreach ($key as $value) {
                $query->orWhere('f_name', 'like', "%{$value}%")
                    ->orWhere('l_name', 'like', "%{$value}%")
                    ->orWhere('email', 'like', "%{$value}%")
                    ->orWhere('phone', 'like', "%{$value}%");
            };
        })->withcount('orders')

        ->when(isset($request->join_date) , function ($query) use($join_date_start, $join_date_end) {
            $query->WhereBetween('created_at', [$join_date_start, $join_date_end]);
        })
        ->when(isset($request->order_date) , function ($query) use($order_date_start, $order_date_end) {
            $query->wherehas('orders',function ($query) use($order_date_start, $order_date_end){
                $query->WhereBetween('created_at', [$order_date_start, $order_date_end]);
            });
        })

        ->when(isset($zone_id) && is_numeric($zone_id) , function ($query) use($zone_id){
            $query->where('zone_id' ,$zone_id);
        })
        ->when(isset($filter) && in_array($filter, ['active', 'blocked'], true), function ($query) use ($filter) {
            $this->applyUserStatusFilter($query, $filter);
        })
        ->when(isset($filter) && $filter == 'new' , function ($query) {
            $query->whereDate('created_at', '>=', now()->subDays(30)->format('Y-m-d'));
        })
        ->when(isset($order_wise) && $order_wise == 'top' , function ($query) {
            $query->orderBy('orders_count', 'desc');
        })
        ->when(isset($order_wise) && $order_wise == 'least' , function ($query) {
            $query->orderBy('orders_count', 'asc');
        })
        ->when(isset($order_wise) && $order_wise == 'latest' , function ($query) {
            $query->latest();
        })
        ->when(isset($order_wise) && $order_wise == 'oldest' , function ($query) {
            $query->oldest();
        })

        ->when(isset($order_wise) && $order_wise == 'order_amount', function ($query) {
            $query->withSum('orders as total_order_amount', 'order_amount')
                ->orderByDesc('total_order_amount');
        })
        ->when(!$order_wise, function ($query) {
            $query->orderBy('orders_count', 'desc');
        });


        if(isset($show_limit) && $show_limit > 0 ){
            $customers= $customers->take($show_limit)->get();
            $perPage = config('default_pagination');
            $page =  $request?->page ?? 1;
            $offset = ($page - 1) * $perPage;
            $itemsForCurrentPage = $customers->slice($offset, $perPage);
            $customers = new \Illuminate\Pagination\LengthAwarePaginator(
                $itemsForCurrentPage,
                $customers->count(),
                $perPage,
                $page,
                ['path' => Paginator::resolveCurrentPath(), 'query' => request()->query()]
            );


        } else{
            $customers=$customers->paginate(config('default_pagination'));
        }


        return view('admin-views.customer.list', compact('customers'));
    }

    public function status(User $customer, Request $request)
    {
        if (! $this->getUserStatusColumn()) {
            Toastr::warning('Customer status control is unavailable for the current database schema.');
            return back();
        }

        $customer->status = $request->status;
        $customer->save();

        try {
            if ($request->status == 0) {
                $customer->tokens->each(function ($token, $key) {
                    $token->delete();
                });
                if (isset($customer->cm_firebase_token) && Helpers::getNotificationStatusData('customer','customer_account_block','push_notification_status') ) {
                    $data = [
                        'title' => translate('messages.suspended'),
                        'description' => translate('messages.your_account_has_been_blocked'),
                        'order_id' => '',
                        'image' => '',
                        'type' => 'block'
                    ];
                    Helpers::send_push_notif_to_device($customer->cm_firebase_token, $data);

                    DB::table('user_notifications')->insert([
                        'data' => json_encode($data),
                        'user_id' => $customer->id,
                        'created_at' => now(),
                        'updated_at' => now()
                    ]);
                }

                if ( config('mail.status') && Helpers::get_mail_status('suspend_mail_status_user') == '1' &&  Helpers::getNotificationStatusData('customer','customer_account_block','mail_status') )  {
                    Mail::to($customer?->getRawOriginal('email'))->send(new \App\Mail\UserStatus('suspended', $customer->f_name.' '.$customer->l_name));
                }

            } else{

                if(Helpers::getNotificationStatusData('customer','customer_account_unblock','push_notification_status')  && isset($customer->cm_firebase_token))
                {
                    $data = [
                        'title' => translate('messages.account_activation'),
                        'description' => translate('messages.your_account_has_been_activated'),
                        'order_id' => '',
                        'image' => '',
                        'type'=> 'unblock'
                    ];
                    Helpers::send_push_notif_to_device($customer->cm_firebase_token, $data);

                    DB::table('user_notifications')->insert([
                        'data'=> json_encode($data),
                        'user_id'=>$customer->id,
                        'created_at'=>now(),
                        'updated_at'=>now()
                    ]);
                }

                if ( config('mail.status') && Helpers::get_mail_status('unsuspend_mail_status_user')== '1' &&  Helpers::getNotificationStatusData('customer','customer_account_unblock','mail_status') ) {
                    Mail::to($customer?->getRawOriginal('email'))->send(new \App\Mail\UserStatus('unsuspended', $customer->f_name.' '.$customer->l_name));
                }
            }


        } catch (\Exception $e) {
            Log::warning('Customer status notification failed after status update.', [
                'customer_id' => $customer->id,
                'status' => (int) $request->status,
                'message' => $e->getMessage(),
            ]);
        }

        Toastr::success(translate('messages.customer') . translate('messages.status_updated'));
        return back();
    }

    public function activateAll()
    {
        $statusColumn = $this->getUserStatusColumn();

        if (! $statusColumn) {
            Toastr::warning('Customer status control is unavailable for the current database schema.');
            return back();
        }

        $updated = User::query()
            ->where(function ($query) {
                $statusColumn = $this->getUserStatusColumn();
                $query->whereNull($statusColumn)->orWhere($statusColumn, 0);
            })
            ->update([
                $statusColumn => 1,
                'updated_at' => now(),
            ]);

        Toastr::success($updated > 0
            ? "{$updated} customers activated successfully."
            : 'All customers are already active.'
        );

        return back();
    }

    public function search(Request $request)
    {
        $key = explode(' ', $request['search']);
        $customers = User::where(function ($q) use ($key) {
            foreach ($key as $value) {
                $q->orWhere('f_name', 'like', "%{$value}%")
                    ->orWhere('l_name', 'like', "%{$value}%")
                    ->orWhere('email', 'like', "%{$value}%")
                    ->orWhere('phone', 'like', "%{$value}%");
            }
        })->orderBy('order_count', 'desc')->limit(50)->get();
        return response()->json([
            'count' => count($customers),
            'view' => view('admin-views.customer.partials._table', compact('customers'))->render()
        ]);
    }

    public function destroy($id)
    {
        $customer = User::find($id);

        if (! $customer) {
            Toastr::error(translate('messages.customer_not_found'));
            return back();
        }

        if ($this->hasOngoingOrders($customer->id)) {
            Toastr::warning('Please complete the customer ongoing orders before deleting the account.');
            return back();
        }

        if ($this->hasOngoingTrips($customer->id)) {
            Toastr::warning('Please complete the customer ongoing trips before deleting the account.');
            return back();
        }

        try {
            DB::transaction(function () use ($customer) {
                $customer->tokens()->delete();
                $customer->storage()->delete();
                $customer->addresses()->delete();

                if ($customer->userinfo) {
                    $customer->userinfo->delete();
                }

                if (Schema::hasTable('wishlists') && Schema::hasColumn('wishlists', 'user_id')) {
                    DB::table('wishlists')->where('user_id', $customer->id)->delete();
                }

                if (Schema::hasTable('carts') && Schema::hasColumn('carts', 'user_id')) {
                    DB::table('carts')->where('user_id', $customer->id)->delete();
                }

                if (Schema::hasTable('recent_searches') && Schema::hasColumn('recent_searches', 'user_id')) {
                    DB::table('recent_searches')->where('user_id', $customer->id)->delete();
                }

                if (Schema::hasTable('user_notifications') && Schema::hasColumn('user_notifications', 'user_id')) {
                    DB::table('user_notifications')->where('user_id', $customer->id)->delete();
                }

                $customer->delete();
            });
        } catch (\Throwable $exception) {
            Log::error('Customer delete failed.', [
                'customer_id' => $customer->id,
                'message' => $exception->getMessage(),
            ]);

            Toastr::error('Customer delete failed. Please try again.');
            return back();
        }

        Toastr::success('Customer deleted successfully.');
        return back();
    }

    public function view(Request $request,$id)
    {
        $key = $request['search'];
        $customer = User::find($id);
        if (isset($customer)) {
            $total_order_amount = Order::selectRaw('sum(order_amount) as total_order_amount')->latest()->where(['user_id' => $id])
                ->when(isset($key), function($query) use($key){
                    $query->Where('id', 'like', "%{$key}%");
                } )
                ->Notpos()->get();
            $orders = Order::withcount('details')->latest()->where(['user_id' => $id])
            ->when(isset($key), function($query) use($key){
                $query->Where('id', 'like', "%{$key}%");
            } )
            ->Notpos()->paginate(config('default_pagination'));
            $courierPerformanceSummary = app(CustomerCourierPerformanceService::class)->summarizeForUser($customer);
            $codRestriction = app(CustomerCodRestrictionService::class)->payloadFor($customer);

            return view('admin-views.customer.customer-view', compact('customer', 'orders', 'total_order_amount', 'courierPerformanceSummary', 'codRestriction'));
        }
        Toastr::error(translate('messages.customer_not_found'));
        return back();
    }

    public function courierPerformance($user_id, CustomerCourierPerformanceService $customerCourierPerformanceService)
    {
        $customer = User::find($user_id);

        if (! $customer) {
            Toastr::error(translate('messages.customer_not_found'));
            return back();
        }

        $courierPerformanceSummary = $customerCourierPerformanceService->summarizeForUser($customer);

        return view('admin-views.customer.courier-performance', [
            'customer' => $customer,
            'courierPerformanceSummary' => $courierPerformanceSummary,
            'sourceOrder' => null,
        ]);
    }

    public function rentalView(Request $request,$id)
    {
        if (!rental_module_is_ready()) {
            Toastr::error(translate('messages.rental_module_is_not_available'));
            return redirect()->route('admin.users.customer.view', $id);
        }

        $key = $request['search'];
        $customer = User::find($id);
        if (isset($customer)) {
            $tripModel = \Modules\Rental\Entities\Trips::class;
            $total_trips_amount = $tripModel::selectRaw('sum(trip_amount) as total_trip_amount')->latest()->where(['user_id' => $id])
                ->when(isset($key), function($query) use($key){
                    $query->Where('id', 'like', "%{$key}%");
                })->get();
            $trips = $tripModel::withcount('trip_details')->latest()->where(['user_id' => $id])
            ->when(isset($key), function($query) use($key){
                $query->Where('id', 'like', "%{$key}%");
            })->paginate(config('default_pagination'));
            return view('admin-views.customer.customer-rental-view', compact('customer', 'trips','total_trips_amount'));
        }
        Toastr::error(translate('messages.customer_not_found'));
        return back();
    }

    public function customer_order_export(Request $request)
    {
        $customer = User::find($request->id);

        $orders = Order::latest()->where(['user_id' => $request->id])->Notpos()->get();

        $data = [
            'orders'=>$orders,
            'customer_id'=>$customer->id,
            'customer_name'=>$customer->f_name.' '.$customer->l_name,
            'customer_phone'=>$customer->phone,
            'customer_email'=>$customer->email,
        ];

        if ($request->type == 'excel') {
            return Excel::download(new CustomerOrderExport($data), 'CustomerOrders.xlsx');
        } else if ($request->type == 'csv') {
            return Excel::download(new CustomerOrderExport($data), 'CustomerOrders.csv');
        }
    }

    public function customer_trip_export(Request $request)
    {
        if (!rental_module_is_ready() || !class_exists(\Modules\Rental\Exports\TripExport::class)) {
            Toastr::error(translate('messages.rental_module_is_not_available'));
            return back();
        }

        $key = explode(' ', $request['search']);

        $tripModel = \Modules\Rental\Entities\Trips::class;
        $tripExportModel = \Modules\Rental\Exports\TripExport::class;
        $trips = $tripModel::latest()->where(['user_id' => $request->id])
            ->when(isset($key), function ($query) use ($key) {
                return $query->where(function ($q) use ($key) {
                    foreach ($key as $value) {
                        $q->orWhere('id', 'like', "%{$value}%");
                    }
                });
            })
            ->get();

        $data = [
            'data' => $trips,
            'search' => $request['search'] ?? null,
        ];

        if ($request->type == 'excel') {
            return Excel::download(new $tripExportModel($data), 'CustomerTrips.xlsx');
        } else if ($request->type == 'csv') {
            return Excel::download(new $tripExportModel($data), 'CustomerTrips.csv');
        }
    }

    public function subscribedCustomers(Request $request)
    {
        $filter=  $request->filter ?? null;
        $show_limit=  $request->show_limit ?? null;
        $join_date_start =null;
        $join_date_end = null;
        if($request?->join_date){
            list($join_date_start, $join_date_end) = explode(' - ', $request?->join_date);
            $join_date_start = Carbon::createFromFormat('m/d/Y', $join_date_start)->startOfDay();
            $join_date_end = Carbon::createFromFormat('m/d/Y', $join_date_end)->endOfDay();
        }

        $key = explode(' ', $request['search']);


        $customers = Newsletter::when(isset($key), function($query) use($key) {
            $query->where(function ($q) use ($key) {
                foreach ($key as $value) {
                    $q->orWhere('email', 'like', "%". $value."%");
                }
            });
        })

        ->when(isset($request->join_date) , function ($query) use($join_date_start, $join_date_end) {
            $query->WhereBetween('created_at', [$join_date_start, $join_date_end]);
        });


        if(isset($filter) && $filter == 'oldest' ){
            $customers=$customers->oldest();
            } else{
                $customers=$customers->latest();
        }

        if(isset($show_limit) && $show_limit > 0 ){
            $customers= $customers->take($show_limit)->get();
            $perPage = config('default_pagination');
            $page =  $request?->page ?? 1;
            $offset = ($page - 1) * $perPage;
            $itemsForCurrentPage = $customers->slice($offset, $perPage);
            $customers = new \Illuminate\Pagination\LengthAwarePaginator(
                $itemsForCurrentPage,
                $customers->count(),
                $perPage,
                $page,
                ['path' => Paginator::resolveCurrentPath(), 'query' => request()->query()]
            );


        } else{
            $customers=$customers->paginate(config('default_pagination'));
        }


        $data['subscribedCustomers'] = $customers;


        return view('admin-views.customer.subscribed-emails', $data);
    }

    public function subscribed_customer_export(Request $request){
        $key = explode(' ', $request['search']);

        $filter=  $request->filter ?? null;
        $show_limit=  $request->show_limit ?? null;
        $join_date_start =null;
        $join_date_end = null;
        if($request?->join_date){
            list($join_date_start, $join_date_end) = explode(' - ', $request?->join_date);
            $join_date_start = Carbon::createFromFormat('m/d/Y', $join_date_start)->startOfDay();
            $join_date_end = Carbon::createFromFormat('m/d/Y', $join_date_end)->endOfDay();
        }



        $customers = Newsletter::when(isset($key), function($query) use($key) {
            $query->where(function ($q) use ($key) {
                foreach ($key as $value) {
                    $q->orWhere('email', 'like', "%". $value."%");
                }
            });
        })
        ->when(isset($request->join_date) , function ($query) use($join_date_start, $join_date_end) {
            $query->WhereBetween('created_at', [$join_date_start, $join_date_end]);
        });

        if(isset($filter) && $filter == 'oldest' ){
            $customers=$customers->oldest();
            } else{
                $customers=$customers->latest();
        }

        if(isset($show_limit) && $show_limit > 0 ){
            $customers= $customers->take($show_limit)->get();
        } else{
            $customers= $customers->get();
        }


        $data = [
            'customers'=>$customers
        ];

        if ($request->type == 'excel') {
            return Excel::download(new SubscriberListExport($data), 'Subscribers.xlsx');
        } else if ($request->type == 'csv') {
            return Excel::download(new SubscriberListExport($data), 'Subscribers.csv');
        }
    }



    public function get_customers(Request $request){
        $key = explode(' ', $request['q']);
        $data = User::
        where(function ($q) use ($key) {
            foreach ($key as $value) {
                $q->orWhere('f_name', 'like', "%{$value}%")
                ->orWhere('l_name', 'like', "%{$value}%")
                ->orWhere('phone', 'like', "%{$value}%");
            }
        })
        ->limit(8)
        ->get([DB::raw('id, CONCAT(f_name, " ", l_name, " (", phone ,")") as text')]);
        if($request->all) $data[]=(object)['id'=>false, 'text'=>translate('messages.all')];


        return response()->json($data);
    }

    public function settings()
    {
        $data = BusinessSetting::where('key','like','wallet_%')
            ->orWhere('key','like','loyalty_%')
            ->orWhere('key','like','review_reward_%')
            ->orWhere('key','like','ref_earning_%')
            ->orWhere('key','like','ref_earning_%')->get();
        $data = array_column($data->toArray(), 'value','key');
        // dd($data);
        return view('admin-views.customer.settings', compact('data'));
    }

    public function bonusLogs(Request $request)
    {
        $query = BonusClaimLog::with('user')
            ->latest('attempted_at')
            ->latest('id');

        if (in_array($request->bonus_type, ['signup', 'review'], true)) {
            $query->where('bonus_type', $request->bonus_type);
        }

        if (in_array($request->status, ['granted', 'blocked'], true)) {
            $query->where('granted_status', $request->status === 'granted' ? 1 : 0);
        }

        if ($request->filled('reason')) {
            $query->where('block_reason', $request->reason);
        }

        if ($request->filled('search')) {
            $search = trim((string) $request->search);
            $query->where(function ($bonusLogQuery) use ($search) {
                $bonusLogQuery
                    ->where('email', 'like', "%{$search}%")
                    ->orWhere('phone', 'like', "%{$search}%")
                    ->orWhere('device_identifier', 'like', "%{$search}%")
                    ->orWhereHas('user', function ($userQuery) use ($search) {
                        $userQuery
                            ->where('f_name', 'like', "%{$search}%")
                            ->orWhere('l_name', 'like', "%{$search}%")
                            ->orWhere('email', 'like', "%{$search}%")
                            ->orWhere('phone', 'like', "%{$search}%");
                    });
            });
        }

        $logs = $query->paginate(25)->appends($request->query());
        $reasonOptions = BonusClaimLog::whereNotNull('block_reason')
            ->distinct()
            ->orderBy('block_reason')
            ->pluck('block_reason')
            ->filter()
            ->values();

        return view('admin-views.customer.bonus-logs', compact('logs', 'reasonOptions'));
    }

    public function update_settings(Request $request)
    {
        $request->validate([
            'add_fund_bonus'=>'nullable|numeric|max:100|min:0',
            'loyalty_point_exchange_rate'=>'nullable|numeric',
            'ref_earning_exchange_rate'=>'nullable|numeric',
            'registration_bonus_amount' => 'nullable|numeric|min:0',
            'registration_bonus_popup_message' => 'nullable|string|max:500',
            'review_reward_point' => 'nullable|integer|min:0',
            'review_reward_popup_message' => 'nullable|string|max:500',
            'risk_based_cod_restriction_threshold' => 'nullable|numeric|min:0|max:100',
            'risk_based_cod_restriction_message' => 'nullable|string|max:500',
        ]);
            $keys=['guest_checkout_status','toggle_veg_non_veg','wallet_status','wallet_add_refund','add_fund_status','loyalty_point_status','loyalty_point_exchange_rate','loyalty_point_item_purchase_point',
                    'loyalty_point_minimum_point','ref_earning_status','ref_earning_exchange_rate','new_customer_discount_status',
                    'new_customer_discount_amount_type','new_customer_discount_validity_type','new_customer_discount_amount','new_customer_discount_amount_validity',
                    'registration_bonus_status','registration_bonus_amount','registration_bonus_popup_message',
                    'review_reward_status','review_reward_point','review_reward_popup_message',
                    'risk_based_cod_restriction_status','risk_based_cod_restriction_threshold','risk_based_cod_restriction_message',
                // 'country_picker_status',
                ];
        $textSettingKeys = [
            'registration_bonus_popup_message',
            'review_reward_popup_message',
            'risk_based_cod_restriction_message',
        ];

        foreach ($keys as $key) {
            Helpers::businessUpdateOrInsert(['key' => $key], [
                'value' => in_array($key, $textSettingKeys, true)
                    ? trim((string) $request->input($key, ''))
                    : ($request->$key ?? 0),
            ]);
        }
        Toastr::success(translate('messages.customer_settings_updated_successfully'));
        return back();
    }

    public function export(Request $request){
        $zone_id=  $request->zone_id ?? null;
        $filter=  $request->filter ?? null;
        $order_wise=  $request->order_wise ?? null;
        $show_limit=  $request->show_limit ?? null;
        $key = [];
        if ($request->search) {
            $key = explode(' ', $request['search']);
        }

        $order_date_start = null;
        $order_date_end =null;

        $join_date_start =null;
        $join_date_end = null;

        if($request?->order_date){
            list($order_date_start, $order_date_end) = explode(' - ', $request?->order_date);
            $order_date_start = Carbon::createFromFormat('m/d/Y', $order_date_start)->startOfDay();
            $order_date_end = Carbon::createFromFormat('m/d/Y', $order_date_end)->endOfDay();
        }
        if($request?->join_date){
            list($join_date_start, $join_date_end) = explode(' - ', $request?->join_date);
            $join_date_start = Carbon::createFromFormat('m/d/Y', $join_date_start)->startOfDay();
            $join_date_end = Carbon::createFromFormat('m/d/Y', $join_date_end)->endOfDay();
        }



        $customers = User::when(count($key) > 0, function ($query) use ($key) {
            foreach ($key as $value) {
                $query->orWhere('f_name', 'like', "%{$value}%")
                    ->orWhere('l_name', 'like', "%{$value}%")
                    ->orWhere('email', 'like', "%{$value}%")
                    ->orWhere('phone', 'like', "%{$value}%");
            };
        })->withcount('orders')

        ->when(isset($request->join_date) , function ($query) use($join_date_start, $join_date_end) {
            $query->WhereBetween('created_at', [$join_date_start, $join_date_end]);
        })
        ->when(isset($request->order_date) , function ($query) use($order_date_start, $order_date_end) {
            $query->wherehas('orders',function ($query) use($order_date_start, $order_date_end){
                $query->WhereBetween('created_at', [$order_date_start, $order_date_end]);
            });
        })
        ->when(isset($zone_id) && is_numeric($zone_id) , function ($query) use($zone_id){
            $query->where('zone_id' ,$zone_id);
        })
        ->when(isset($filter) && in_array($filter, ['active', 'blocked'], true), function ($query) use ($filter) {
            $this->applyUserStatusFilter($query, $filter);
        })
        ->when(isset($filter) && $filter == 'new' , function ($query) {
            $query->whereDate('created_at', '>=', now()->subDays(30)->format('Y-m-d'));
        })
        ->when(isset($order_wise) && $order_wise == 'top' , function ($query) {
            $query->orderBy('orders_count', 'desc');
        })
        ->when(isset($order_wise) && $order_wise == 'least' , function ($query) {
            $query->orderBy('orders_count', 'asc');
        })
        ->when(isset($order_wise) && $order_wise == 'latest' , function ($query) {
            $query->latest();
        })
        ->when(isset($order_wise) && $order_wise == 'oldest' , function ($query) {
            $query->oldest();
        })

        ->when(isset($order_wise) && $order_wise == 'order_amount', function ($query) {
            $query->withSum('orders as total_order_amount', 'order_amount')
                ->orderByDesc('total_order_amount');
        })
        ->when(!$order_wise, function ($query) {
            $query->orderBy('orders_count', 'desc');
        });


        if(isset($show_limit) && $show_limit > 0 ){
            $customers= $customers->take($show_limit)->get();
            } else{
            $customers= $customers->get();
        }


        if($order_wise == 'top'){
            $order_wise = translate('messages.Sort by order count');
        }elseif ($order_wise == 'order_amount'){
            $order_wise = translate('messages.Sort by order amount');
        }elseif ($order_wise == 'oldest'){
            $order_wise = translate('messages.Sort by oldest');
        }elseif ($order_wise == 'latest'){
            $order_wise =  translate('messages.Sort by newest');
        }


        $data = [
            'customers'=>$customers,
            'filter'=>$request->filter ?? null,
            'order_wise'=>$order_wise ?? null,
            'show_limit'=>$request->show_limit ?? null,
            'order_date'=>$request?->order_date,
            'join_date'=>$request?->join_date,
            'search'=>$request->search??null,

        ];

        if ($request->type == 'excel') {
            return Excel::download(new CustomerListExport($data), 'Customers.xlsx');
        } else if ($request->type == 'csv') {
            return Excel::download(new CustomerListExport($data), 'Customers.csv');
        }
    }
}
