<?php

namespace App\Http\Controllers\Clients;

use Exception;
use App\Models\Nas;
use App\Models\Pop;
use App\Models\Client;
use App\Models\Packages;
use App\Models\Radcheck;
use App\Models\Reseller;
use App\Classes\MikrotikService\Mikrotik;
use App\Classes\MikrotikService\SyncWithMk;
use Illuminate\Http\Request;
use App\Classes\Notification;
use App\Models\ClientEditLog;
use App\Classes\SMS\WelcomeSms;
use App\Http\Controllers\ClientController;
use App\Models\ResellerSmsGetway;
use App\Models\CompanyInformation;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\Http\Controllers\Controller;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Support\Facades\Auth;
use App\Http\Controllers\PaymentController;
use App\Models\CustomerAccount;
use App\Models\User_log;
use App\Services\ClientApproveService;
use App\Services\ExpirationService;
use Carbon\Carbon;
use App\Exports\PendingClientExport;
use Maatwebsite\Excel\Facades\Excel;

class PendingClientController extends Controller
{

    public function pendingCustomer()
    {
        if (checkSettings('local-user-first-approve') == 'enable') {

            if (auth()->user()->can('local-user-first-approve')) {

                $list = Client::list('approved')->where('first_approval', 'Pending');
            } else {

                $list = Client::list('pending'); //->where('first_approval', 'Approved');
            }
        } else {
            $list = Client::list('pending');
        }


        return view('clients.pending', [
            'page_title' => 'Pending Customer List',
            'list' => $list->paginate(500),
            'reseller'   =>  Reseller::resellerList()->get(),
        ]);
    }

    public function pendingCustomerSearch(Request $request)
    {
        if ($request->ajax()) {
            // Store search parameters in session for export
            session()->put('pendingCustomerSearchArgument', $request->all());

            $list = Client::list('pending');

            if ($request->reseller != "null" && $request->pop != "all") {
                $list->where('pop_id', $request->pop);
            }
            if ($request->reseller != "null" && $request->pop == "all") {
                $reseller_pop = Pop::where('reseller_id', $request->reseller)->get()->pluck('id');
                $poplist = userPops()->whereIn('id', $reseller_pop)->pluck('id');
                $list->whereIn('pop_id', $poplist);
            }

            if ($request->package != "null") {
                $list->where('package_id', $request->package);
            }

            return view('clients.customer_search', [
                'list' =>  $list->get(),
            ]);
        }
    }

    public function pendingCustomerExport(Request $request)
    {
        $searchParams = $request->session()->get('pendingCustomerSearchArgument');

        if (!$searchParams) {
            // If no search parameters, export all pending customers
            $list = Client::list('pending')->with('adminUser')->get();
        } else {
            // Apply the same filters as search
            $list = Client::list('pending')->with('adminUser');

            if (isset($searchParams['reseller']) && $searchParams['reseller'] != "null" && isset($searchParams['pop']) && $searchParams['pop'] != "all") {
                $list->where('pop_id', $searchParams['pop']);
            }
            if (isset($searchParams['reseller']) && $searchParams['reseller'] != "null" && isset($searchParams['pop']) && $searchParams['pop'] == "all") {
                $reseller_pop = Pop::where('reseller_id', $searchParams['reseller'])->get()->pluck('id');
                $poplist = userPops()->whereIn('id', $reseller_pop)->pluck('id');
                $list->whereIn('pop_id', $poplist);
            }

            if (isset($searchParams['package']) && $searchParams['package'] != "null") {
                $list->where('package_id', $searchParams['package']);
            }

            $list = $list->get();
        }

        $fileName = 'pending_customers_' . date('Y_m_d_H_i_s') . '.xlsx';
        return Excel::download(new PendingClientExport($list), $fileName);
    }

    public function approveApiUser($pop_users, $pop_id)
    {
        foreach ($pop_users as $user) {
            $user_log = new User_log();
            $client = Client::with('pops')->find($user->id);
            if (!auth()->user()->can('approve-local-customer') && $user->pop->bill_generate == 'yes') {
               throw new \ErrorException('Not Enough Permission!!');
            }
            DB::beginTransaction();
            try {
                if (getBillingType() == 'day_to_day'){
                    $today = Carbon::parse(today())->startOfDay();
                    $expire = Carbon::parse($client->expire_date)->endOfDay();
                    if($today->lessThan($expire)){
                        $status = 'active';
                    }else{
                        $status = 'deactive';
                    }
                }else{
                    $status = ($client->clients_status == 'disable') ? 'deactive' : 'active';
                }
                Client::where('id', $user->id)
                    ->update([
                        'client_approval' => 'approved',
                        'clients_status' => $status,
                    ]);
                $user_log->log_type = "id_approved";
                $user_log->user_id = auth()->user()->id;
                $user_log->details = "Client Created";
                $user_log->client_id = $client->id;
                $user_log->save();

                if ($client->pops->billable == 'yes') {
                    $checkCustomerAccount = CustomerAccount::where('client_id', $client->id)->get()->count();
                    if ($checkCustomerAccount <= 0) {
                        CustomerAccount::create([
                            'client_id'       => $client->id,
                            'totalPaid'       => 0,
                            'dueAmount'       => 0,
                            'totalDiscount'   => 0,
                            'totalBillAmount' => 0
                        ]);
                    }
                }
                (new ClientController)->slugInsert($user);
                $mikrotik = new SyncWithMk();
                $mikrotik->syncSingleClient($user->id);

                DB::commit();

                (new Notification)->notify("..::[Customer Approved]::..\n \nCustomer Username : " . $user->userid . " \nPassword : " . $user->password . "\n Approved By: " . Auth::user()->name . "\n \nThank You!!");

                // if ($user->pop->bill_generate == 'yes' && $user->pop->sms_send == 'yes') {
                    // if (checkSettings('new-user-create-sms') == 'enable' && $user->clientsinfo->contact_no != null) {
                        (new PendingClientController)->welcomeSms($client);
                    // }
                // }
            } catch (Exception $err) {
                DB::rollback();
               throw new \ErrorException($err->getMessage());
            }
        }
    }

