<?php

namespace App\Http\Controllers;

use App\Models\Client;
use App\Models\Pop;
use Brian2694\Toastr\Facades\Toastr;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class RadcheckUserController extends Controller
{
    public function index()
    {

        return view('radcheckuser.index');
    }

    public function radUserUpdate(Request $request)
    {
        // dd($request->all());
        if ($request->ajax()) {

            $pop_ids = Pop::where('reseller_id', $request->reseller)->pluck('id')->toArray();

            if ($request->reseller != 'all') {

                if ($request->pop == 'all') {

                    $list = Client::with('pop', 'nas')->whereIn('pop_id', $pop_ids)->get();
                }

                if ($request->pop != 'all') {

                    $list = Client::with('pop', 'nas')->where('pop_id', $request->pop)->get();
                }
            }

            echo 'process start';
            echo '<br>';

            foreach ($list as $l) {
                echo 'process start for ' . $l->userid . '<br>';
                
                if ($l->clients_status == 'active' || $l->clients_status == 'disable' || $l->clients_status == 'expired') {

                    DB::table('radcheck')->where('username', $l->userid)->delete();

                    DB::table('radcheck')->insert([
                        'username' => $l->userid,
                        'attribute' => 'Cleartext-Password',
                        'op' => ':=',
                        'value' => $l->password
                    ]);

                    DB::table('radcheck')->insert([
                        'username' => $l->userid,
                        'attribute' => 'NAS-IP-Address',
                        'op' => ':=',
                        'value' => $l->pop->nas->nasname
                    ]);
                } else {

                    DB::table('radcheck')->where('username', $l->userid)->delete();
                }
            }
            echo 'process stop';
            echo '<br>';
            Toastr::success('Radcheck User Updated Successfully', 'Success');
        }
    }
}
