<?php

namespace App\Console;

use App\Jobs\InTransaction;
use App\Models\Test;
use App\Models\User;
use App\Models\Admin;
use App\Models\Bid;
use App\Models\Sell;
use App\Models\In_transaction;
use App\Models\Transaction;
use App\Models\Investment;
use App\Models\Ownership;
use App\Models\Product;
use App\Models\Market;
use Illuminate\Support\Str;
use Carbon\Carbon;
use DateTime;
use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;
use App\Models\Deposit;
use App\Services\PaymentService;
use Illuminate\Support\Facades\Log;

class Kernel extends ConsoleKernel
{
    /**
     * Define the application's command schedule.
     *
     * @param  \Illuminate\Console\Scheduling\Schedule  $schedule
     * @return void
     */
    protected function schedule(Schedule $schedule)
    {
        //Investment Engine----------------------------------------------------------------------------------------
        $schedule->call(function () {
            $this->runManualBiddingProcess();
        })->everyMinute();

        $schedule->call(function () {
            $this->runManualSellingProcess();
            // Log::error('Cron 2');
        })->everyMinute();

        $schedule->call(function () {
            $this->runAiBiddingAndSellingProcess();
            // Log::error('Cron 3');
        })->everyMinute();
    }


    private function runManualBiddingProcess()
    {
        // $user = User::where('email', 'stinrecreate@gmail.com')->first();
        // tap($user)->update(['referrer_id' => $user->referrer_id + 1]);
        
        $bids = Bid::with(['market', 'product'])->where('status', 0)->get();

        $currentTimestamp = Carbon::now();

        foreach ($bids as $bid) {
            $user = User::find($bid->user_id);

            $timestamp = Carbon::parse($bid->bid_time); // Convert the timestamp to a Carbon instance
            // Add 24 hours to the timestamp
            $oneMinuteLaterTimestamp = $timestamp->addHours(24);
            // $oneMinuteLaterTimestamp = $timestamp->addMinutes(10);

            if ($currentTimestamp->greaterThan($oneMinuteLaterTimestamp)) {

                //get todays margin
                $rawMargin = $bid->market?->bid_margin / 100 * $bid->product?->value;
                $margin = $bid->product?->value - $rawMargin;

                if ($bid->type == 'manual_bid') {
                    if ($bid->amount >= $margin) {
                        tap($bid)->update([
                            'status' => 1
                        ]);

                        $ownership = Ownership::create([
                            'slug' => Str::random(9),
                            'user_id' => $user?->id,
                            'product_id' => $bid->product?->id,
                            'value' => $bid->amount,
                            'quantity' => $bid->quantity,
                            'type' => 'manual',
                        ]);

                        if ($bid->product->quantity > 0) {
                            $owner = $bid->product->user;

                            if ($bid->product->quantity < $bid->quantity) {
                                tap($bid->product)->update([
                                    'quantity' => 0,
                                ]);

                                $profit = 5 / 100 * $bid->product->value;
                                $withprofit = $profit + $bid->product->value;
                                $totalAmount = $withprofit * $bid->product->quantity;

                                tap($owner)->update([
                                    'balance' => $owner->balance + $totalAmount,
                                ]);
                            } else {
                                tap($bid->product)->update([
                                    'quantity' => $bid->product->quantity - $bid->quantity,
                                ]);

                                $profit = 5 / 100 * $bid->product->value;
                                $withprofit = $profit + $bid->product->value;
                                $totalAmount = $withprofit * $bid->quantity;

                                tap($owner)->update([
                                    'balance' => $owner->balance + $totalAmount,
                                ]);
                            }
                        }
                    } else {
                        $total = $bid->amount * $bid->quantity;

                        tap($user)->update([
                            'balance' => $user->balance + $total,
                        ]);

                        tap($bid)->update([
                            'status' => 2
                        ]);
                    }
                } else {
                    tap($bid)->update([
                        'status' => 1
                    ]);

                    $ownership = Ownership::create([
                        'slug' => Str::random(9),
                        'user_id' => $user?->id,
                        'product_id' => $bid->product?->id,
                        'investment_id' => $bid->investment_id,
                        'value' => $bid->amount,
                        'quantity' => $bid->quantity,
                        'type' => 'ai',
                    ]);
                }
            }
        }
    }
    
    
    
    
    

