<?php

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Lib\TreeInvestLab;
use App\Models\Invest;
use App\Models\Project;
use App\Models\Transaction;
use Illuminate\Http\Request;
use Illuminate\Validation\ValidationException;


class InvestController extends Controller
{
    public function invest(Request $request)
    {

        $request->validate([
            'project_id' => 'required',
            'quantity'   => 'required|gt:0',
            'method'     => 'required|in:gateway,balance',
        ]);

        $project = Project::active()->eligibleToInvest()->with('timeSetting')->whereHas('timeSetting', function ($time) {
            $time->active();
        })->findOrFail($request->project_id);


        if ($request->quantity < $project->minimum_quantity || $request->quantity > $project->maximum_quantity) {
            throw ValidationException::withMessages(['error' => 'Please check the quantity limit']);
        }

        $user = auth()->user();

        $pricePerTree = $project->investment / $project->total_quantity;
        $amount       = $request->quantity * $pricePerTree;

        session()->forget('invest_data');


        if ($request->method == 'gateway') {
            $investData = [
                'quantity'   => $request->quantity,
                'amount'     => $amount,
                'project_id' => $project->id
            ];
            session()->put('invest_data', $investData);
            return to_route('user.deposit.payment');
        }

        if ($amount > $user->balance) {
            $notify[] = ['error', 'Your balance is not sufficient'];
            return back()->withNotify($notify);
        }

        $tree = new TreeInvestLab($user, $project);
        $tree->invest($request->quantity);

        $notify[] = ['success', 'Invested to project successfully'];
        return to_route('user.invest.log')->withNotify($notify);
    }

    public function log()
    {
        $pageTitle = 'Invest Log';
        $invests   = Invest::searchable(['trx', 'project:name'])->filter(['project:is_dispatch'])->where('user_id', auth()->id())->orderBy('id', 'desc')->with('project.timeSetting')->paginate(getPaginate());
        return view('Template::user.invest.log', compact('pageTitle', 'invests'));
    }

    public function details($id)
    {
        $pageTitle    = 'Investment Details';
        $invest       = Invest::with('project', 'user')->where('user_id', auth()->id())->findOrFail(decrypt($id));
        $transactions = Transaction::where('invest_id', $invest->id)->orderBy('id', 'desc')->paginate(getPaginate());
        return view('Template::user.invest.details', compact('pageTitle', 'invest', 'transactions'));
    }
}
