<?php

namespace App\Http\Controllers;

use App\Classes\EditLogHistory;
use App\Classes\SMS\DueCustomerSms;
use App\Classes\SMS\ExpireCustomerNotifySms;
use App\Console\Commands\ExpireCustomerSendSMS;
use Carbon\Carbon;
use App\Models\Pop;
use App\Models\User;
use App\Models\Client;
use App\Models\SmsApi;
use App\Models\SmsLog;
use App\Jobs\SendSmsJob;
use App\Models\Reseller;
use App\Models\SmsSetting;
use App\Models\BillGenerate;
use Illuminate\Http\Request;
use App\Models\CompanyInformation;
use Illuminate\Support\Facades\DB;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Cache;
use App\Jobs\ExpireCustomerNotification;
use App\Models\GlobalSettings;
use App\Models\ResellerSmsGetway;
use Illuminate\Support\Facades\Artisan;
use Mpdf\Tag\Tr;
use Symfony\Component\Console\Input\Input;

class  SmsController extends Controller
{
    public function __construct()
    {

        $this->middleware('permission:send-sms-from-header-search', ['only' => ['sendSmsSingle']]);
        $this->middleware('permission:sms_gateway_list', ['only' => ['index']]);
    }

    public function index()
    {


        $data = [
            'gateway' => SmsApi::paginate(500)
        ];
        return view('sms.index', $data);
    }

    public function create()
    {
        return view('sms.create');
    }

    public function store(Request $request)
    {

        $request->validate([
            'sender' => 'required|unique:sms_apis',
        ]);

        $gateway = new SmsApi();
        $gateway->fill($request->all());

        if ((SmsApi::where('status', '=', 'enable')->exists()) && ($gateway->status == 'enable')) {

            Artisan::call('optimize:clear');
            exec('/usr/bin/sudo supervisorctl restart all');

            Toastr::error('Already One item is Enable', '', ['progressbar' => true]);
            return redirect()->route('sms-gateway.create');
        } else {

            $gateway->save();
            exec('/usr/bin/sudo supervisorctl restart all');

            Toastr::success('Information Added Successfully', '', ['progressbar' => true]);
            return redirect()->route('sms-gateway.index');
        }
    }

    public function show($id)
    {
        //
    }

    public function edit($id)
    {
        // dd($id);
        $gateway = SmsApi::find($id);
        return view('sms.edit', [
            'gateway' => $gateway
        ]);
    }

    public function update(Request $request, $id)
    {
        $type = 'SMS Gateway';
        $old_info = SmsApi::where('id', $id)->first();

        $gateway = SmsApi::find($id);
        $previous_sms_gateway = SmsApi::where('status', '=', 'enable')->first();

        if ($previous_sms_gateway != null) {
            if ($id != $previous_sms_gateway->id) {
                Toastr::error('Already One item is Enable', '', ['progressbar' => true]);
                return redirect()->back();
            }
        }

        $request->validate([
            'sender' => 'required|unique:sms_apis,sender,' . $gateway->id,
        ]);
        $gateway->fill($request->all());
        $gateway->update();

        $new_info = SmsApi::find($gateway->id);
        (new EditLogHistory)->editLogSave($gateway, $type, $old_info, $new_info);

        Cache::forget('smsMessage');
        Artisan::call('cache:clear');
        Artisan::call('optimize:clear');
        exec('/usr/bin/sudo supervisorctl restart all');
        Toastr::success('Information Updated Successfully', '', ['progressbar' => true]);
        return redirect()->route('sms-gateway.index');

        //old code start
        // if ((SmsApi::where('status', '=', 'enable')->exists()) && ($gateway->status == 'enable')) {
        //     $existEnableId = SmsApi::where('status', '=', 'enable')->first();
        //     if ($existEnableId->id == $id) {

        //         $gateway->update();
        //         Artisan::call('optimize:clear');
        //         exec('/usr/bin/sudo supervisorctl restart all');
        //         Toastr::success('Information Updated Successfully', '', ['progressbar' => true]);
        //         return redirect()->route('sms-gateway.index');
        //     } else {
        //         Toastr::error('Already One item is Enable', '', ['progressbar' => true]);
        //         return redirect()->route('sms-gateway.index');
        //     }
        // } else {
        //     $gateway->update();
        //     Artisan::call('optimize:clear');
        //     exec('/usr/bin/sudo supervisorctl restart all');
        //     Toastr::success('Information Updated Successfully', '', ['progressbar' => true]);
        //     return redirect()->route('sms-gateway.index');
        // }
        //old code end
    }

