<?php

namespace App\Lib;

use App\Constants\Status;
use App\Models\AdminNotification;
use App\Models\Invest;
use App\Models\Referral;
use App\Models\Transaction;
use App\Models\User;
use Carbon\Carbon;


class PlanInvest
{
    /**
    * Instance of investor user
    *
    * @var object
    */
    private $user;

    /**
    * Plan which is purchasing
    *
    * @var object
    */
    private $plan;

    /**
    * Set some properties
    *
    * @param object $user
    * @param object $plan
    * @return void
    */
    public function __construct($user, $plan)
    {
        $this->user = $user;
        $this->plan = $plan;
    }

    /**
    * Invest process
    *
    * @param float $amount
    * @return void
    */
    public function invest($amount){
        $plan = $this->plan;
        $user = $this->user;
        $time = $plan->time;

        $user->balance -= $amount;
        $user->save();

        $trx                       = getTrx();
        $transaction               = new Transaction();
        $transaction->user_id      = $user->id;
        $transaction->amount       = $amount;
        $transaction->post_balance = $user->balance;
        $transaction->charge       = 0;
        $transaction->trx_type     = '-';
        $transaction->details      = 'Invested on ' . $plan->name;
        $transaction->trx          = $trx;
        $transaction->remark       = 'invest';
        $transaction->save();

        $interestAmount = ($amount * $plan->interest) / 100;
        $next           = Carbon::parse(now())->addHours($time->time)->toDateTimeString();

        $invest            = new Invest();
        $invest->user_id   = $user->id;
        $invest->plan_id   = $plan->id;
        $invest->amount    = $amount;
        $invest->interest  = $interestAmount;
        $invest->time_name = $time->name;
        $invest->hours     = $time->time;
        $invest->next_time = $next;
        $invest->status    = Status::INVEST_RUNNING;
        $invest->trx       = $trx;
        $invest->save();

        if (gs()->invest_commission == Status::ENABLE) {
            $commissionType = 'invest_commission';
            self:: levelCommission($user, $amount, $commissionType, $trx);
        }

        notify($user, 'INVESTMENT', [
            'trx'             => $invest->trx,
            'amount'          => showAmount($amount),
            'plan_name'       => $plan->name,
            'interest_amount' => showAmount($interestAmount),
            'time_name'       => $time->name,
            'ends_in'         => $invest->next_time,
            'post_balance'    => showAmount($user->balance),
        ]);


        $adminNotification            = new AdminNotification();
        $adminNotification->user_id   = $user->id;
        $adminNotification->title     = curSym().' '.showAmount($amount).' invested to '.$plan->name;
        $adminNotification->click_url = route('admin.report.invest.history')."?search=$user->username&status=".Status::INVEST_RUNNING;
        $adminNotification->save();
    }

    /**
    * Give referral commission
    *
    * @param object $user
    * @param float $amount
    * @param string $commissionType
    * @param string $trx
    * @return void
    */

    public static function levelCommission($user, $amount, $commissionType, $trx){

        $meUser       = User::where('id',$user->id)->with('referrer')->firstOrFail();
        $i            = 1;
        $level        = Referral::where('commission_type',$commissionType)->count();
        $transactions = [];

        while ($i <= $level) {
            $me    = $meUser;
            $refer = $me->referrer;
            if ($refer == "") {
                break;
            }

            $commission = Referral::where('commission_type',$commissionType)->where('level', $i)->first();
            if (!$commission) {
                break;
            }

            $com             = ($amount * $commission->percent) / 100;
            $refer->balance += $com;
            $refer->save();

            if($commissionType == 'deposit_commission'){
                $comType = 'Deposit';
            }elseif($commissionType == 'interest_commission'){
                $comType = 'Interest';
            }else{
                $comType = 'Invest';
            }

            $transactions[] = [
                'user_id'      => $refer->id,
                'amount'       => $com,
                'post_balance' => $refer->balance,
                'charge'       => 0,
                'trx_type'     => '+',
                'details'      => "level $i Referral $comType Commission From $user->username",
                'trx'          => $trx,
                'remark'       => 'referral_commission',
                'created_at'   => now()
            ];



            notify($refer, 'REFERRAL_COMMISSION', [
                'amount'       => showAmount($com),
                'post_balance' => showAmount($refer->balance),
                'trx'          => $trx,
                'level'        => ordinal($i),
                'type'         => $comType
            ]);

            $meUser = $refer;
            $i++;
        }

        if (!empty($transactions)) {
            Transaction:: insert($transactions);
        }
    }


}
