<?php

namespace App\Http\Controllers;

use App\Models\Investment;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\InvestmentPlan;
use App\Models\Referral;
use App\Models\User;
use App\Models\Funding;
use App\Models\Trading;
use AmrShawky\LaravelCurrency\Facade\Currency;
use App\Notifications\GeneralNotification;
use App\Services\AdminNotificationService;

class InvestmentController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }

    public function getCoinBalance($coin) {
        $bal = 0;
        $balance = Funding::where('gateway', $coin)->where('user_id', (int)Auth::id())->where('status', 'successful')->sum("amount");
        $bal += $balance;
        $trading = Trading::where('pair', $coin)->where('user_id', (int)Auth::id())->sum("profit");
        $bal += $trading;

        $investments = Investment::where('payment_source', $coin)->where('user_id', (int)Auth::id())->sum("amount_invested");
        $bal -= $investments;

        $investments = Investment::where('payment_source', $coin)->where('user_id', (int)Auth::id())->sum("earning");
        $bal += $investments;

        return $bal;
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'investment_plan_id' => 'required',
            'amount' => 'required',
            'rate' => 'required',
            'duration' => 'nullable',
            'payment_source' => 'required',
        ]);

        $plan = InvestmentPlan::find($request->investment_plan_id);
        if (!$plan) {
           return response()->json([
            'status' => 'error',
            'message' => 'plan not found!'
           ], 400);
        }

        $min_amount = $plan->min_amount;
        $max_amount = $plan->amount_invested;
        $currency = Auth::user()->currency;

        if (($request->amount < $min_amount) || ($request->amount > $max_amount)) {
            return response()->json([
                'status' => 'error',
                'message' => 'Amount must not be less than $'. number_format($min_amount, 2, '.', ',').' or greater than $' .number_format($max_amount, 2, '.', ',')
               ], 400);
        }

        
        if ($request->has('payment_source') && $request->payment_source != '') {

            switch ($request->payment_source) {
               
                case 'Overall Asset':
                    $balance = Auth::user()->balance();

                    if ($balance < $request->amount) {
                        return response()->json([
                            'status' => 'error',
                            'message' => 'Insufficient funds in your '. $request->payment_source
                           ], 400);
                    }

                    break;
                
                default:
    
                // do nothing
               
                break;
            }

          
        }

        $investment = new Investment;
        $investment->user_id = Auth::id();
        $investment->investment_plan_id = $request->investment_plan_id;
        $investment->status = 'pending';
        $investment->earning = 0;
        $investment->duration = '5 Years';
        $investment->payment_source = $request->payment_source;
        $investment->amount_invested = $request->amount;
        $investment->save();

        // Send admin notification about new investment request
        AdminNotificationService::newInvestment($investment);

        // check for referral and credit the earnings
        $referral = Referral::where('invited_id', Auth::id())->first();
        if ($referral && $referral->status == 'pending') {

            $upliner = $referral->inviter;
            $upliner_investments = $upliner->investments->where('status', 'approved');
            $upliner_referrals = $upliner->referrals;

            if (!$referral->investment) {
                if ($upliner_investments->count() > 0) {

                    foreach ($upliner_investments as $old_investment) {
                    $number_invited = $old_investment->referrals->count();
    
                    if ($number_invited < $old_investment->plan->number_of_downlines) {
                        $percentage = $investment->plan->bonus_per_downline /100;
                        $earning = $percentage * $investment->amount_invested;

                        $referral->earning = $earning;
                        $referral->status = 'approved';
                        $referral->investment_id = $investment->id;
                        $referral->save();                        
                    }
    
                    }
                }
            }
            
        }

        $investments = Investment::orderByDesc('id')->where('user_id', (int)Auth::id())->take(10)->get()->load(['plan']);
        // send mail

        $notification_investment = [
            'title' => 'Investment Registered 💰',
            'url' => '/',
            'content' =>  'Investment Registered 💰',
            'mail_content' => "Dear ". $investment->user->name. ", <br/> This is to notify you that we have received your request to invest with our company through our ".$investment->plan->name." with a liquidity value of $".number_format($investment->amount_invested, 4, '.', ',').". Kindly wait for admin's approval of your request as you review the details of your trading below: <br/><br/> 
            <p style='text-align:left;'>
            <p><strong>Trader Name:</strong> ". $investment->user->name ."</p>
            <p><strong>Trading Package:</strong> ". $investment->plan->name ."</p>
            <p><strong>Date:</strong> ". $investment->created_at->format('d-m-Y') ."</p>
            <p><strong>Amount Invested:</strong> $". number_format($investment->amount_invested) ."</p>  
            <br/> Regards<br/> T-TRADES  <br/> <br/><br/><br/><strong>If you  didn't initiate the above transaction kindly disregard. Thank you </strong></p>         
            ",
            ];

            $ref_activity = (object)$notification_investment;
            // $investment->user->notify(new GeneralNotification($ref_activity));

        return response()->json([
            'status' => 'success',
            'message' => 'investment registered successfully, kindly wait for approval from admin',
            'investments' => $investments
        ],200);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Investment  $investment
     * @return \Illuminate\Http\Response
     */
    public function balanceAccount(Investment $investment)
    {
        $investments = $investment->where('status', 'approved')->get();
        foreach ($investments as $investment) {

            $plan = $investment->plan;
            $percentage = $plan->total_earning/100;
            $amount_to_earn = $percentage * $investment->amount_invested;
            $now = strtotime('now');
            $expiry_date = strtotime($investment->created_at .' + '. $investment->duration);

            $started_date = strtotime($investment->created_at);

            $seconds_spent = $expiry_date - $started_date;
            $hours_spent = $seconds_spent/3600;
            $amount_earned = $hours_spent * $investment->plan->amount_per_hour;

            // daily amount calculation
            // percentage_earned
            $percent_amount_per_5_minutes = (5 * $investment->plan->amount_per_hour) / 60;
            $amount_per_5_minutes = $percent_amount_per_5_minutes * $investment->amount_invested;

            if ($investment->earning > 0) {
                $old_earning = $investment->earning;
                $investment->earning = ($amount_per_5_minutes + $old_earning);

                $old_percent = $investment->percentage_earned;
                $investment->percentage_earned = ($percent_amount_per_5_minutes + $old_percent);
            }else {
                $investment->earning = $amount_per_5_minutes;
                $investment->percentage_earned = $percent_amount_per_5_minutes;

            }
            $investment->save();

            // if ($expiry_date <= $now) {

            //     $investment->status = 'completed';
                
            //     $investment->save();

            //    $notification_completed = [
            //     'title' => 'Investment  '.$investment->status,
            //     'url' => '/',
            //     'content' =>  'Investment '.$investment->status,
    
            //     'mail_content' => "Dear ". $investment->user->name. ", <br/> This is to notify you that your investment in our ".$investment->plan->name." with a liquidity value of $".number_format($investment->amount_invested, 4, '.', ',').". has been updated as $investment->status, you can review the details of your investment below: <br/><br/> 
            //     <p style='text-align:left;'>
    
            //     <p><strong>Investor:</strong> ". $investment->user->name ."</p>
            //     <p><strong>Trading Package:</strong> ". $investment->plan->name ."</p>
            //     <p><strong>Date:</strong> ". $investment->created_at->format('d-m-Y') ."</p>
            //     <p><strong>Amount Invested:</strong> $". number_format($investment->amount_invested) ."</p>  
            //     <br/> Regards<br/> T-TRADES  <br/> <br/><br/><br/><strong>If you  didn't initiate the above transaction kindly disregard. Thank you </strong></p>         
            //     ",
            //     ];
    
            //     $ref_activity = (object)$notification_completed;
            //     $investment->user->notify(new GeneralNotification($ref_activity));
            // }
        }

        return response()->json([
            'status' => 'success',
            'message' => 'earning credited successfully'
        ], 200);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Investment  $investment
     * @return \Illuminate\Http\Response
     */
    public function show(Investment $investment)
    {
        $investments = Investment::orderByDesc('id')->take(50)->get()->load(['plan', 'user']);
        return response()->json([
            'status' => 'success',
            'message' => 'investments loaded successfully',
            'investments' => $investments
        ], 200);

    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Investment  $investment
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Investment $investment)
    {
        $request->validate([
            'investment_status' => 'required',
            'investment_id' => 'required'
        ]);

        $investment = $investment->find($request->investment_id);
        if (!$investment) {
            return response()->json([
                'status' => 'success',
                'message' => 'investment not found',
            ], 400);    
        }

        $investment->status = $request->investment_status;
        $investment->save();

        // send a mail to user
        $notification_approved = [
            'title' => 'Investment  '.$investment->status,
            'url' => '/',
            'content' =>  'Investment '.$investment->status,

            'mail_content' => "Dear ". $investment->user->name. ", <br/> This is to notify you that your investment in our ".$investment->plan->name." with a liquidity value of $".number_format($investment->amount_invested, 4, '.', ',').". has been updated as $investment->status, you can review the details of your investment below: <br/><br/> 
            <p style='text-align:left;'>

            <p><strong>Investor:</strong> ". $investment->user->name ."</p>
            <p><strong>Trading Package:</strong> ". $investment->plan->name ."</p>
            <p><strong>Date:</strong> ". $investment->created_at->format('d-m-Y') ."</p>
            <p><strong>Amount Invested:</strong> $". number_format($investment->amount_invested) ."</p>  
            <br/> Regards<br/> T-TRADES  <br/> <br/><br/><br/><strong>If you  didn't initiate the above transaction kindly disregard. Thank you </strong></p>         
            ",
            ];

            $ref_activity = (object)$notification_approved;
            $investment->user->notify(new GeneralNotification($ref_activity));

        return response()->json([
            'status' => 'success',
            'message' => 'investment updated successfully',
        ], 200);
    }

    public function editInvestment(Request $request, $id){

        $request->validate([
            'investment_plan_id' => 'required',
            'amount' => 'required',
            'duration' => 'required',
            'status'=> 'required',
            'earning'=> 'required',
            'payment_source' => 'required',
        ]);

        $plan = InvestmentPlan::find($request->investment_plan_id);
        if (!$plan) {
           return response()->json([
            'status' => 'error',
            'message' => 'plan not found!'
           ], 400);
        }

        $min_amount = $plan->min_amount;
        $max_amount = $plan->amount_invested;
        // $currency = Auth::user()->currency;

        if (($request->amount < $min_amount) || ($request->amount > $max_amount)) {
            return response()->json([
                'status' => 'error',
                'message' => 'Amount must not be less than $'. number_format($min_amount, 2, '.', ',').' or greater than $' .number_format($max_amount, 2, '.', ',')
               ], 400);
        }

        $investment = Investment::find($id);
        if (!$investment) {
            return response()->json([
                        'status' => 'error',
                        'message' => 'Investment not found'
                       ], 400);
        }

        $investment->investment_plan_id = $request->investment_plan_id;
        $investment->status = $request->status;
        $investment->earning = $request->earning;
        $investment->duration = $request->duration;
        $investment->payment_source = $request->payment_source;
        $investment->amount_invested = $request->amount;
        $investment->save();


        $investments = Investment::orderByDesc('id')->where('user_id', Auth::id())->take(50)->get()->load(['plan']);

        return response()->json([
            'status' => 'success',
            'message' => 'investment updated successfully',
            'investments' => $investments
        ],200);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Investment  $investment
     * @return \Illuminate\Http\Response
     */
    public function getRate(Investment $investment)
    {
        $earning = 0;
        $sec_earning = 0;
        $percentages = collect([]);

        $user = Auth::user();
        foreach ($user->investments as $investment) {

            if (!$investment) {
                return response()->json([
                    'status' => 'success',
                    'message' => 'investment not found',
                ], 400);
            }
    
            $plan = $investment->plan;
            $hourly_percentage = $plan->amount_per_hour/100;
            $hourly_earning = $hourly_percentage * $investment->amount_invested;
            $seconds_earning = $hourly_earning/3600;
            
            $expected_percentage = $plan->total_earning/100;
            $expected_earning =  $expected_percentage * $investment->amount_invested;
    
            $now = strtotime('now');
            // $expiry_date = strtotime($investment->created_at .' + '. $investment->plan->duration);
    
            $current_duration = $now - strtotime($investment->created_at);
            $current_earning = $seconds_earning * $current_duration;
            $earning += $current_earning;
            $sec_earning += $seconds_earning;

            $percentages->push(['current_earning' => $current_earning, 'amount' => $investment->amount_invested, 'status' => $investment->status, 'id' => $investment->id, 'plan' => $investment->plan->name, 'rate' => $seconds_earning, 'total' => $expected_earning]);
        }
        
        return response()->json([
            'status' => 'success',
            'message' => 'earning credited successfully',
            'current_earning' => $earning,
            'rate' => $sec_earning,
            'analysis' => $percentages
        ], 200);
    }
}
