<?php

namespace App\Console\Commands;

use App\Models\Pop;
use App\Models\Client;
use App\Jobs\BillGenerateJob;
use Illuminate\Console\Command;
use App\Http\Controllers\BillGenerateController;
use Illuminate\Support\Facades\Log;

class billgenerate extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'bill:generate';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Bill Generate';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */

    public function runBillGenerate($bill_month = null)
    {


        $pops_id = Pop::where('bill_generate', 'yes')->pluck('id')->toArray();

        Client::with('packages', 'generatedBill')
            ->where('clients_status', '!=', 'deactive')
            ->where('clients_status', '!=', 'close')
            ->where('is_free', '!=', '1')
            ->whereIn('pop_id', $pops_id)
            ->select('id', 'expire_date', 'package_id', 'parmanent_discount')
            ->chunk(100, function ($clients) use ($bill_month) {
                BillGenerateJob::dispatch($clients, $bill_month);
            });


    }
    public function handle()
    {

        $bill_month = today();

        // Log::info("log -bill:generate");

        if (checkSettings('dailyBillGenerate') == 'enable' && checkSettings('monthlyBillGenerate') != 'disable') {

            $this->runBillGenerate($bill_month);

        } elseif (checkSettings('monthlyBillGenerate') != 'disable') {

            if (today()->firstOfMonth() == now()->firstOfMonth()) {

                $this->runBillGenerate($bill_month);
            } else {

            }
        } else {
           
        }
    }
}
