<?php

namespace App\Livewire\Account;

use App\Models\Plan;
use App\Utils\HandlesEarn;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Validate;
use Livewire\Component;

#[Layout('components.layouts.account-inner', ['title' => 'Invest'])]
class Earn extends Component
{
    use HandlesEarn;

    public Plan $plan;

    #[Validate('required|numeric|gt:0')]
    public $amount;
    public $selected;

    public function render() {
        return view('livewire.account.earn', [
            'plans' => Plan::active()->get(),
        ]);
    }

    public function select($plan_id) {
        $this->plan = Plan::find($plan_id);
    }

    public function invest() {
        $this->validate();
        $planCoin = $this->plan->coin;
        $user = auth_user();

        if(!$user->can_invest) {
            return $this->dispatchAlert('Your account is not eligible to invest. To start investing, please contact our support team.');
        }
        
        if($this->balanceIsInsufficient()) {
            return $this->dispatchAlert($this->insufficientBalance($planCoin));
        }
        
        if($this->amountIsLessThanMinimum()) {
            return $this->dispatchAlert($this->notInvestmentAmount($this->plan, 'minimum'));
        }

        if($this->amountIsGreaterThanMaximum()) {
            return $this->dispatchAlert($this->notInvestmentAmount($this->plan, 'maximum'));
        }

        $planCoin->user_balance->decrement('value', $this->amount);
        
        $this->createInvestment();
        
        $this->dispatch('investment-completed');
        return $this->dispatchAlert('Investment Processed Successfully.');
    }
}