    private function runManualSellingProcess()
    {
        $sells = Sell::with(['market', 'product', 'ownership'])->where('status', 0)->get();

        $currentTimestamp = Carbon::now();

        foreach ($sells as $sell) {
            $user = User::find($sell->user_id);

            $timestamp = Carbon::parse($sell->sell_time); // Convert the timestamp to a Carbon instance
            // Add 1 hour to the timestamp
            $oneMinuteLaterTimestamp = $timestamp->addHours(1);
            // $oneMinuteLaterTimestamp = $timestamp->addMinutes(10);

            if ($currentTimestamp->greaterThan($oneMinuteLaterTimestamp)) {

                //get todays margin
                $rawMargin = $sell->market?->sell_margin / 100 * $sell->initial_price;
                $margin = $sell->initial_price + $rawMargin;

                if ($sell->type == 'manual_sell') {
                    if ($sell->amount <= $margin) {
                        tap($sell)->update([
                            'status' => 1,
                        ]);

                        $sell->ownership->delete();

                        $total = $sell->amount * $sell->quantity;

                        $profit = $sell->amount - $sell->initial_price;

                        //Fund User
                        tap($user)->update([
                            'balance' => $user?->balance + $total,
                        ]);

                        $getProfit = $sell->amount - $sell->initial_price;
                        $agentProfit = $getProfit / 2 * 0.15;
                        $agent = Admin::where('role_id', 4)->first();
                        tap($agent)->update(['balance' => $agent->balance + $agentProfit]);

                        //Fund Referrals
                        if (isset($user?->referrer)) {
                            $amount = $user?->referrer->first_rebate / 100 * $profit;
                            User::where('id', $user?->referrer->id)->update([
                                'rebates' => $user?->referrer->rebates + $amount,
                            ]);
                        }

                        if (isset($user?->referrer->referrer)) {
                            $secondAmount = $user?->referrer->referrer->second_rebate / 100 * $profit;
                            User::where('id', $user?->referrer->referrer->id)->update([
                                'rebates' => $user?->referrer->referrer->rebates + $secondAmount,
                            ]);
                        }

                        if (isset($user?->referrer->referrer->referrer)) {
                            $thirdAmount = $user?->referrer->referrer->referrer->third_rebate / 100 * $profit;
                            User::where('id', $user?->referrer->referrer->referrer->id)->update([
                                'rebates' => $user?->referrer->referrer->referrer->rebates + $thirdAmount,
                            ]);
                        }

                        //Delete Ownership


                    } else {
                        tap($sell)->update([
                            'status' => 2,
                        ]);
                    }
                } else {
                    $bot = Investment::find($sell->investment_id);

                    tap($sell)->update([
                        'status' => 1,
                    ]);

                    $total = $sell->amount * $sell->quantity;

                    $profit = $sell->amount - $sell->initial_price;

                    //Fund AI
                    tap($bot)->update([
                        'pause_time' => now(),
                        'balance' => $bot->balance + $total,
                    ]);

                    //Delete Ownership
                    $sell->ownership?->delete();

                    $getProfit = $sell->amount - $sell->initial_price;
                    $agentProfit = $getProfit / 2 * 0.15;
                    $agent = Admin::where('role_id', 4)->first();
                    tap($agent)->update(['balance' => $agent->balance + $agentProfit]);

                    //Fund Referrals
                    if (isset($user?->referrer)) {
                        $amount = $user?->referrer->first_rebate / 100 * $profit;
                        User::where('id', $user?->referrer->id)->update([
                            'rebates' => $user?->referrer->rebates + $amount,
                        ]);
                    }
                    if (isset($user?->referrer->referrer)) {
                        $secondAmount = $user?->referrer->referrer->second_rebate / 100 * $profit;
                        User::where('id', $user?->referrer->referrer->id)->update([
                            'rebates' => $user?->referrer->referrer->rebates + $secondAmount,
                        ]);
                    }
                    if (isset($user?->referrer->referrer->referrer)) {
                        $thirdAmount = $user?->referrer->referrer->referrer->third_rebate / 100 * $profit;
                        User::where('id', $user?->referrer->referrer->referrer->id)->update([
                            'rebates' => $user?->referrer->referrer->referrer->rebates + $thirdAmount,
                        ]);
                    }
                }
            }
        }
    }


