<?php

namespace App\Http\Controllers;

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

class CronController extends Controller
{


    public function interest(){
	/*
        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('next_return_date', '<=', $now)
                ->with('user')
				->take(200)
                ->get();//run_to
				

            //return $investments;
			foreach($investments as $index => $data){
				$user = $data->user;
				if( $user ){
					// NGN Currency
					if($data->currency == 'NGN') {
						$user->income += $data->interest_amount;
						$user->save();
						$post_balance = $user->pending_income;
					}

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

					$data->next_return_date = Carbon::now()->addHours(24);
					$data->total_paid += 1;
					//$data->is_started = 0;

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

					$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{
					echo('User not found'.$data->user_id);
				}
			}
			

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

    public function croned(){
/*
        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('next_return_date', '<=', $now)
                ->with('user')
				->take(200)
                ->get();//run_to
				

            //return $investments;
            foreach($investments as $index => $data){
                $user = $data->user;
                
                // NGN Currency
                if($data->currency == 'NGN') {
                    $user->pending_income += $data->interest_amount;
                    $user->save();
                    $post_balance = $user->pending_income;
                }

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

                //$data->next_return_date = getNextDayWithTime(8, 5);
                $data->next_return_date = Carbon::now()->addHours(24);
                $data->total_paid += 1;
                //$data->is_started = 0;

                if($data->total_paid >= $data->total_return){
                    $data->status = 1;
                }

                $data->save();

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

            }

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

*/
    }

    public function lockedPlan(){
/*
        try{

            $plan = Plan::where('p_status', 'coming')
                ->where('lock_endat', '<=', Carbon::now())
                ->get();


            //return $plan;
            foreach($plan as $index => $data){

                // Make available plan
                $data->p_status = 'to_buy';
                $data->lock_limit = 0;

                $data->save();

            }

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

    }

    public function salary(){

/*        try{

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

            Config::set('app.timezone', 'Africa/Lagos');
            $now = Carbon::now();

            $isSundayAtTen = ($now->dayOfWeek == Carbon::SUNDAY);
            
            if(!$isSundayAtTen) throw new \Exception("Sorry not ready");
            

            $users = User::where('status', 1)->get();


            foreach($users as $index => $user){

                $user_id = $user->id;

                // Referrals
                $referrals = Investment::with('user')->with('plan')->where(['currency' => session()->get('currency')])->whereHas('user', function ($query) use ($user_id) {
                    $query->where('ref_by', $user_id);
                })->distinct('user_id')->count();

                $paidLevel = Transaction::where(['user_id' => $user_id, 'type' => 'salary'])->sum('number');
                $referrals = max(0, $referrals - $paidLevel);

                // Skip
                if(!$referrals) continue;

                $rewards = RewardPlan::where(['type' => 2, 'status' => 1])->orderBy('id')->get();

                $levelNumber = 0;
                $currentLevel = 0;

                foreach ($rewards as $key => $reward) {
                
                    $activeNumber = 0;
                    $previousIndex = ($key > 0) ? $key - 1 : 0;
                    $previousItem = ($previousIndex !== null) ? $rewards[$previousIndex] : null;

                    if ($referrals >= $reward->number) {
                        $activeNumber = $reward->number;
                        $levelNumber = $reward->number;
                        $currentLevel = $reward->id;
                    }

                    // Last loop
                    if(!$previousIndex) {
                        //$status = $rewards[$key - 1];
                        $levelNumber = $referrals - $previousItem->number;
                        $activeNumber = max(0, $levelNumber);
                        $levelNumber = $activeNumber;
                        $referrals = $levelNumber;
                        $activeNumber = ($activeNumber >= $reward->number) ? $reward->number : $activeNumber - $reward->number;
                        $activeNumber = max(0, $activeNumber);
                    }
                }

                // Skip
                if(!$currentLevel) continue;

                // Find reward
                $reward = RewardPlan::where(['type' => 2, 'status' => 1, 'id' => $currentLevel])->first();
                
                $today = Carbon::now()->toDateString();

                // Check if already action
                $todayRecords = Transaction::where(['user_id' => $user_id, 'type' => 'salary'])->whereDate('created_at', $today)->get();

                if(!empty($todayRecords->count())) continue;

                // NGN Currency
                if($reward->currency == 'NGN') {
                    $user->pending_income += $reward->amount;
                    $user->save();
                    $post_balance = $user->pending_income;
                }

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

                // Add Transaction records
                $transaction = new Transaction();
                $transaction->user_id = $user_id;
                $transaction->type =  'salary';
                $transaction->amount = $reward->amount;
                $transaction->post_balance = $post_balance;
                $transaction->charge = '0';
                $transaction->currency = $reward->currency;
                $transaction->trx_type = '+';
                $transaction->details = $reward->summary;
                $transaction->number = $reward->number;
                $transaction->trx =  getTrx();
                $transaction->status =  1;
                $transaction->save();

            }

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

*/
    }

    public function couponStart(){

/*        try{

            $coupons = Coupon::where('started', 0)
                ->where('start_date', '<=', Carbon::now())
                ->get();


            //return $coupon;
            foreach($coupons as $index => $data){

                // Make available coupon
                $data->started = 1;
                $data->start_date = null;

                $data->save();

            }

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

*/
    }

    public function couponGenerate(){
/*
        try{

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

            $users = User::get();

            //return $coupon;
            foreach($users as $index => $user){

                // Escape duplicated
                $today = Carbon::now()->toDateString();

                // Check if already action
                $todayRecords = Coupon::where(['user_id' => $user->id])->whereDate('created_at', $today)->get();

                if(!empty($todayRecords->count())) continue;
                

                $label = '<iconify-icon icon="ph:moon-light" class="text-dark" width="20"></iconify-icon> Ramadan Kareem';
                $type = 'invest';

                // Create 10% to expire 10am Saturday (16/03/2024)
                $this->addCoupon($user, $type, $label, 10, 1, null, '2024-03-16 10:00:00', 1);

                // Create 5% to expire Sunday 10am(17/03/2024)
                $this->addCoupon($user, $type, $label, 5, 1, null, '2024-03-17 10:00:00', 1);

            }

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

*/
    }

    public function addCoupon(
        User $user,
        string $type,
        string $label,
        string $discount,
        string $started,
        string $start_date = null,
        string $expired_date,
        string $status
    ){

        $startDate = ($start_date) ? Carbon::createFromFormat('Y-m-d H:i:s', $start_date, 'Africa/Lagos') : null;
        $expiredDate = Carbon::createFromFormat('Y-m-d H:i:s', $expired_date, 'Africa/Lagos');

        $coupon = new Coupon();
        $coupon->user_id = $user->id;
        $coupon->type = $type;
        $coupon->label = $label;
        $coupon->discount = $discount;
        $coupon->started = $started;
        $coupon->start_date = $startDate;
        $coupon->expired = 0;
        $coupon->expired_date = $expiredDate;
        $coupon->code = verificationCode(8);
        $coupon->status = $status;
        $coupon->save();

        return $coupon;

    }

    public function couponExpired(){

/*        try{

            $coupons = Coupon::where('expired_date', '<=', Carbon::now())
                ->get();


            //return $coupon;
            foreach($coupons as $index => $data){

                // Make expired coupon
                $data->expired = 1;
                $data->save();

            }

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

*/
    }


}
