<?php

namespace App\Http\Controllers\Invest\User;

use App\Exceptions\Invest\User\BasickycInvestErrorException;
use App\Exceptions\Invest\User\InvestDisablePurchaseException;
use App\Exceptions\Invest\User\InvestNoBalanceException;
use App\Exceptions\Invest\User\InvestNoFundsException;
use App\Exceptions\Invest\User\InvestNoPlanException;
use App\Exceptions\Invest\User\InvestWrongException;

use App\Helpers\MsgState;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Invest\User\PreviewInvestRequest;
use App\Services\Investment\User\IvInvestService;

class InvestController extends Controller
{
    private $investService;

    public function __construct(
        IvInvestService $investService    
    ) {
        $this->investService = $investService;
    }

    public function showPlans(Request $request, $ucode = null)
    {     
        try {
            return view("investment.user.invest",  $this->investService->getShowPlans($request, $ucode));
        } catch (InvestDisablePurchaseException $e) {
            $errors = MsgState::of('disable', 'invest');
            return view("investment.user.invest.errors", $errors);
        } catch(BasickycInvestErrorException $e) {
            $errors = module_msg_of('invest', 'error', 'BasicKYC');
            return view("investment.user.invest.errors", $errors);
        } catch (InvestNoPlanException $e) {
            $errors = MsgState::of('no-plan', 'invest');
            return view("investment.user.invest.errors", $errors);
        } catch (InvestNoBalanceException $e) {
            $errors = MsgState::of('no-balance', 'invest');
            return view("investment.user.invest.errors", $errors);
        } catch (InvestNoFundsException $e) {        
            $errors = MsgState::of('no-funds', 'invest');
            return view("investment.user.invest.errors", $errors);
        }
    }

    public function previewInvest(PreviewInvestRequest $request)
    {
        try {
            $data = $request->validated();
            return view("investment.user.invest.preview", $this->investService->getPreviewInvest($data));
        } catch (InvestNoFundsException $e) {
            $errors = MsgState::of('no-funds', 'invest');
            return view("investment.user.invest.failed", $errors);
        }
    }

    public function confirmInvest(Request $request)
    {   
        try {
           $invest = $this->investService->getConfirmInvest($request);
           return view("investment.user.invest.success", compact('invest'));
        } catch (InvestWrongException $e) {
            $errors = MsgState::of('wrong', 'invest');
            return view("investment.user.invest.failed", $errors);
        }
    }

    public function cancelInvestment($id, Request $request)
    {
        $this->investService->getCancelInvestment($id, $request);
        return response()->json(['msg' => __('Investment cancelled successfully!')]);
    }

}
