<?php

namespace App\Http\Controllers\Billing;

use App\Models\Pop;
use App\Models\Client;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use App\Models\Radcheck;
use App\Services\BillingCycleChange;

class UserBillCycleChangeController extends Controller
{
    public function userBillingCycleChange(Request $request)
    {

        // dd($request->all());


        if (!empty($request->id) && !empty($request->billCycle)) {

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

            if (checkSettings('expire_billing_change_today_from_billing_date') != 'enable') {
                
                if ($user->client_status == 'expired' || $user->client_status == 'deactive' || now()->subMonth() > $user->expire_date) {
                    return redirect()->back()->with('error_message', 'Customer Expired or Deactivated or expired one month older');
                }
            }



            if ($request->billCycle == $user->billing_cycle) {
                return redirect()->back()->with('error_message', 'Select a Different Billing Cycle Date');
            }

            DB::beginTransaction();

            try {

                $status = (new BillingCycleChange)->billingCycleChange($user->pop, $user, $request->billCycle);

                // dd($status);

                if ($status == 'error') {

                    return redirect()->route('billingCycleChange')->with('error_message', 'Not Enough Balance..');
                } elseif ($status == 'success') {

                    $user->clients_status = 'active';
                    $user->save();

                    DB::table('radcheck')
                        ->whereUsername($user->userid)
                        ->update([
                            'op' => ':='
                        ]);
                }

                if ($status == 'balance_error') {
                    return redirect()->route('billingCycleChange')->with('error_message', 'Not Enough Balance..');
                }

                DB::commit();
                return redirect()->back()->with('success_message', 'Bill Cycle Changed Successfully');
            } catch (\Throwable $th) {
                dd($th);
                DB::rollBack();
            }
        } else {

            return redirect()->back();
        }
    }
}