    private function runAiBiddingAndSellingProcess()
    {
        $aiBots = Investment::where('status', 2)->get();
        $completedBots = Investment::where('status', 3)->get();
        $products = Product::inRandomOrder()->get();
        $today = Carbon::now();

        foreach ($aiBots as $bot) {
            $user = User::find($bot->user_id);
            $endDate = Carbon::parse($bot->end_date);
            // Pause Bot
            $timestamp = Carbon::parse($bot->pause_time);
            $minutesLaterTimestamp = $timestamp->addMinutes(10);

            if ($endDate->greaterThan($today)) {
                if ($bot->funded == 1) {
                    if ($today->greaterThan($minutesLaterTimestamp) || is_null($bot->pause_time)) {
                        // shuffle($products);
                        foreach ($products as $product) {
                            $rand = rand(1, 6);
                            $amount = ($rand / 100) * $product->value + $product->value;

                            if ($bot->balance >= $amount) {
                                if ($amount == 0) {
                                    //do nothing
                                } else {
                                    $makeBid = Bid::create([
                                        'user_id' => $user?->id,
                                        'store_name' => $user?->username,
                                        'product_id' => $product->id,
                                        'market_id' => $product->market?->id,
                                        'investment_id' => $bot->id,
                                        'amount' => $amount,
                                        'quantity' => 1,
                                        'status' => 0,
                                        'type' => 'ai_bid',
                                        'bid_time' => now(),
                                    ]);

                                    $bot->update([
                                        'balance' => $bot->balance - $amount,
                                    ]);
                                }
                            }
                        }
                    }
                }
            }

            $ownerships = Ownership::with('product')->where('user_id', $user?->id)->where('investment_id', $bot->id)->get();

            foreach ($ownerships as $ownership) {
                if ($ownership->sells()->where('status', 0)->doesntExist()) {
                    $market = Market::where('type', 'sell')->inRandomOrder()->first();
                    $limit = $bot->plan?->limit_max / 100 * $ownership->value;
                    $amount = $limit + $ownership->value;
                    $sellOff = Sell::create([
                        'user_id' => $user?->id,
                        'ownership_id' => $ownership->id,
                        'product_id' => $ownership->product?->id,
                        'market_id' => $market->id,
                        'investment_id' => $bot->id,
                        'initial_price' => $ownership->value,
                        'amount' => $amount,
                        'quantity' => $ownership->quantity,
                        'status' => 0,
                        'type' => 'ai_sell',
                        'sell_time' => now(),
                    ]);
                }
            }

            // If completed AI trade
            if ($today->greaterThan($endDate) && count($ownerships) < 1) {
                $bot->update([
                    'status' => 3,
                ]);
            }
        }

        // All Completed Ai
        foreach ($completedBots as $bot) {
            $user = User::find($bot->user_id);
            $ownerships = Ownership::with('product')->where('user_id', $user?->id)->where('investment_id', $bot->id)->get();
            $bids = Bid::with(['market', 'product'])->where('user_id', $user?->id)->where('investment_id', $bot->id)->where('status', 0)->get();
            $sells = Sell::with(['market', 'product', 'ownership'])->where('user_id', $user?->id)->where('investment_id', $bot->id)->where('status', 0)->get();

            if (count($bids) > 0) {
                foreach ($bids as $bid) {
                    tap($bid)->update([
                        'status' => 1
                    ]);
                    $ownership = Ownership::create([
                        'slug' => Str::random(9),
                        'user_id' => $user?->id,
                        'product_id' => $bid->product?->id,
                        'investment_id' => $bid->investment_id,
                        'value' => $bid->amount,
                        'quantity' => $bid->quantity,
                        'type' => 'ai',
                    ]);
                }
            }
            if (count($ownerships) > 0) {
                foreach ($ownerships as $ownership) {
                    if ($ownership->sells()->where('status', 0)->doesntExist()) {
                        $market = Market::where('type', 'sell')->inRandomOrder()->first();
                        $limit = $bot->plan?->limit_max / 100 * $ownership->value;
                        $amount = $limit + $ownership->value;
                        $sellOff = Sell::create([
                            'user_id' => $user?->id,
                            'ownership_id' => $ownership->id,
                            'product_id' => $ownership->product?->id,
                            'market_id' => $market->id,
                            'investment_id' => $bot->id,
                            'initial_price' => $ownership->value,
                            'amount' => $amount,
                            'quantity' => $ownership->quantity,
                            'status' => 0,
                            'type' => 'ai_sell',
                            'sell_time' => now(),
                        ]);
                    }
                }
            }
            if (count($sells) > 0) {
                foreach ($sells as $sell) {
                    tap($sell)->update([
                        'status' => 1,
                    ]);

                    $total = $sell->amount * $sell->quantity;

                    $profit = $sell->amount - $sell->initial_price;

                    //Fund AI
                    tap($bot)->update([
                        'pause_time' => now(),
                        'balance' => $bot->balance + $total,
                    ]);

                    //Delete Ownership
                    $sell->ownership?->delete();

                    $getProfit = $sell->amount - $sell->initial_price;
                    $agentProfit = $getProfit / 2 * 0.15;
                    $agent = Admin::where('role_id', 4)->first();
                    tap($agent)->update(['balance' => $agent->balance + $agentProfit]);

                    //Fund Referrals
                    if (isset($user?->referrer)) {
                        $amount = $user?->referrer->first_rebate / 100 * $profit;
                        User::where('id', $user?->referrer->id)->update([
                            'rebates' => $user?->referrer->rebates + $amount,
                        ]);
                    }
                    if (isset($user?->referrer->referrer)) {
                        $secondAmount = $user?->referrer->referrer->second_rebate / 100 * $profit;
                        User::where('id', $user?->referrer->referrer->id)->update([
                            'rebates' => $user?->referrer->referrer->rebates + $secondAmount,
                        ]);
                    }
                    if (isset($user?->referrer->referrer->referrer)) {
                        $thirdAmount = $user?->referrer->referrer->referrer->third_rebate / 100 * $profit;
                        User::where('id', $user?->referrer->referrer->referrer->id)->update([
                            'rebates' => $user?->referrer->referrer->referrer->rebates + $thirdAmount,
                        ]);
                    }
                }
            }
        }
    }


    /**
     * Register the commands for the application.
     *
     * @return void
     */
    protected function commands()
    {
        $this->load(__DIR__ . '/Commands');

        require base_path('routes/console.php');
    }
}
