<?php

namespace App\Services;

use App\Classes\Notification;
use App\Http\Controllers\ClientController;
use App\Http\Controllers\Clients\PendingClientController;
use App\Http\Controllers\Controller;
use App\Models\Client;
use App\Models\CustomerAccount;
use App\Models\User_log;
use Brian2694\Toastr\Facades\Toastr;
use Carbon\Carbon;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;


class ClientApproveService {

    use AuthorizesRequests;

    public static function approveClients($ids){
        if (checkAPI()) {

                $clients = Client::with('pop', 'pop.nas', 'packages', 'clientsinfo')->whereIn('id', $ids)->get();
                $popGroup = $clients->groupBy('pop_id');

                foreach ($popGroup as $pop_id => $pop_users) {
                    (new PendingClientController)->approveApiUser($pop_users, $pop_id);
                }

        } else {
            $clients = Client::with('pop', 'pop.nas', 'packages', 'clientsinfo')->whereIn('id', $ids)->get();
            foreach ($clients as $client) {
                DB::beginTransaction();

                if (!auth()->user()->can('approve-local-customer') && $client->pop->bill_generate == 'yes') {
                    throw new \Exception("You don't have permission to approve this client");
                }

                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', $client->id)
                        ->update([
                            'client_approval' => 'approved',
                            'clients_status' => $status,
                        ]);


                    $user_log = new User_log();

                    $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();

                    (new ClientController)->slugInsert($client);
                    (new PendingClientController)->addInRadius($client);

                    if ($client->pop->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
                            ]);
                        }
                    }


                    DB::commit();
                    try{
                        (new Notification)->notify("..::[Customer Approved]::..\n \nCustomer Username : " . $client->userid . " \nPassword : " . $client->password . "\n Approved By: " . Auth::user()->name . "\n \nThank You!!");
                    }catch (\Throwable $err){

                    }

                    try{
                        (new PendingClientController)->welcomeSms($client);
                    }catch (\Throwable $err){

                    }

                } catch (\Throwable $err) {

                    Log::channel('pending-approval')->error($err->getMessage());
                    DB::rollback();

                   throw new \Exception($err->getMessage());
                }

            }


        }
    }

}