    public function firstApproveAllPending(Request $request)
    {
        $ids = explode(',', $request->first_client_ids[0]);
        $clients = Client::with('pop', 'pop.nas', 'packages', 'clientsinfo')->whereIn('id', $ids)->get();

        foreach ($clients as $key => $value) {

            $old_client_data = Client::with('clientsinfo')->find($value->id);

            Client::where('id', $value->id)
                ->update([
                    'first_approval' => 'Approved',
                    // 'first_approve_by' => Auth::user()->id,
                ]);

            $new_client_data = Client::with('clientsinfo')->find($value->id);
            $this->clientEditLog($value, $old_client_data, $new_client_data);
        }

        Toastr::success('All Customer First Approved Successfull!!');
        return redirect()->back();
    }

    public function clientEditLog($client, $old_client, $new_data_client)
    {
        $client_update_log = new ClientEditLog();
        $client_update_log->client_id = $client->id;
        $client_update_log->user_id = Auth::user()->id;
        $client_update_log->old_data = json_encode($old_client);
        $client_update_log->new_data = json_encode($new_data_client);
        $client_update_log->save();
    }

    public function addInRadius($user)
    {
        if ($user->ip_address != null && strlen($user->ip_address) == 15) {
            DB::table('radreply')->insert([
                'username'  => $user->userid,
                'attribute' => 'Framed-IP-Address',
                'op'        => ':=',
                'value'     => $user->ip_address
            ]);

            DB::table('radreply')->insert([
                'username'  => $user->userid,
                'attribute' => 'Service-Type',
                'op'        => ':=',
                'value'     => 'Framed-User'
            ]);
        }

        DB::table('radcheck')
            ->updateOrInsert(
                [
                    'username' => $user->userid,
                    'attribute' => 'Cleartext-Password'
                ],
                [
                    'op' => getBillingType() == 'day_to_day' ? '!=' : ':=',
                    'value' => $user->password
                ]
            );

        DB::table('radcheck')
            ->updateOrInsert(
                [
                    'username' => $user->userid,
                    'attribute' => 'NAS-IP-Address'
                ],
                [
                    'op' => getBillingType() == 'day_to_day' ? '!=' : ':=',
                    'value' => $user->pop->nas->nasname
                ]
            );

            if(globalPermission('RadiusExpiration')){
                (new ExpirationService())->syncExpiration($user->userid);
            }

        DB::table('radusergroup')
            ->updateOrInsert(
                [
                    'username' => $user->userid,
                    'groupname' => $user->packages->id
                ],
                [
                    'priority' => 1
                ]
            );
    }

    public function approveAllPending(request $request)
    {
        // if (config('app.license_check') == true) {
        if (siteLicenseInfo() == "true" || config('app.license_check') == true) {
            if(license_check()['info']['client_type'] != "" && license_check()['info']['license_check'] != ""){
                if (license_check()['info']['client_limit'] != 0 && totalClientCount() > license_check()['info']['client_limit']) {
                    abort(403, 'Your Limit crosed. Please contact software vendor. your limit was ' . license_check()['info']['client_limit'] . '. ');
                }
            }
        }

        $ids = explode(',', $request->client_ids[0]);
        try {
            ClientApproveService::approveClients($ids);
            Toastr::success('All Customer Approved Successfull!!');
            return redirect()->back();
        } catch (\Throwable $th) {
            Toastr::error($th->getMessage(), 'Failed');
            return back();
        }

    }

