<?php

namespace App\Services;

use Carbon\Carbon;
use App\Models\BillGenerate;
use App\Models\FundTransfer;
use App\Models\CustomerAccount;
use Illuminate\Support\Facades\DB;
use App\Classes\BillgenerateUpdate;
use App\Models\ResellerCommissionReference;
use App\Models\SubResellerCommissionReference;
use App\Http\Controllers\BillGenerateController;
use Illuminate\Support\Facades\Log;

class GenerateMonthlyBill
{

    public function generate($user, $bill_month = null)
    {

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

        $genbill = BillGenerate::where('client_id', $user->id)
            ->whereMonth('created_at', '=', $request_month->format('m'))
            ->whereYear('created_at', '=', $request_month->format('Y'))
            ->where('billing_type', 'monthly')
            ->orderBy('id', 'desc')
            ->first();


        if (empty($genbill)) {

            DB::beginTransaction();
            try {

                $rate = $user->packages->package_rate - $user->parmanent_discount;

                $cac = CustomerAccount::whereClient_id($user->id)->firstOrCreate(['client_id' => $user->id]);

                if ($cac->dueAmount < 0 && abs($cac->dueAmount) >= $rate) {

                    BillGenerateController::updateExpireAndCustomer($user, $rate);
                    $remark = 'Monthly Bill Generate: User Has Advanced Balance: ' . ($rate);
                    BillGenerateController::entryBillGenerate($user->id, $rate, $remark, 'monthly', $user->expire_date, $user->payment_discount, $user->parmanent_discount, $user->packages->package_name, $user->packages->package_rate, $request_month);
                    try{
                        (new BillgenerateUpdate)->update($user->id);
                    }catch(\Exception $e){
                        Log::error($e->getMessage());
                    }
                } else {

                    if ($rate > 0  && getBillingType() != 'day_to_day' && siteinfo()->day_to_day_after_10_days != 'Yes') {
                        CustomerAccount::updateCustomrAccount($user->id, $rate, 0, 0, $rate);
                        BillGenerateController::entryBillGenerate($user->id, $rate, 'Monthly Bill Generate', 'monthly', $user->expire_date, 0, $user->parmanent_discount, $user->packages->package_name, $user->packages->package_rate, $request_month);
                    }
                }
                DB::commit();
            } catch (\Exception $e) {
                Log::error($e->getMessage());
            }

            return 'success';
        } else {
            return 'error';
        }
    }
}
