<?php

namespace App\Http\Controllers;

use App\Classes\Accounting\Accounting;

use App\Jobs\StoreClientDownLoadUploadJob;
use App\Jobs\UserRedcheckUpdateJob;
use App\Models\ApiBandwidthUsage;
use App\Models\Client;
use App\Models\RadiusLog;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;

class RadiusLogController extends Controller
{



    public function userUpdate()
    {
        // dd("user update");
        $list = DB::table('clients')
            ->leftJoin('pops', 'pops.id', '=', 'clients.pop_id')
            ->leftJoin('nas', 'nas.id', '=', 'pops.nas_id')
            ->select('clients.userid', 'clients.password', 'nas.nasname', 'clients.clients_status', 'clients.deleted_at')
            ->OrderbY('clients.id')->chunk(1000, function ($lists) {
                UserRedcheckUpdateJob::dispatch($lists);
            });
    }

    public function getCustomerLogHistory($client_id)
    {
        $currentDate = today()->endOfDay();



        $client = Client::withTrashed()->where('id', $client_id)->first();
        $id = $client->userid;

        if ($currentDate->day < $client->billing_cycle) {
            $prevExpDate = Carbon::createFromDate(today()->year, today()->month, $client->billing_cycle)->subMonth()->endOfDay();
        } else {
            $prevExpDate = Carbon::createFromDate(today()->year, today()->month, $client->billing_cycle)->endOfDay();
        }

        $start = $prevExpDate;
        $end = $currentDate;



        if (!checkAPI()) {

            $accounting = new Accounting();

            $list = $accounting->singleUserLogRecord(
                $id,
                Carbon::parse($prevExpDate)->format('Y-m-d 00:00:00'),
                Carbon::parse($currentDate)->format('Y-m-d 00:00:00')
            );

            // sort collection by acctstoptime descending
            $list = $list->sortByDesc('acctstoptime');

            return view('clients.logHistoryCustomer', [
                'list' => $list,
                'page_title' => 'Online Customer List',
                'start' => $start,
                'end'   => $end,
                'client' => $id
            ]);
        }

        if (checkAPI()) {
            $prevExpDate = Carbon::parse($prevExpDate)->format('Y-m-d 00:00:00');
            $currentDate = Carbon::parse($currentDate)->format('Y-m-d 23:59:59');
            $list = ApiBandwidthUsage::where('username', $id)
                ->whereBetween('session_start_time', [$prevExpDate, $currentDate])
                ->orderBy('id', 'desc')
                ->get();

            $data = [
                'list' => $list,
                'page_title' => 'Online Customer List',
                'start' => $start,
                'end'   => $end,
                'client' => $id
            ];

            return view('clients.apiBandwidthUsage.session', $data);
        }
    }

    public function logeSearchResult(Request $request)
    {
        // dd($request->all());
        if ($request->ajax()) {
            $from = Carbon::parse($request->from_date)->format('Y-m-d 00:00:00');
            $to = Carbon::parse($request->to_date)->format('Y-m-d 23:59:59');




            if (!checkAPI()) {

                $list = collect();

                if ($request->from_date != null && $request->to_date != null) {
                    $accounting = new Accounting();
                    $list = $accounting->singleUserLogRecord($request->username, $from, $to)
                        ->sortByDesc('acctstoptime'); // collection sorting
                }

                return view('clients.logSearch', [
                    'list' => $list,
                ]);
            }

            if (checkAPI()) {
                $list = ApiBandwidthUsage::where('username', $request->username)
                    ->whereBetween('session_start_time', [$from, $to])
                    ->orderBy('id', 'desc')
                    ->get();

                $data = [
                    'list' => $list,
                    'page_title' => 'Online Customer List',
                    'start' => $from,
                    'end'   => $to,
                    'client' => $request->username
                ];

                return view('clients.apiBandwidthUsage.search', $data);
            }
        }
    }

    public function saveRadiusLogToClientTableCommand()
    {


        $all_clients = Client::select('id', 'userid', 'billing_cycle')->get();

        $all_clients->chunk(1)->each(function ($clients) {
            StoreClientDownLoadUploadJob::dispatch($clients)->onQueue('user_log_queue');
        });
    }

    public function saveRadiusLogToClientTable($clients)
    {

        foreach ($clients as $client) {
            try {

                $billing_cycle = $client->billing_cycle;
                $today_only_day = today()->day;
                if ($today_only_day > $billing_cycle) {
                    $get_date = Carbon::createFromDate(today()->year, today()->month, $billing_cycle);
                } else {
                    $get_date = Carbon::createFromDate(today()->year, today()->month, $billing_cycle)->subMonth();
                }

                $from_date = Carbon::parse($get_date)->format('Y-m-d 00:00:00');
                $to_date = Carbon::parse(today())->format('Y-m-d 23:59:59');

                $accounting = new Accounting();
                $list = $accounting->singleUserLog($client->userid, $from_date, $to_date);

                // Initialize total upload and download
                $total_upload = $list["upload"] / 8388608; // Convert bytes to MB
                $total_download = $list["download"] / 8388608; // Convert bytes to MB



                // Round and update client's bandwidth in the database
                Client::where('userid', $client->userid)->update([
                    'up_bandwidth' => round($total_upload),
                    'down_bandwidth' => round($total_download),
                ]);


                Log::error($client->userid);
                Log::error($total_upload);
                Log::error($total_download);
            } catch (\Exception $e) {
                Log::error($e->getMessage());
            }
        }
    }
}
