<?php

namespace App\Classes\OtherReseller;

use App\Jobs\ResellerClientBillPaymentSyncJob;
use App\Models\ResellerBillGenerate;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;

class MonthlyBillGenerateClass
{
    public function generate($user, $bill_month)
    {
        try {
            DB::transaction(function () use ($user, $bill_month) {
                $reseller_id = $user->pops->reseller_id;
                $client_id = $user->id;
                $amount = getResellerClientPaymentAmount($user);
                $paid_amount = 0;
                $due_amount = $amount;
                $description = 'Monthly Bill';
                $type = 'monthly';



                $request_month = now();
                if ($bill_month) {
                    $request_month = Carbon::parse($bill_month);
                }

                $checkThisMonthBill = ResellerBillGenerate::where('reseller_id', $reseller_id)
                        ->where('client_id', $client_id)
                        ->whereMonth('created_at', '=', $request_month->format('m'))
                        ->whereYear('created_at', '=', $request_month->format('Y'))
                        ->where('type', 'monthly')
                        ->orderBy('id', 'desc')
                        ->first();



                if (!$checkThisMonthBill && $amount > 0) {
                    $this->generateMonthlyBill($reseller_id,$client_id,$amount,$paid_amount,$due_amount,$description,$type);

                    if($user->customer_account_balance_reseller < 0){
                        ResellerClientBillPaymentSyncJob::dispatch($user->id);
                    }

                    $user->customer_account_balance_reseller = $user->customer_account_balance_reseller + $amount;
                    $user->save();

                }
            });
        } catch (\Exception $e) {

        }

    }

    public function generateMonthlyBill($reseller_id,$client_id,$amount,$paid_amount,$due_amount,$description,$type)
    {
        $resellerBillGenerate = new ResellerBillGenerate();
        $resellerBillGenerate->reseller_id = $reseller_id;
        $resellerBillGenerate->client_id = $client_id;
        $resellerBillGenerate->amount = $amount;
        $resellerBillGenerate->paid_amount = $paid_amount;
        $resellerBillGenerate->due_amount = $due_amount;
        $resellerBillGenerate->description = $description;
        $resellerBillGenerate->type = $type;
        $resellerBillGenerate->save();
    }

}