    function techno_bulk_sms($ap_key, $user_email)
    {
        $url = 'https://24bulksms.com/24bulksms/api/user-info-chack';
        $data = array(
            'api_key' => $ap_key,
            'user_email' => $user_email
        );
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }


    public function balance()
    {
        $result =  cache()->remember('smsapi', 60 * 60, function () {
            return SmsApi::where('status', 'enable')->first();
        });

        try {

            if ($result) {
                $host = parse_url($result->balance_url);
                // dd($host);
                if ($host['host'] == 'smsplus.sslwireless.com') {
                    $res = Http::post($result->balance_url, [
                        'api_token' => $result->apikey,
                        'sid' => $result->sender,
                    ]);
                    $b = json_decode($res->body());
                    $balance = isset($b->balance) ? $b->balance : 0;
                } else if ($host == 'sms.solutionsclan.com') {
                    $res = Http::get($result->path);
                    $b = json_decode($res->body());
                    $balance = $b->balance;
                } else if ($host['host'] == '24bulksms.com') {
                    $email = $result->sender;
                    $ap_key = $result->apikey;
                    $res = $this->techno_bulk_sms($ap_key, $email);
                    $b = json_decode($res);
                    $balance = isset($b->data->balance) ? $b->data->balance : 0;
                } else if ($host['host'] == 'msg.elitbuzz-bd.com') {
                    $res = Http::get($result->balance_url);
                    $balance = $res->body();
                } else if ($host['host'] == 'smpp.revesms.com') {

                    $res = Http::get($result->balance_url);

                    $balance = json_decode($res)->Balance;
                } else if ($host['host'] == 'sms.mram.com.bd') {
                    $res = Http::get($result->balance_url);
                    $balance = $res->body();
                } else {
                    // $res = Http::get($result->path);
                    // $balance =  $res->body();

                    // dd(Http::get($result->path));

                    // $res = Http::get($host['scheme'] . '://' . $host['host'] . $host['path'] . '?' . $host['query']);
                    $res = Http::get($host['scheme'] . '://' . $host['host'] . $host['path'] . (!empty($host['query']) ? '?' . $host['query'] : ''));
                    $balance =  $res->body();
                }
            } else {

                $balance = 0;
            }
        } catch (\Throwable $th) {
            // dd($th);
            $balance = 0;
        }

        $data = [
            'emptyBalance' => $balance, // number_format($balance,2),
        ];

        return view('balance.index', $data);
    }

    public function showSmsBalance()
    {
        return getYourSmsBalance();
    }

    public function recharge()
    {
        return view('sms.recharge');
    }
    public function setting()
    {
        // return view('sms.recharge');
        $data = [
            'smsSetting' => SmsSetting::get(),
        ];
        // dd($data);
        return view('smsSetting.index', $data);
    }

    public function smsTempalteSave(Request $request)
    {
        $template = SmsSetting::where('tamplate_name', $request->sms_type)->first();

        $type = $request->sms_type;
        $old_info = SmsSetting::where('tamplate_name', $request->sms_type)->first();

        if ($request->sms_type == "bill_payment" || $request->sms_type == "welcome") {

            $data = json_decode($request->sms_body, true);
            $sendsms = $data['sendsms'];

            if ($request->sms_type == "bill_payment") {
                $setting = GlobalSettings::where('name', 'bill-payment-sms')->first();
            } elseif ($request->sms_type == "welcome") {
                $setting = GlobalSettings::where('name', 'new-user-create-sms')->first();
            }

            if ($sendsms == "Yes") {
                $setting->status = 'enable';
            } elseif ($sendsms == "No") {
                $setting->status = 'disable';
            }
            $setting->update();

            if ($template) {
                $template->tamplate_body = $request->sms_body;
                $template->save();
            } else {
                $new_template = new SmsSetting();
                $new_template->tamplate_name = $request->sms_type;
                $new_template->tamplate_body = $request->sms_body;
                $new_template->save();
            }
        } else {

            if ($template) {
                $template->tamplate_body = $request->sms_body;
                $template->save();
            } else {
                $new_template = new SmsSetting();
                $new_template->tamplate_name = $request->sms_type;
                $new_template->tamplate_body = $request->sms_body;
                $new_template->save();
            }
        }

        $new_info = SmsSetting::where('tamplate_name', $request->sms_type)->first();
        (new EditLogHistory)->editLogSave($old_info, $type, $old_info, $new_info);

        Cache::forget('smsMessage');
        Artisan::call('cache:clear');
        return 1;
    }

