<?php
namespace App\Console\Commands;

use App\Models\Admin;
use App\Models\Investment;
use App\Models\Plan;
use App\Models\User;
use App\Models\Transaction;
use App\Models\Coupon;
use Carbon\Carbon;
use App\Models\GeneralSetting;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;


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

    /**
     * The console commands description.
     *
     * @var string
     */
    protected $description = 'Runs users investment interest';

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

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

        try{

            ini_set("memory_limit",-1);
            ini_set('max_execution_time', 0);

			$now                = Carbon::now();
			$general            = GeneralSetting::first();
			$general->last_cron = $now;
			$general->save();
			
            $investments = Investment::where('status', 0)  // Status: 0=>Running, 1=>Completed
                ->where('run_to', '<=', $now)
                ->with('user')
				->take(650)
                ->get();//run_to

            //return $investments;
            foreach($investments as $index => $data){
				
				$Profits 	= json_decode($data->profits);
				$Dates 		= json_decode($data->dates);
				$State 		= $data->state;
				$Stop 		= $data->stop;
				
				if( $Profits && $State <= $Stop ){
					$user = $data->user;

					$thisInterest = $Profits[$State];
					$data->earned 	+= $thisInterest;
                
					// NGN Currency
					if($data->currency == 'NGN') {
						$user->pending_income += $thisInterest;
						$user->save();
						$post_balance = $user->pending_income;
					}

					// USDT Currency
					if($data->currency == 'USDT') {
						$user->usdt_pending_income += $thisInterest;
						$user->save();
						$post_balance = $user->usdt_pending_income;
					}

					if( $State == $Stop ){
						$data->next_return_date = $nextReturn = Carbon::now()->addHours(24);
						$data->total_paid += 1;
						
						//Start another cycle of earning droping for the next 24 hours
						$leftMinutes = 1434; //now()->diffInMinutes($nextReturn);
						
						$nextRun = [];$max = 1; $check = []; $addRate = [];
						$cycle = $data->plan->cycle; $uInRate = $data->interest_amount;
						$constant = ceil($leftMinutes/$cycle);
						$interestRate = ceil($uInRate/$cycle);
						$rateHalf = ceil($interestRate/2);
						for($i=1; $i<=$cycle; $i++){
							$min = $max; $max = $constant * $i;

							$minutes = rand($min, $max);
							$nextRun[] = Carbon::now()->addMinutes($minutes)->toDateTimeString();
							
							$rMin = ($interestRate-$rateHalf); 
							$rMax = ceil($interestRate+($rateHalf/1.6)); 
							$inCycle = rand($rMin, $rMax);
							$addRate[] = $eachRate = ($i < $cycle) ? $inCycle:$uInRate;
							$uInRate -= $eachRate;
						}

						$data->run_to 		= $nextRun[0];
						$data->profits 		= json_encode($addRate);
						$data->dates 		= json_encode($nextRun);
						$data->state 		= 0; 
						$data->stop  		= ($cycle-1);

						
						$transaction = new Transaction();
						$transaction->user_id = $data->user_id;
						$transaction->currency = $data->currency;
						$transaction->amount = $data->interest_amount;
						$transaction->charge = 0;
						$transaction->post_balance = $post_balance;
						$transaction->type = 'income';
						$transaction->trx_type = '+';
						$transaction->trx = getTrx();
						$transaction->details = 'Profits From '.$data->plan->name." assets";
						$transaction->save();
						
					}else{
						$State ++;
						$data->run_to 		= $Dates[$State];
						$data->state 		= $State;
					}


					if($data->total_paid >= $data->total_return){

						$data->status = 1;

						// Give the capital back if plan says the same
						if ($data->capital_status == 1) {
							$capital =  $data->amount;

							// NGN Currency
							if($data->currency == 'NGN') {
								$user->balance += $capital;
								$postBalance = $user->balance;
							}

							// USDT Currency
							if($data->currency == 'USDT') {
								$user->usdt_balance += $capital;
								$postBalance = $user->usdt_balance;
							}

							$user->save();
							
							$capReturn = new Transaction();
							$capReturn->user_id = $data->user_id;
							$capReturn->currency = $data->currency;
							$capReturn->amount = $capital;
							$capReturn->charge = 0;
							$capReturn->post_balance = $postBalance;
							$capReturn->type = 'capital';
							$capReturn->trx_type = '+';
							$capReturn->trx = getTrx();
							$capReturn->details = $capital . ' ' . config('settings')->cur_text . ' Capital Back From '.@$data->plan->name;
							$capReturn->save();
						}

					}

					$data->save();

				}
			}
			$this->info('Investors investment updated');

        }catch(\Exception $ex){
			$this->info($ex->getMessage());
            $admin = Admin::first();
            sendGeneralEmail($admin->email, $ex->getMessage(), $ex->getMessage(), '');
            \Log::error('CronController -> investment() line '. __LINE__ .': '.$ex->getMessage() ."\n");
        }

    }
}