    public function welcomesms($client)
    {
        if(globalPermission('customResellerSmsGatewaySetup')){

            if($client->pop->bill_generate == 'yes'){
                $reseller_sme_getway = getResellerSmsGateway($client);
                // if($client->id == 1){
                //         dd("You can't send welcome sms to this user",$reseller_sme_getway,"won");
                // }
                if ($reseller_sme_getway) {
                    $wellcome_sms = collect(json_decode($reseller_sme_getway->sms_formate))->where('sms_type', 'own_reseller_customer_create')->first();
                    if ($wellcome_sms->send_sms == "Yes") {
                            // dd("comes");
                            (new WelcomeSms)->sendOtherReseller(
                                $client,
                                $reseller_sme_getway->sms_gateway,
                                $reseller_sme_getway->reseller->name,
                                $reseller_sme_getway->reseller->contact,
                                $wellcome_sms->sms_body,
                                $reseller_sme_getway->reseller->id
                            );
                        }
                }
            }else{
                $reseller_sme_getway = getResellerSmsGateway($client);
                //  if($client->id == 1){
                //         dd("You can't send welcome sms to this user",$reseller_sme_getway,"other");
                // }
                if ($reseller_sme_getway) {
                    $wellcome_sms = collect(json_decode($reseller_sme_getway->sms_formate))->where('sms_type', 'other_reseller_customer_create')->first();
                    if ($wellcome_sms->send_sms == "Yes") {
                        (new WelcomeSms)->sendOtherReseller(
                            $client,
                            $reseller_sme_getway->sms_gateway,
                            $reseller_sme_getway->reseller->name,
                            $reseller_sme_getway->reseller->contact,
                            $wellcome_sms->sms_body,
                            $reseller_sme_getway->reseller->id
                        );
                    }
                }
            }
        }else{
            if (checkSettings('main_sms_gateway_for_own_other') == 'enable' && $client->pop->sms_send == 'yes') {
                if (checkSettings('new-user-create-sms') == 'enable' && $client->clientsinfo->contact_no != null) {
                    (new WelcomeSms)->send($client);
                }
            } else {
                if ($client->pop->bill_generate == 'yes' && $client->pop->sms_send == 'yes') {

                    if (checkSettings('new-user-create-sms') == 'enable' && $client->clientsinfo->contact_no != null) {
                        (new WelcomeSms)->send($client);
                    }
                } else {
                    $reseller_sme_getway = getResellerSmsGateway($client);
                    if ($reseller_sme_getway) {
                        $wellcome_sms = collect(json_decode($reseller_sme_getway->sms_formate))->where('sms_type', 'other_reseller_customer_create')->first();
                        if ($wellcome_sms->send_sms == "Yes") {
                            (new WelcomeSms)->sendOtherReseller(
                                $client,
                                $reseller_sme_getway->sms_gateway,
                                $reseller_sme_getway->reseller->name,
                                $reseller_sme_getway->reseller->contact,
                                $wellcome_sms->sms_body,
                                $reseller_sme_getway->reseller->id
                            );
                        }
                    }
                }
            }
        }
    }

    public function updateUserForRadius($userid)
    {
        DB::table('radcheck')
            ->whereUsername($userid)
            ->update([
                'op' => ':='
            ]);
    }

    public function insertUserForRadius($userid, $password, $package_id, $nasname)
    {
        DB::table('radcheck')->insert(
            [
                'username' => $userid,
                'attribute' => 'Cleartext-Password',
                'op' => ':=',
                'value' => $password
            ],
            [
                'username' => $userid,
                'attribute' => 'NAS-IP-Address',
                'op' => ':=',
                'value' => $nasname
            ]
        );
        DB::table('radusergroup')
            ->insert([
                'username' => $userid,
                'groupname' => $package_id,
                'priority' => 1
            ]);
    }

    public function insertStaticIpForRadius($userid, $ip_address)
    {
        DB::table('radreply')->insert(
            [
                'username'  => $userid,
                'attribute' => 'Framed-IP-Address',
                'op'        => ':=',
                'value'     => $ip_address
            ],
            [
                'username'  => $userid,
                'attribute' => 'Service-Type',
                'op'        => ':=',
                'value'     => 'Framed-User'
            ]
        );
    }

    public function accountsPendingCustomer()
    {
        if (checkSettings('local-user-first-approve') == 'enable') {
            if (auth()->user()->can('local-user-first-approve')) {
                $list = Client::list('pending');

                return view('clients.accountsPending', [
                    'page_title' => 'Pending Customer List',
                    'list' => $list->paginate(1000),
                    'reseller'   =>  Reseller::resellerList()->get(),
                ]);
            }else{
                return redirect()->route('pendingCustomer');
            }
        }else{
            return false;
        }
    }

    public function printClientCopy($id)
    {
        $client = Client::with('clientsinfo', 'packages', 'pops')->where('id', $id)->first(); //list('pending')->where('id', $id)->first();
        $date= today()->format('Y-m-d');
        return view('clients.createClientPrint', [
            'page_title' => 'Print Client Copy',
            'data' => $client,
            'date' => $date,
        ]);
    }

    public function deleteAllPending(Request $request)
    {
        $ids = explode(',', $request->delete_client_ids[0]);

        foreach ($ids as $id) {
            (new ClientController)->destroy($id);
        }

        Toastr::success('Customer Deleted Successfull!!');
        return redirect()->back();
    }

}