    public function sendSms()
    {
        $reseller = Reseller::resellerList()->get();
        $users = User::whereHas('userdetails', function ($q) {
            $q->where('user_status', 'active');
        })->where('id', '>', 1)
            ->where('email', '!=', 'soiket@outlook.com')
            ->where('email', '!=', 'support@yetfix.com')
            ->where('email', '!=', 'admin@billingfix.xyz')
            ->get();


        return view('smsSetting.create', [
            'reseller' => $reseller,
            'single' => false,
            'client' => null,
            'users' => $users,
            'confday' => config('app.billing_cycle'),

        ]);
    }

    public function sendSmsToSelectedPop(Request $request)
    {

        if ($request->pop_id && $request->reseller_id && $request->billing_cycle && $request->status && $request->message && $request->singel_number == null) {

            if ($request->pop_id == 'all') {

                $pop_ids = Pop::where('reseller_id', $request->reseller_id)->pluck('id');
                if ($request->billing_cycle == 'all') {
                    $clients = Client::with('clientsinfo')
                        ->whereIn('pop_id', $pop_ids);
                } else {
                    $clients = Client::with('customerAccount', 'clientsinfo')
                        ->whereIn('pop_id', $pop_ids)
                        ->where('billing_cycle', $request->billing_cycle);
                }
            } else {
                if ($request->billing_cycle == 'all') {
                    $clients = Client::with('clientsinfo')
                        ->where('pop_id', $request->pop_id);
                } else {
                    $clients = Client::with('clientsinfo')
                        ->where('pop_id', $request->pop_id)
                        ->where('billing_cycle', $request->billing_cycle);
                }
            }

            // If "close" is selected as a status, always send only to SOFT-DELETED close customers
            if (in_array('close', (array) $request->status)) {
                // requires Client model to use SoftDeletes trait
                $clients = $clients->onlyTrashed();//->where('deleted_at', '!=', null);
            } else {
                $clients = $clients->whereIn('clients_status', $request->status);
            }

            if (in_array('all', $request->areas)) {
                $clients = $clients->get();
            } else {
                $clients = $clients->whereHas('clientsinfo', function ($query) use ($request) {
                    $query->whereIn('area', $request->areas);
                })->get();
            }

            if ($clients->count() > 0) {
                $datas = [];
                foreach ($clients as $client) {
                    if ($client->clientsinfo->contact_no) {

                        $data = [
                            'message' => $this->smsReplace($request->message, $client),
                            'contact_no' => $client->clientsinfo->contact_no,
                            'type' => 'sms_send'
                        ];
                        $datas[] = $data;
                        try {
                            SendSmsJob::dispatch($data);
                        } catch (\Throwable $th) {
                        }
                    }
                }


                $res['success'] = 'Total Customer: ' . $clients->count() . '. All Process In Queue';
            } else {
                $res['error'] = 'No Customer Found';
            }
        } else if ($request->singel_number && $request->message) {
            $len = strlen($request->singel_number);
            if ($len == 11) {

                $client = Client::with('clientsinfo')->whereHas('clientsinfo', function ($query) use ($request) {
                    $query->where('contact_no', $request->singel_number);
                })->first();

                if ($client != null) {
                    $data = [
                        'message' => $this->smsReplace($request->message, $client),
                        'contact_no' => $client->clientsinfo->contact_no ?? $request->singel_number,
                        'type' => 'sms_send'
                    ];
                } else {
                    $data = [
                        'message' => $request->message,
                        'contact_no' => $request->singel_number,
                        'type' => 'sms_send'
                    ];
                }

                SendSmsJob::dispatch($data);
                $res['success'] = 'Sms Send to ' . $request->singel_number . '. All Process In Queue';
            } else {
                $res['error'] = 'Single Number Must be 11 digit';
            }
        } else {
            $res['error'] = 'Required all input';
        }

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

    public function smsReplace($message, $client)
    {
        if ($client->customerAccount != null) {
            $dueAmount = $client->customerAccount->dueAmount;
        } else {
            $dueAmount = 0;
        }
        $company_info = CompanyInformation::latest()->first();
        $link = CompanyInfoController::baseUrl();
        $message = str_replace(
            [
                '{c_code}',
                '{c_password}',
                '{userid}',
                '{customer_id}',
                '{c_id}',
                '{c_username}',
                '{c_name}',
                '{c_deadline}',
                '{TotalDue}',
                '{company_cell}',
                '{company_name}',
                '{payment_url}'
            ],
            [
                $client->customer_code ?? '',
                $client->password,
                $client->userid,
                $client->id,
                $client->id,
                $client->userid,
                $client->clientsinfo->clients_name,
                $client->expire_date,
                $dueAmount,
                $company_info->mobile,
                $company_info->name,
                $link . $client->slug
            ],
            $message
        );

        return $message;
    }

    public function smsLog()
    {

        $start = Carbon::now()->startOfMonth();
        $end = today();
        $types = SmsLog::groupBy('type')->pluck('type');

        $data = [
            'smsLog' => SmsLog::orderBy('id', 'desc')->paginate(100),
            'start' => $start,
            'end' => $end,
            'types'     => $types
        ];

        return view('sms.smsLog', $data);
    }

    public function smsLogSearchResult(Request $request)
    {
        if ($request->ajax()) {

            if (!empty($request->from_date) && !empty($request->to_date)) {

                $from = Carbon::parse($request->from_date)->format('Y-m-d 00:00:00');
                $to   = Carbon::parse($request->to_date)->format('Y-m-d 23:59:59');


                if (!empty($request->type)) {

                    $list = SmsLog::where(function ($q) use ($from, $to) {
                        return $q->whereBetween('created_at', [$from, $to]);
                    })->where('type', $request->type)->orderBy('id', 'DESC');
                } elseif (!empty($request->contact)) {

                    $list = SmsLog::where(function ($q) use ($from, $to) {
                        return $q->whereBetween('created_at', [$from, $to]);
                    })->where('contact', 'like', '%' . $request->contact)->orderBy('id', 'DESC');
                } else {
                    $list = SmsLog::where(function ($q) use ($from, $to) {
                        return $q->whereBetween('created_at', [$from, $to]);
                    })->orderBy('id', 'DESC');
                }
            } else if (!empty($request->contact)) {

                $list = SmsLog::where('contact', $request->contact)->orderBy('id', 'DESC');
            } else {

                return '<p class="text-center text-danger">Please Select (From Date, To Date and Type) or (From Date, To Date and Contact) Field</p>';
            }

            return view('sms.result', [
                'smsLog' =>  $list->orderBy('id', 'desc')->get(),
            ]);
        }
    }

    public function sendSmsSingle($id)
    {
        $client = Client::with('clientsinfo')->find($id);
        $reseller = Reseller::resellerList()->get();
        $users = User::whereHas('userdetails', function ($q) {
            $q->where('user_status', 'active');
        })->where('id', '>', 1)
            ->where('email', '!=', 'soiket@outlook.com')
            ->where('email', '!=', 'support@yetfix.com')
            ->get();

        return view('smsSetting.create', [
            'reseller' => $reseller,
            'single' => true,
            'client' => $client,
            'users'  => $users,
            'confday' => config('app.billing_cycle'),
        ]);
    }


    public function sendSmsToSelectedUser(Request $request)
    {
        if ($request->users && $request->message) {

            if (in_array('all_user', $request->users) && in_array('all_manager', $request->users)) {
                // return 1;

                $users = User::where('id', '>', 1)
                    ->where('email', '!=', 'soiket@outlook.com')
                    ->where('email', '!=', 'support@yetfix.com')
                    ->get();
                // return $users;
                foreach ($users as $user) {
                    if ($user->mobile_number) {

                        $data = [
                            'message' => $request->message,
                            'contact_no' => $user->mobile_number,
                            'type' => 'user_sms_send'
                        ];
                        SendSmsJob::dispatch($data);
                    }
                }

                $managers = Reseller::get();
                foreach ($managers as $manager) {
                    if ($manager->contact) {
                        $data = [
                            'message' => $request->message,
                            'contact_no' => $manager->contact,
                            'type' => 'sms_send'
                        ];
                        SendSmsJob::dispatch($data);
                    }
                }
                $total = $users->count() + $managers->count();
                $res['success'] = 'Total Users: ' . $total . '. All Process In Queue';
                return response()->json($res);
            } else if (in_array('all_user', $request->users) || in_array('all_manager', $request->users)) {
                // return 2;
                if (in_array('all_user', $request->users)) {
                    $users = User::where('id', '>', 1)
                        ->where('email', '!=', 'soiket@outlook.com')
                        ->where('email', '!=', 'support@yetfix.com')
                        ->get();
                    // return $users;
                    foreach ($users as $user) {
                        if ($user->mobile_number) {

                            $data = [
                                'message' => $request->message,
                                'contact_no' => $user->mobile_number,
                                'type' => 'user_sms_send'
                            ];
                            SendSmsJob::dispatch($data);
                        }
                    }
                    $total = $users->count();
                    $res['success'] = 'Total Users: ' . $total . '. All Process In Queue';
                    return response()->json($res);
                } else {

                    $users = Reseller::get();
                    foreach ($users as $user) {
                        $data = [
                            'message' => $request->message,
                            'contact_no' => $user->contact,
                            'type' => 'manager_sms_send'
                        ];
                        SendSmsJob::dispatch($data);
                    }

                    $res['success'] = 'Total Users: ' . $users->count() . '. All Process In Queue';
                    return response()->json($res);
                }
            } else {
                // return 3;
                $users = User::whereIn('id', $request->users)->get();
                foreach ($users as $user) {
                    if ($user->mobile_number) {

                        $data = [
                            'message' => $request->message,
                            'contact_no' => $user->mobile_number,
                            'type' => 'user_sms_send'
                        ];
                        SendSmsJob::dispatch($data);
                    }
                }

                $res['success'] = 'Total Users: ' . $users->count() . '. All Process In Queue';
                return response()->json($res);
            }
        } else {
            $res['error'] = 'Required all input';
            return response()->json($res);
        }
    }

    public function sendBillGenerateSMS()
    {
        $link = CompanyInfoController::baseUrl();
        $today_start = Carbon::parse(today())->format('Y-m-d 00:00:00');
        $today_end = Carbon::parse(today())->format('Y-m-d 23:59:59');
        $sms_setting = SmsSetting::where('tamplate_name', 'bill_generate')->first();
        $result_decode = json_decode($sms_setting->tamplate_body, true);
        $sms_send = $result_decode["sendsms"];
        $message = $result_decode["sms_body"];
        $now = new \DateTime('now');
        $current_month = $now->format('M-Y');
        // dd($sms_send);
        $company_info = CompanyInformation::latest()->first();
        $bill_generates = BillGenerate::with('clients.customerAccount', 'clientsinfo', 'clients.pop')->whereBetween('updated_at', [$today_start, $today_end])->where('billing_type', 'monthly')->get();
        // If billgenerate send sms == yes than proceed
        if ($sms_send == "Yes") {

            foreach ($bill_generates as $bill) {
                if ($bill->clients->pop->sms_send == 'yes') {
                    $dead_line_time = Carbon::parse($bill->clients->expire_date)->addDay($bill->clients->payment_dadeline)->format('d-M-Y');
                    $actual_message = str_replace("{c_name}", "{$bill->clientsinfo->clients_name}", $message);
                    $actual_message = str_replace("{c_username}", "{$bill->clients->userid}", $actual_message);
                    $actual_message = str_replace("{MonthBillAmount}", "{$bill->bill_amount}", $actual_message);
                    $actual_message = str_replace("{ThisMonth}", "-{$current_month}", $actual_message);
                    $actual_message = str_replace("{company_name}", "{$company_info->name}", $actual_message);
                    $actual_message = str_replace("{company_cell}", "{$company_info->mobile}", $actual_message);
                    $actual_message = str_replace("{c_id}", "{$bill->clients->id}", $actual_message);
                    $actual_message = str_replace("{TotalDue}", "{$bill->clients->customerAccount->dueAmount}", $actual_message);
                    $actual_message = str_replace("{billing_deadline}", "{$dead_line_time}", $actual_message);
                    $actual_message = str_replace("{MonthDiscountAmount}", "{$bill->clients->billing_cycle}", $actual_message);
                    $actual_message = str_replace("{bill_type}", "{$bill->billing_type}", $actual_message);
                    $actual_message = str_replace("{payment_url}", $link . $bill->clients->slug, $actual_message);

                    $data = [
                        'message' => $actual_message,
                        'contact_no' => $bill->clientsinfo->contact_no,
                        'type' => 'bill_generate'
                    ];
                    SendSmsJob::dispatch($data);
                }
            }
        }
    }

    public function sendSMSExpiredCustomers()
    {
        if (globalPermission('expire_before_expire_date')) {

            $clients = Client::with('pop.reseller', 'clientsinfo')
            ->whereRaw('DATE(DATE_ADD(expire_date,INTERVAL payment_dadeline+0 DAY)) = DATE(CURDATE())')
            ->get();
        } else {
            $clients = Client::with('pop.reseller', 'clientsinfo')
                ->whereRaw('DATE(DATE_ADD(expire_date,INTERVAL payment_dadeline+1 DAY)) = DATE(CURDATE())')
                ->get();
        }



        foreach ($clients as $client) {

            if ($client->pop->bill_generate == 'yes' && $client->pop->sms_send == 'yes') {
                if (globalPermission('customResellerSmsGatewaySetup')){
                    $reseller_sms_getway = ResellerSmsGetway::with('reseller')->where('reseller_id', $client->pop->reseller_id)->first();
                    if ($reseller_sms_getway) {
                        $expire_customer_sms = collect(json_decode($reseller_sms_getway->sms_formate))->where('sms_type', 'own_reseller_customer_expire')->first();
                        if ($expire_customer_sms->send_sms == "Yes") {
                            (new ExpireCustomerNotifySms)->sendOtherReseller(
                                $client,
                                $reseller_sms_getway->sms_gateway,
                                $reseller_sms_getway->reseller->name,
                                $reseller_sms_getway->reseller->contact,
                                $expire_customer_sms->sms_body,
                                $reseller_sms_getway->reseller->id
                            );
                        }
                    }
                } else {
                    if (useResellerSmsGatewayForOwnWhenMainEnabled($client)) {
                        $reseller_sms_getway = ResellerSmsGetway::with('reseller')->where('reseller_id', $client->pop->reseller_id)->first();
                        if ($reseller_sms_getway) {
                            $expire_customer_sms = collect(json_decode($reseller_sms_getway->sms_formate))->where('sms_type', 'own_reseller_customer_expire')->first();
                            if ($expire_customer_sms && $expire_customer_sms->send_sms == "Yes") {
                                (new ExpireCustomerNotifySms)->sendOtherReseller(
                                    $client,
                                    $reseller_sms_getway->sms_gateway,
                                    $reseller_sms_getway->reseller->name,
                                    $reseller_sms_getway->reseller->contact,
                                    $expire_customer_sms->sms_body,
                                    $reseller_sms_getway->reseller->id
                                );
                            }
                        }
                    } else {
                        sendSmsAfterExpired($client->id);
                    }
                }
            } else {
                if (checkSettings('main_sms_gateway_for_own_other') == 'enable') {
                    if (useResellerSmsGatewayForOwnWhenMainEnabled($client)) {
                        $reseller_sms_getway = ResellerSmsGetway::with('reseller')->where('reseller_id', $client->pop->reseller_id)->first();
                        if ($reseller_sms_getway) {
                            $expire_customer_sms = collect(json_decode($reseller_sms_getway->sms_formate))->where('sms_type', 'other_reseller_customer_expire')->first();
                            if ($expire_customer_sms && $expire_customer_sms->send_sms == "Yes") {
                                (new ExpireCustomerNotifySms)->sendOtherReseller(
                                    $client,
                                    $reseller_sms_getway->sms_gateway,
                                    $reseller_sms_getway->reseller->name,
                                    $reseller_sms_getway->reseller->contact,
                                    $expire_customer_sms->sms_body,
                                    $reseller_sms_getway->reseller->id
                                );
                            }
                        }
                    } else {
                        sendSmsAfterExpired($client->id);
                    }
                } else {
                    $reseller_sms_getway = ResellerSmsGetway::with('reseller')->where('reseller_id', $client->pop->reseller_id)->first();
                    if ($reseller_sms_getway) {
                        $expire_customer_sms = collect(json_decode($reseller_sms_getway->sms_formate))->where('sms_type', 'other_reseller_customer_expire')->first();
                        if ($expire_customer_sms->send_sms == "Yes") {
                            (new ExpireCustomerNotifySms)->sendOtherReseller(
                                $client,
                                $reseller_sms_getway->sms_gateway,
                                $reseller_sms_getway->reseller->name,
                                $reseller_sms_getway->reseller->contact,
                                $expire_customer_sms->sms_body,
                                $reseller_sms_getway->reseller->id
                            );
                        }
                    }
                }
            }
        }
    }

    public function sendSmsToDueCustomer(Request $request)
    {
        if ($request->billing_cycle == null || $request->status == null || $request->message == null) {
            $res['error'] = 'Required all input';
            return response()->json($res);
        } else {

            if ($request->pop_id == 'all') {

                $pop_ids = Pop::where('reseller_id', $request->reseller_id)->pluck('id');
                if ($request->billing_cycle[0] == 'all') {
                    $clients = Client::with('pop', 'clientsinfo:id,client_id,contact_no,clients_name', 'customerAccount:id,client_id,dueAmount')
                        ->whereHas('customerAccount', function ($query) use ($request) {
                            $query->where('dueAmount', '>', 0);
                        })
                        ->whereHas('pop', function ($query) use ($request) {
                            $query->where('sms_send', 'yes')->where('bill_generate', 'yes');
                        })
                        ->whereIn('pop_id', $pop_ids)
                        ->whereIn('clients_status', $request->status);
                } else {
                    $clients = Client::with('pop', 'clientsinfo:id,client_id,contact_no,clients_name', 'customerAccount:id,client_id,dueAmount')
                        ->whereHas('customerAccount', function ($query) use ($request) {
                            $query->where('dueAmount', '>', 0);
                        })
                        ->whereHas('pop', function ($query) use ($request) {
                            $query->where('sms_send', 'yes')->where('bill_generate', 'yes');
                        })
                        ->whereIn('billing_cycle', $request->billing_cycle)
                        ->whereIn('pop_id', $pop_ids)
                        ->whereIn('clients_status', $request->status);
                }
            } else {
                if ($request->billing_cycle[0] == 'all') {
                    $clients = Client::with('pop', 'clientsinfo:id,client_id,contact_no,clients_name', 'customerAccount:id,client_id,dueAmount')
                        ->whereHas('customerAccount', function ($query) use ($request) {
                            $query->where('dueAmount', '>', 0);
                        })
                        ->whereHas('pop', function ($query) use ($request) {
                            $query->where('sms_send', 'yes')->where('bill_generate', 'yes');
                        })
                        ->where('pop_id', $request->pop_id);
                } else {
                    $clients = Client::with('pop', 'clientsinfo:id,client_id,contact_no,clients_name', 'customerAccount:id,client_id,dueAmount')
                        ->whereHas('customerAccount', function ($query) use ($request) {
                            $query->where('dueAmount', '>', 0);
                        })
                        ->whereHas('pop', function ($query) use ($request) {
                            $query->where('sms_send', 'yes')->where('bill_generate', 'yes');
                        })
                        ->where('pop_id', $request->pop_id)
                        ->whereIn('billing_cycle', $request->billing_cycle);
                }
            }
            if ($request->areas) {
                if (in_array('all', $request->areas)) {
                    $clients = $clients;
                } else {
                    $clients = $clients->whereHas('clientsinfo', function ($query) use ($request) {
                        $query->whereIn('area', $request->areas);
                    });
                }
            }
            if (in_array("all", $request->status)) {
                $clients = $clients;
            } else {
                $clients = $clients->whereIn('clients_status', $request->status);
            }
            $clients = $clients->get();
            $total_count = 0;
            foreach ($clients as $client) {
                if ($client->clientsinfo->contact_no != null) {
                    $sms_send = new DueCustomerSms();
                    $sms_send->sendSms($client, $request->message);
                    $total_count++;
                }
            }
            $res['success'] = 'Total Users: ' . $total_count . '. All Process In Queue';
            return response()->json($res);
        }
    }
}
