<?php

namespace App\Http\Controllers;

use App\Models\Reinvestment;
use App\Models\Investment;
use App\Models\Plan;
use App\Models\Wallet;
use Illuminate\Http\Request;

use Illuminate\Support\Facades\Auth;
use App\Notifications\GeneralNotification;
use App\Models\Role;
use PragmaRX\Countries\Package\Countries;

class ReinvestmentController 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()
    {
        //
    }

    
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        $request->validate([
            'source' => 'required',
            'amount' => 'required|integer|min:1',            
        ]);

        $plan = Plan::where('min_amount', '<=', $request->amount)->where('max_amount', '>=', $request->amount)->first();
        if (!$plan) {
            return response()->json([
                'status' => 'error',
                'message' => 'Sorry, the amount entered does not match any of our plans',
            ], 400);
        }
        $wallet = Wallet::first();
        
        if (!$plan) {
            return response()->json([
                'status' => 'error',
                'message' => 'invalid request',
            ], 400);
        }

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

        $durations = json_decode($plan->durations);
        $duration = $durations[0];
        
        // if (Auth::user()->investments->where('status', 'pending')->count() > 0) {
        //     return response()->json([
        //         'status' => 'error',
        //         'message' => 'you still have a pending investment, kindly wait for admin\'s approval before making another request. Thank you.',
        //     ], 400);
        // }
        $investment = new Investment;
        $investment->user_id = Auth::id();
        $investment->plan_id = $plan->id;
        $investment->wallet_id = $wallet->id;
        $investment->amount = $request->amount;
        $investment->duration = $duration;
        $investment->status = 'pending';
        $investment->save();
        
        $reinvestment = new Reinvestment;
        $reinvestment->user_id = $investment->user_id;
        $reinvestment->investment_id = $investment->id;
        $reinvestment->amount = $investment->amount;
        $reinvestment->status = $investment->status;
        $reinvestment->source = $request->source;
        $reinvestment->save();

        $countries = new Countries();

        // notify the user of confirmed deposit
        $notification_details = [
            'title' => 'Reinvestment Registered',
            'content' => substr($investment->user->name, 0, -3).'****'.' just reinvested $'.number_format($investment->amount, 2, '.', ','),
            'mail_content' => "Dear ". Auth::user()->name. ", <br/> This is to notify you that we have received your request to reinvest with our company through our ".$investment->plan->name." with a liquidity power of $".number_format($investment->amount, 2, '.', ',').". 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>Wallet Address:</strong> ". $investment->wallet->wallet_address ."</p>
            <p><strong>Trading Package:</strong> ". $investment->plan->name ."</p>
            <p><strong>Wallet Name:</strong> ". $investment->wallet->wallet_name ."</p>
            <p><strong>Date:</strong> ". $investment->created_at->format('d-m-Y') ."</p>
            <p><strong>Amount Invested:</strong> $". number_format($investment->amount) ."</p>  
                            <br/> Regards<br/> AMD CONSULTING  <br/> <br/><br/><br/><strong>If you  didn't initiate the above transaction kindly disregard. Thank you </strong></p>         
            ",
        ];
        $activity = (object)$notification_details;
        Auth::user()->notify(new GeneralNotification($activity));

        $roles = Role::all();
         $admin_notification = [
            'title' => 'New Reinvestment',
            'content' => substr($investment->user->name, 0, -3).'****'.' just reinvested with $'.number_format($investment->amount, 2, '.', ','),
            'mail_content' => 'there is a new reinvestment of $'.number_format($investment->amount, 2, '.', ','). ' from '.Auth::user()->name,
        ];
        $admin_activity = (object)$admin_notification;        
        foreach ($roles->where('name', 'admin') as $role) {
           $user = $role->user;
           $user->notify(new GeneralNotification($admin_activity));
        }


        return response()->json([
            'status' => 'success',
            'message' => 'reinvestment registered successfully, we will notify you upon approval by admin.',
        ], 200);
    }


    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Reinvestment  $reinvestment
     * @return \Illuminate\Http\Response
     */
    public function show(Reinvestment $reinvestment)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Reinvestment  $reinvestment
     * @return \Illuminate\Http\Response
     */
    public function edit(Reinvestment $reinvestment)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Reinvestment  $reinvestment
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Reinvestment $reinvestment)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Reinvestment  $reinvestment
     * @return \Illuminate\Http\Response
     */
    public function destroy(Reinvestment $reinvestment)
    {
        //
    }
}
