<?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\BillGenerate as ModelsBillGenerate;
use App\Models\Billpayment;
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;
use App\Models\BillGenerate;


class ClientApproveService
{

    use AuthorizesRequests;

    public static function approveClients($ids, $autoApprove = false)
    {
        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') {

                    if (!$autoApprove) {
                        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);
                    (new RadiusClientSync)->syncSingleRadiusClient($client->id);

                    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
                            ]);
                        } else {
                            // check if user has due amount
                            if (globalPermission('check-due-amount-for-customer-approval')) {

                                // check new client entry bill and otc bill
                                $bill_generate_amount = BillGenerate::where('client_id', $client->id)
                                    ->whereIn('billing_type', ['new', 'otc'])
                                    ->get()
                                    ->sum('bill_amount');

                                $total_paid_amount = Billpayment::where('client_id', $client->id)->get()->sum('paid_amount');

                                $due_amount = $bill_generate_amount - $total_paid_amount;

                                if ($due_amount > 0) {
                                    throw new \Exception("User has due amount. Please pay otc and new customer entry bill first. Due amount: " . $due_amount);
                                }
                            }
                        }
                    }
                    

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