<?php

namespace App\Http\Controllers\Clients;

use App\Classes\BillgenerateUpdate;
use App\Models\Client;
use App\Models\Income;
use App\Models\Balance;
use App\Models\IncomeHead;
use App\Models\Clientsinfo;
use Illuminate\Http\Request;
use App\Services\ExpireCheck;
use App\Models\UserAccounting;
use App\Models\CustomerAccount;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Support\Facades\Auth;
use App\Models\ReselleBalanceLogReport;
use Illuminate\Support\Facades\Artisan;
use App\Http\Controllers\PaymentController;
use App\Models\SubResellerBalanceLogReport;
use Brian2694\Toastr\Toastr as ToastrToastr;
use App\Http\Controllers\BillGenerateController;
use App\Jobs\BillGenerateUpdateJob;
use App\Models\Pop;

class OtcController extends Controller
{
    public function addOtc(Request $request)
    {
        // dd($request->all());
        $otc = $request->otc_amount;
        $client_id = $request->id;

        $client = Client::with('pop')->find($request->id);

        $reseller_balance =  ExpireCheck::getResellerBalance('reseller', $client->pop->reseller_id);
        $sub_reseller_balance =  ExpireCheck::getResellerBalance('pop', $client->pop_id);


        if ($client->pop->billable == 'yes') {

            if ($otc > $reseller_balance) {

                Toastr::error('Not Enough Balance On Reseller Account', 'error');
                return redirect()->back();
            }

            if ($client->pop->subreseller == 'yes' && $otc > $sub_reseller_balance) {

                Toastr::error('Not Enough Balance On Account', 'error');
                return redirect()->back();
            }
        }




        DB::beginTransaction();
        try {

            $clientsinfo = Clientsinfo::where('client_id', $client_id)->first();
            $clientsinfo->otc = $otc;
            $clientsinfo->otc_due = checkSettings('otc-auto-due') == 'enable' ? $otc : 0;
            $clientsinfo->save();

            if ($otc != null && $otc > 0 && checkSettings('otc-auto-due') == 'disable'  && !globalPermission('check_client_balance_before_package_billing_date_change')) {

                $actions = 'New User create. OTC Collect. ' . $otc . 'TK for customer ' . $request->userid;
                UserAccounting::userAcStore($otc, $actions, $client_id, '', 'otc');

            }

            // add otc to income table
            if(checkSettings('otc-auto-due') == 'disable' && !globalPermission('check_client_balance_before_package_billing_date_change')){
                $income_type = IncomeHead::find(2);
                $income = Income::create([
                    'name' => $income_type->name,
                    'date' => now(),
                    'amount' => $otc,
                    'description' => 'Bill Payment for customer : ' . $client->userid,
                    'incomeHead' => $income_type->id
                ]);
            }



            if ($client->pop->billable == 'yes'  && !globalPermission('check_client_balance_before_package_billing_date_change')) {

                Balance::balanceDeductForUserRecharge('reseller', $client->pop->reseller_id, $otc);
                $pop = Pop::with('reseller')->find($client->pop_id);
                $resellerBalanceLogReport = ReselleBalanceLogReport::create(
                    [
                        'reseller_id' => $client->pop->reseller_id,
                        'client_id' => $client_id,
                        'action' => 'New OTC added cost '.$otc,
                        'amount' => $otc,
                        'remarks' => 'Created BY ' . Auth::user()->email,
                        'uniqueId'     => createUUID(),
                        'pop_id'       => $client->pop_id,
                        'commission_amount' => getCommissionForResellerRecharge($client_id,$otc),
                        'reseller_commission_percentage' => $pop->reseller->commission_percentage,
                        'pop_commission_percentage' => $pop->commission_percentage,
                    ]
                );

                if ($client->pop->subreseller == 'yes') {

                    Balance::balanceDeductForUserRecharge('pop', $client->pop->id, $otc);

                    SubResellerBalanceLogReport::create(
                        [
                            'reseller_id' => $client->pop->reseller_id,
                            'sub_reseller_id' => $client->pop->id,
                            'client_id' => $client_id,
                            'action' => 'New OTC added cost '.$otc,
                            'amount' => $otc,
                            'remarks' => 'Created BY ' . Auth::user()->email,
                            'reseller_cost' => $otc,
                            'commission_amount' => getCommissionForSubResellerRecharge($client_id,$otc,),
                            'reseller_balance_log_id'     => $resellerBalanceLogReport->id,
                        ]
                    );

                }
            }



            if ($client->pop->bill_generate == 'yes') {

                CustomerAccount::updateCustomrAccount($client_id, $otc, 0, 0, $otc);

                BillGenerateController::entryBillGenerate(
                    $client_id,
                    $otc,
                    'New Customer OTC',
                    'otc',
                    ''
                );

                if (checkSettings('otc-auto-due') == 'disable' && !globalPermission('check_client_balance_before_package_billing_date_change')) {
                    (new PaymentController)->newUserOTCPaymentProcess($client_id, $otc ,$income->id);
                }

            }

            Artisan::call('cache:clear');

            DB::commit();

            try {
                BillGenerateUpdateJob::dispatch($client->id);


            } catch (\Throwable $th) {
                //throw $th;
            }

            Toastr::success('Otc Added Successfully','success');
            return redirect()->back();

        } catch (\Throwable $th) {

            DB::rollBack();
            dd($th);
            Toastr::error('Something is worng please contact Admin','error');
            return redirect()->back();
            //throw $th;
        }

    }
}
