<?php

namespace App\Console\Commands;

use App\Jobs\BandwidthLimitJob;
use App\Models\Client;
use App\Models\Pop;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class BandwidthLimitStore extends Command
{

    protected $signature = 'bandwidth:limit';

    protected $description = 'Store Client Bandwidth Limit To Clients Table';

    public function __construct()
    {
        parent::__construct();
    }

    public function handle()
    {
        // Log::info("log -bandwidth:limit");

        $this->info("start to store clients bandwidth Limit \n");

        if (!checkAPI()) {

            $currentDate = Carbon::now();
            $day = $currentDate->format('d');

            if (checkSettings('only_local_bandwidth_check') == 'enable') {

                $pops_id = Pop::where('bill_generate', 'yes')->pluck('id')->toArray();
                Client::with('packages')->where('clients_status', '!=', 'deactive')->where('clients_status', '!=', 'close')
                    ->whereIn('pop_id', $pops_id)->where('billing_cycle', $day)
                    ->select('id', 'userid', 'expire_date', 'bandwidth_limit')
                    ->chunk(100, function ($clients) {
                        BandwidthLimitJob::dispatch($clients);
                    });

                $this->info("End to store only local clients bandwidth Limit");
            } else {

                Client::with('packages')->where('clients_status', '!=', 'deactive')->where('clients_status', '!=', 'close')
                    ->where('billing_cycle', $day)
                    ->select('id', 'userid', 'expire_date', 'bandwidth_limit')
                    ->chunk(100, function ($clients) {
                        BandwidthLimitJob::dispatch($clients);
                    });

                $this->info("End to store all bandwidth Limit");
            }
        } else {

            $this->info("Sorry its not possible \n");
        }
    }
}
