<?php

namespace App\Http\Controllers;

use App\Models\Copier;
use App\Models\Trader;
use App\Models\CoinRateChange;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CopierController 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([
            'amount' => 'required',
            'trader_id' => 'required',
            'payment_source' => 'required',
            'proportion' => 'required',
        ]);

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

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


        // switch ($request->payment_source) {
        //     case 'Withdrawable Balance':
        //         $balance = Auth::user()->withdrawableBalance();
        //         break;

        //     case 'Funding Wallet':
        //         $balance = Auth::user()->balance();
        //         break;

        //     case 'Referral Wallet':

        //         $balance = Auth::user()->referralEarning();
        //         break;
            
        //     default:

        //     return response()->json([
        //         'status' => 'error',
        //         'message' => 'invalid payment source'
        //        ], 400);
        //         break;
        // }


        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;
            }

          
        }

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

        $copier = new Copier;
        $copier->user_id = Auth::id();
        $copier->trader_id = $request->trader_id;
        $copier->amount = $request->amount;
        $copier->proportion = $request->proportion;
        $copier->profit = 0;
        $copier->floating_profit = 0;
        $copier->equity = $request->amount;
        $copier->gain = 0;
        $copier->average_daily = 0;
        $copier->average_month = 0;
        $copier->payment_source = $request->payment_source;
        $copier->status = 'pending';
        $copier->save();

        // $coin_from = CoinRateChange::where('symbol', $request->payment_source)->first();
        // if ($coin_from) {
        //     $balance = Auth::user()->getCoinBalance($request->payment_source);
        //     $coin_from->balance = $balance;
        //     $coin_from->save();
        // }

        $investments = Copier::orderByDesc('id')->where('user_id', Auth::id())->take(100)->get()->load(['trader', 'trader.trades']);

        return response()->json([
            'status' => 'success',
            'message' => 'Your copying is being set up, you will receive a mail upon completion, thank you.',
            'investments' => $investments
        ],200);
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Copier  $copier
     * @return \Illuminate\Http\Response
     */
    public function show(Copier $copier)
    {
        $copiers = Copier::orderByDesc('id')->take(150)->get()->load(['user', 'trader']);
        return response()->json([
            'status' => 'success',
            'message' => 'copiers loaded successfully',
            'copiers' => $copiers
        ], 200);
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  \App\Models\Copier  $copier
     * @return \Illuminate\Http\Response
     */
    public function edit(Copier $copier, $id)
    {
        $copier = $copier->find($id)->load(['user', 'trader']);
        if (!$copier) {
           return response()->json([
            'status' => 'error',
            'message' => 'failed to load trader'
           ], 400);
        }

        return response()->json([
            'status' => 'success',
            'message' => 'loaded',
            'copier' => $copier
        ], 200);
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \App\Models\Copier  $copier
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, Copier $copier)
    {
        $request->validate([
            'copier_id' => 'required'
        ]);
        $copy = $copier->find($request->copier_id);
        if (!$copy) {
            return response()->json([
                'status' => 'error',
                'message' => 'copy not found!'
            ], 400);
        }

        $copy->status = 'completed';
        $copy->save();

        // $coin_from = CoinRateChange::where('symbol', $copy->payment_source)->first();
        // if ($coin_from) {
        //     $balance = Auth::user()->getCoinBalance($copy->payment_source);
        //     $coin_from->balance = $balance;
        //     $coin_from->save();
        // }

        $investments = Copier::orderByDesc('id')->where('user_id', Auth::id())->take(100)->get()->load(['trader', 'trader.trades']);

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

    }

    public function adminUpdate(Request $request){

        $request->validate([
            'copier_id' => 'required',
            'amount' => 'required',	
            'proportion' => 'required',	
            'profit' => 'required',	
            'floating_profit' => 'required',	
            'equity' => 'required',	
            'gain' => 'required',	
            'average_daily' => 'required',	
            'average_month' => 'required',	
            'status' => 'required',	
        ]);

        $copier = Copier::find($request->copier_id);
        if (!$copier) {
            return response()->json([
                'status' => 'error',
                'message' => 'failed to load trader'
            ], 400);
        }
        $copier->amount = $request->amount;	
        $copier->proportion = $request->proportion;	
        $copier->profit = $request->profit;	
        $copier->floating_profit = $request->floating_profit;	
        $copier->equity = $request->equity;	
        $copier->gain = $request->gain;	
        $copier->average_daily = $request->average_daily;	
        $copier->average_month = $request->average_month;	
        $copier->status = $request->status;	
        $copier->save();

        // $coin_from = CoinRateChange::where('symbol', $copier->payment_source)->first();
        // if ($coin_from) {
        //     $balance = Auth::user()->getCoinBalance($copier->payment_source);
        //     $coin_from->balance = $balance;
        //     $coin_from->save();
        // }

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

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