<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Services\ExpirationService;
use Brian2694\Toastr\Facades\Toastr;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
class RadiusTableController extends Controller
{
    public function checkInRedcheck()
    {
        if(auth()->user()->id == 1){
            return view('radiusTable.redcheck');
        }

    }

    public function searchInRedcheck(Request $request){

        $user = DB::table('radcheck')->where('username', $request->userid)->get();
        $reduser_group = DB::table('radusergroup')->where('username', $request->userid)->get();
        $data=[
            'users' => $user,
            'reduser_group' => $reduser_group,
        ];

        return view('radiusTable.resultredcheck',$data);

    }

    public function editRedcheck($id)
    {
        $user = DB::table('radcheck')->where('id', $id)->first();
        $data=[
            'user' => $user
        ];
        if(auth()->user()->id == 1){
            return view('radiusTable.editredcheck',$data);
        }
    }

    public function updateRedcheck(Request $request, $id){

        try{
            $user = DB::table('radcheck')->where('id', $id)->update([
                'username' => $request->user_name,
                'attribute' => $request->attribute,
                'op' => $request->op,
                'value' => $request->value,
            ]);
            // dd("comes");
            Toastr::success('User Updated Successfully In redcheck table', 'Success');
            return redirect()->back();

        }catch(\Exception $e){
            Toastr::error('Something went wrong', 'Error');
            dd($e);
            return redirect()->back();
        }

    }

    public function isClientDisableOrDeactive(Client $client){
        return $client->clients_status == 'disable' || $client->clients_status == 'deactive';
    }

    public function makeFirstRowDisable($userId,$password){
        $firstRow = DB::table('radcheck')->where('username', $userId)->where('attribute','Cleartext-Password')->first();
        if($firstRow == null){

            DB::table('radcheck')->insert([
                'username' => $userId,
                'attribute' => 'Cleartext-Password',
                'op' => globalPermission('RadiusExpiration') ? ':=' : '!=',
                'value' => $password
            ]);
        }else if($firstRow->op == ':='){
            DB::table('radcheck')->where('username', $userId)->where('attribute','Cleartext-Password')->update([
                'op' => globalPermission('RadiusExpiration') ? ':=' : '!=',
            ]);
        }
    }

    public function makeSecondRowDisable($userId,$nasname){
        $secondRow = DB::table('radcheck')->where('username', $userId)->where('attribute','NAS-IP-Address')->first();

        if($secondRow == null){

            DB::table('radcheck')->insert([
                'username' => $userId,
                'attribute' => 'NAS-IP-Address',
                'op' => globalPermission('RadiusExpiration') ? ':=' : '!=',
                'value' => $nasname
            ]);
        }else if($secondRow->op == ':='){
            DB::table('radcheck')->where('username', $userId)->where('attribute','NAS-IP-Address')->update([
                'op' => globalPermission('RadiusExpiration') ? ':=' : '!=',
            ]);
        }
    }

    public function makeFirstRowEnable($userId,$password)
    {
        $firstRow = DB::table('radcheck')->where('username', $userId)->where('attribute','Cleartext-Password')->first();
        if($firstRow == null){

            DB::table('radcheck')->insert([
                'username' => $userId,
                'attribute' => 'Cleartext-Password',
                'op' => ':=',
                'value' => $password
            ]);
        }else if($firstRow->op == '!='){
            DB::table('radcheck')->where('username', $userId)->where('attribute','Cleartext-Password')->update([
                'op' => ':=',
            ]);
        }

    }

    public function makeSecondRowEnable($userId,$nasname)
    {
        $user2 = DB::table('radcheck')->where('username', $userId)->where('attribute','NAS-IP-Address')->first();
        if($user2 == null){

            DB::table('radcheck')->insert([
                'username' => $userId,
                'attribute' => 'NAS-IP-Address',
                'op' => ':=',
                'value' => $nasname
            ]);
        }else if($user2->op == '!='){
            DB::table('radcheck')->where('username', $userId)->where('attribute','NAS-IP-Address')->update([
                'op' => ':=',
            ]);
        }
    }

