<?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\Http;
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(DATE(expire_date), INTERVAL payment_dadeline DAY), ?) < SUBDATE(NOW(), INTERVAL ? DAY)", [$time, $before])
                ->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();



            $set_all_advance_balance_february_cleint_last_of_march = globalPermission('always_set_february_last_date_to_march_last_date') && Carbon::parse(today())->format('m-d') == '03-01';

            foreach ($advanceCheckClient as $client) {


                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
                            );

                            Log::error("Bill generated for client id: " . $client->id);


                            $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);

                                if (globalPermission('round_expire_date_after_d2d_extend_ExpireDate_By_Month')) {
                                    $date = (new ExpireDateRoundService())->roundExpireDateForRecharge($client->expire_date, $date);
                                }
                            } else {
                                $date = Carbon::parse($client->expire_date)->addDay(30);
                            }

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

                            if ($set_all_advance_balance_february_cleint_last_of_march) {
                                $date = Carbon::parse(today())->lastOfMonth();
                            }
                        } 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_get->payment_dadeline   = 0;
                        $client_get->save();

                        Log::error("Expire date updated for client id: " . $client->id . " to " . $date);

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

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




        if (checkAPI()) {
            Log::error("Going to call API for expire check at " . now());
            ExpireCheckController::api_expair_check($time);
            Log::error("API call finished for expire check at " . now());

            (new SyncWithMk)->syncAllSecretsToMk();
        } else {
            ExpireCheckController::check($time);
        }
    }
}
