<?php

namespace App\Console\Commands;

use App\Classes\MikrotikService\SyncWithMk;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\ExpireCheckController;
use App\Http\Controllers\SessionRefreshController;
use App\Models\Client;
use App\Models\CompanyInformation;
use App\Models\CustomerAccount;
use App\Models\Packages;
use App\Services\ExpireDateRoundService;
use App\Services\GenerateMonthlyBill;
use App\Services\SecondMonthlyBillGenerateForDayToDay;
use Carbon\Carbon;
use Illuminate\Support\Facades\Log;

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

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'User Expire check';

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {

        $time = collect(json_decode(siteinfo()->settings))->where('type', 'expire_time')->first()->value ?? '00:00:00';

        if (getBillingType() == 'day_to_day' || siteinfo()->day_to_day_after_10_days === 'Yes') {
            if(globalPermission('expire_before_expire_date')){
                $before = 0;
            } else{
                $before = 1;
            }
            $bill_month = null;
            $lists = Client::whereRaw("ADDTIME(DATE_ADD(expire_date, INTERVAL payment_dadeline DAY), '$time') < SUBDATE(NOW(), INTERVAL '$before' DAY)")
                    ->pluck('userid')
                    ->toArray();

            $advanceCheckClient = Client::with('packages')
                                ->select(
                                    'clients.id',
                                    'clients.expire_date',
                                    'clients.package_id',
                                    'clients.parmanent_discount',
                                    'customer_accounts.dueAmount',
                                    'packages.package_rate'
                                )
                                ->join('customer_accounts', 'clients.id', '=', 'customer_accounts.client_id')
                                ->join('packages', 'clients.package_id', '=', 'packages.id')
                                ->whereIn('clients.userid', $lists)
                                ->where('customer_accounts.dueAmount', '<', 0)
                                ->where('clients.clients_status', '!=', 'deactive')
                                ->whereRaw('packages.package_rate <= ABS(customer_accounts.dueAmount - IFNULL(clients.parmanent_discount, 0))')
                                ->orderBy('clients.id', 'asc')
                                ->get();


            foreach ($advanceCheckClient as $client) {

                // (new GenerateMonthlyBill)->generate($client,$bill_month);
                if (getBillingType() === 'day_to_day' || siteinfo()->day_to_day_after_10_days === 'Yes' ) {
                    DB::beginTransaction();
                    try{
                        $customerAccount = CustomerAccount::where('client_id', $client->id)->first();
                        $client_package = Packages::find($client->package_id);
                        $addvanced_balance = abs($customerAccount->dueAmount);

                        if ($addvanced_balance >= ($client_package->package_rate - $client->parmanent_discount)) {

                           $bill = (new SecondMonthlyBillGenerateForDayToDay)->generate(
                                $client->id,
                                "monthly",
                                $client_package->package_rate,
                                'Monthly Bill Generate ',
                                $client->parmanent_discount,
                                $client_package->client_package,
                                $client_package->package_rate,
                                $client->expire_date
                            );


                            $customerAccount->dueAmount =  $customerAccount->dueAmount + ($client_package->package_rate - $client->parmanent_discount);
                            $customerAccount->save();
                            if(checkSettings('d2d_extend_ExpireDate_By_Month') == 'enable'){
                                $total_day_of_expire_date = Carbon::parse($client->expire_date)->lastOfMonth()->format('d');
                                $date = Carbon::parse($client->expire_date)->addDay($total_day_of_expire_date);
                            }else{
                                $date = Carbon::parse($client->expire_date)->addDay(30);
                            }

                            if(globalPermission('round_expire_date')){
                                $date = (new ExpireDateRoundService())->roundDate($client->expire_date);
                            }

                        } else {
                            $date = Carbon::parse($client->expire_date);
                        }

                        $client_get = Client::find($client->id);


                        $client_get->expire_date    = $date;
                        $client_get->billing_cycle = Carbon::parse($date)->format('d');
                        // $client->clients_status     = 'active';
                        $client_get->payment_dadeline   = 0;
                        $client_get->save();

                        if ($client_get->expire_date >= today()) {
                            $client_get->clients_status = 'active';
                            $client_get->save();
                        }

                        DB::commit();

                    }catch(\Exception $e){
                        DB::rollBack();
                    }


                }
            }

        }




        if (checkAPI()) {

            ExpireCheckController::api_expair_check($time);

            $sync = (new SyncWithMk)->syncAllSecretsToMk();
        } else {

            ExpireCheckController::check($time);
        }
    }
}
