<?php

namespace App\Console\Commands;

use App\User;
use Carbon\Carbon;
use Illuminate\Console\Command;
use App\Cron\UserCheckPaymentsAccounts;

class PaymentsAccounts extends Command
{
    /**
     * ln -sfv /usr/bin/php73 /usr/bin/php
     *  php artisan payments:accounts   
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'payments:accounts';
    protected $description = 'Check Payments Accounts';

    private $timeStart;

    private $dev = false;

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

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        \Log::info('Starting PaymentsAccounts Command', ['timestamp' => now()]);
        $this->info('RUN Command Payments Account: '.date('d.m.Y H:i'));
        $this->timeStart = microtime(true);

        try {
            $this->updateUserNextLevel();
            $this->updatePaymentsAccountsFree();
            $this->deactivateUserAccounts();
            $this->reminderPaymentsAccounts();
            
            \Log::info('PaymentsAccounts Command completed successfully');
            return 0;
        } catch (\Exception $e) {
            \Log::error('PaymentsAccounts Command failed', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString()
            ]);
            return 1;
        }
    }

    private function updateUserNextLevel(){
        try {
            // now date - renewal_days 
            $count = 0;
            $renewalDate = Carbon::now()->modify('+'.(config('main.renewal_days')).' days');
            $users = User::where('payment_account', '!=', NULL)
                    ->where('active', '=', 1)
                    ->where('blocked', '!=', 1)
                    ->where('payment_account', '<', $renewalDate)
                    ->whereColumn('m_level', '!=', 'next_m_level')
                    ->where('deleted_at', NULL)
                    ->get();
            
            foreach($users as $user){
                $user->m_level = $user->next_m_level;
                $user->save();
                $count ++;
            }

            $diff = microtime(true) - $this->timeStart;
            $sec = intval($diff);
            $micro = $diff - $sec;
            $this->info('END Command updateUserNextLevel: '.$count.' | Time: '.$sec. 'sec :' . round($micro * 1000, 4) . " ms");

            \Log::info('updateUserNextLevel completed', [
                'users_updated' => $count,
                'execution_time' => $sec . 'sec :' . round($micro * 1000, 4) . "ms"
            ]);
        } catch (\Exception $e) {
            \Log::error('updateUserNextLevel failed', [
                'error' => $e->getMessage()
            ]);
            throw $e;
        }
    }


    private function updatePaymentsAccountsFree(){
        try {
            // now date - renewal_days -1  / user_levels.payment_year false is no payment
            $count = 0;
            $renewalDate = Carbon::now()->modify('+'.(config('main.renewal_days')-1).' days');
            $users = User::join('user_levels', 'm_level', '=', 'user_levels.id')->select('users.*')
                    ->where('users.payment_account', '!=', NULL)
                    ->where('users.active', '=', 1)
                    ->where('users.blocked', '!=', 1)
                    ->where('users.payment_account', '<', $renewalDate)
                    ->where('user_levels.payment_year', '=', 0)//user_levels.payment_year false is no payment
                    ->where('users.deleted_at', NULL)
                    ->get();
            
            foreach($users as $user){
                $user->payment_account = Carbon::parse($user->payment_account)->modify('1 year');
                $user->save();
                $count ++;
            }

            $diff = microtime(true) - $this->timeStart;
            $sec = intval($diff);
            $micro = $diff - $sec;
            $this->info('END Command updatePaymentsAccountsFree: '.$count.' | Time: '.$sec. 'sec :' . round($micro * 1000, 4) . " ms");

            \Log::info('updatePaymentsAccountsFree completed', [
                'users_updated' => $count,
                'execution_time' => $sec . 'sec :' . round($micro * 1000, 4) . "ms"
            ]);
        } catch (\Exception $e) {
            \Log::error('updatePaymentsAccountsFree failed', [
                'error' => $e->getMessage()
            ]);
            throw $e;
        }
    }

    private function deactivateUserAccounts(){
        try {
            $count = 0;
            $sevenDaysAfterExpiry = Carbon::now()->subDays(7);
            $users = User::where('payment_account', '!=', NULL)
                    ->where('active', '=', 1)
                    ->where('blocked', '!=', 1)
                    ->where('payment_account', '<', $sevenDaysAfterExpiry)
                    ->where('deleted_at', NULL)
                    ->get();

            foreach($users as $user){
                $user->active = 0;
                $user->save();
                $this->info('deactivateUserAccount | User: '.$user->id.' '.$user->email.' | Date :' . $user->getPaymentAccountDateFormat() . "");

                $count ++;
            }

            $diff = microtime(true) - $this->timeStart;
            $sec = intval($diff);
            $micro = $diff - $sec;
            $this->info('END Command deactivateUserAccounts: '.$count.' | Time: '.$sec. 'sec :' . round($micro * 1000, 4) . " ms");

            \Log::info('deactivateUserAccounts completed', [
                'users_updated' => $count,
                'execution_time' => $sec . 'sec :' . round($micro * 1000, 4) . "ms"
            ]);
        } catch (\Exception $e) {
            \Log::error('deactivateUserAccounts failed', [
                'error' => $e->getMessage()
            ]);
            throw $e;
        }
    }

    private function reminderPaymentsAccounts()
    {
        try {
            $count = 0;
            $max_reminder_date = Carbon::now()->modify('+'.(config('main.remind_first_days')).' days');
            $users = User::where('payment_account', '!=', NULL)
                    ->where('active', '=', 1)
                    ->where('blocked', '!=', 1)
                    ->where('payment_account', '<', $max_reminder_date)
                    ->where('deleted_at', NULL)
                    ->get();

            foreach ($users as $user){
                $status = UserCheckPaymentsAccounts::userReminderPayments($user, $this->dev);
                $this->info('reminderPaymentsAccounts Status: '.$status.' | User: '.$user->id.' '.$user->email.' | Date :' . $user->getPaymentAccountDateFormat() . "");
                $count ++;
            }        

            $diff = microtime(true) - $this->timeStart;
            $sec = intval($diff);
            $micro = $diff - $sec;
            $this->info('END Command reminderPaymentsAccounts: '.$count.' | Time: '.$sec. 'sec :' . round($micro * 1000, 4) . " ms");

            \Log::info('reminderPaymentsAccounts completed', [
                'users_processed' => $count,
                'execution_time' => $sec . 'sec :' . round($micro * 1000, 4) . "ms"
            ]);
        } catch (\Exception $e) {
            \Log::error('reminderPaymentsAccounts failed', [
                'error' => $e->getMessage()
            ]);
            throw $e;
        }
    }
}