    public function crateRecordRadiusUserGroup($userId,$packageId)
    {

        $radiusUserGroupRecord = DB::table('radusergroup')->where('username', $userId)->first();


            DB::table('radusergroup')->updateOrInsert(
                ['username' => $userId], // where clause
                [
                    'groupname' => $packageId,
                    'priority' => 1
                ] // values to update/insert
            );

    }



    public function addredcheck(Request $request)
    {
        if(globalPermission('RadiusExpiration')){

            (new ExpirationService())->syncExpiration($request->userid);
        }

            $isClientValid = Client::with('pops.nas','packages')->where('userid', $request->userid)->first();
            if($isClientValid){
                $client = $isClientValid;
                $expire_date = Carbon::parse($client->expire_date)->addDay($client->payment_dadeline)->format('Y-m-d 00:00:00');
                $today = Carbon::parse(today())->format('Y-m-d 00:00:00');
                if($this->isClientDisableOrDeactive($client)){

                    $this->makeFirstRowDisable($client->userid,$client->password);
                    $this->makeSecondRowDisable($client->userid,$client->pops->nas->nasname);

                    $data=[
                        'message' => "User Not Found",
                    ];
                    return $data;
                }

                if( ($expire_date >= $today) || $client->pops->experity_check == "Yes"){

                    $this->makeFirstRowEnable($request->userid,$client->password);
                    $this->makeSecondRowEnable($request->userid,$client->pops->nas->nasname);
                    $this->crateRecordRadiusUserGroup($request->userid, $client->packages->id);



                    $only_expire_date = Carbon::parse($client->expire_date)->format('Y-m-d 00:00:00');

                    if($client->pops->experity_check != "Yes" && $only_expire_date >= $today){
                        $client->clients_status = "active";
                        $client->save();
                    }


                    $user = DB::table('radcheck')->where('username', $request->userid)->get();
                    $reduser_group = DB::table('radusergroup')->where('username', $request->userid)->get();

                    $data=[
                        'users' => $user,
                        'reduser_group' => $reduser_group,
                        'message' => "User Added Successfully In Redcheck Table",
                    ];

                    return view('radiusTable.resultredcheck',$data);
                }else{

                    $only_expire_date = Carbon::parse($client->expire_date)->format('Y-m-d 00:00:00');
                    if($client->pops->experity_check != "Yes" && $only_expire_date < $today ){
                        $client->clients_status = "expired";
                        $client->save();
                    }


                    $this->makeFirstRowDisable($client->userid,$client->password);
                    $this->makeSecondRowDisable($client->userid,$client->pops->nas->nasname);


                    $user = DB::table('radcheck')->where('username', $request->userid)->get();
                    $reduser_group = DB::table('radusergroup')->where('username', $request->userid)->get();

                    $data=[
                        'users' => $user,
                        'reduser_group' => $reduser_group,
                        'message' => "User Added Successfully In Redcheck Table",
                    ];

                    return view('radiusTable.resultredcheck',$data);
                }

            }else{
                $data=[
                    'message' => "User Not Found",
                ];
                return $data;
            }


    }


    public function editRedUserGroup($id)
    {
        $user = DB::table('radusergroup')->where('id', $id)->first();
        $data=[
            'user' => $user
        ];
        if(auth()->user()->id == 1){
            return view('radiusTable.editRedUserGroup',$data);
        }
    }


    public function updateRedUserGroup(Request $request, $id){

        try{
            $user = DB::table('radusergroup')->where('id', $id)->update([
                'username' => $request->user_name,
                'groupname' => $request->groupname,
                'priority' => $request->priority,

            ]);

            Toastr::success('User Updated Successfully In radusergroup table', 'Success');
            return redirect()->back();

        }catch(\Exception $e){
            Toastr::error('Something went wrong', 'Error');
            dd($e);
            return redirect()->back();
        }

    }

    public function destroyReduserGroup($id)
    {
        $user = DB::table('radusergroup')->where('id', $id)->delete();
        Toastr::success('User Deleted Successfully In radusergroup table', 'Success');
        return redirect()->back();
    }

    public function destroyRedcheck($id)
    {
        $user = DB::table('radcheck')->where('id', $id)->delete();
        Toastr::success('User Deleted Successfully In radcheck table', 'Success');
        return redirect()->back();
    }
}
