<?php


namespace App\Http\Controllers\Api\User;

use App\Models\Plan;
use App\Models\RuningPlan;
use App\Models\Transaction;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Api\User\Auth\AuthController;

class PackageController extends Controller
{
    public function index() {
        $control = gs();
        $user = auth()->user();
        $packages = Plan::where('status', 1)->get();
        $imgPath = asset('assets/images/plan');
        return response()->json(['packages' => $packages, 'user'=> $user, 'imgPath'=>$imgPath, 'control'=>$control]);
    }

    // purchase package
    public function buyPackage(Request $request) {
        $request->validate([
            'id' => 'required',
        ]);

        $control = gs();

        $plan = Plan::where('status', 1)->findOrFail($request->id);
        $user = auth()->user();

        if ($plan->price > $user->balance) {
            $notify = 'Oops! You\'ve no sufficient balance!';
            return response()->json(['msg'=>$notify, 'cls'=>'error']);
        }
        $user->balance -= $plan->price;
        // $user->collect_date = Carbon::yesterday();
        $user->save();

        $runingPlans = new RuningPlan();
        $runingPlans->user_id = auth()->user()->id;
        $runingPlans->plan_id = $plan->id;
        $runingPlans->amount = $plan->price;
        $runingPlans->daily_profit = $plan->daily_profit;
        $runingPlans->validity = now()->addDays($plan->validity);
        $runingPlans->status = 1;
        $runingPlans->save();

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

        levelCommission($user, $plan->price, 'plan_subscribe_commission', $trx);

        notify($user, 'BUY_PLAN', [
            'plan_name'    => $plan->name,
            'amount'       => showAmount($plan->price),
            'trx'          => $trx,
            'post_balance' => showAmount($user->balance),
        ]);

        $notify = 'Purchase successfull!';
        return response()->json(['msg'=>$notify, 'cls'=>'success', 'control'=>$control]);

    }


    public function runingPackages() {
        $control = gs();
        $user = auth()->user();
        $data['runingPackages'] = RuningPlan::with('plan')->where('user_id', $user->id)->latest()->paginate(10);
        return response()->json(['user'=>$user, 'data'=>$data, 'control'=>$control]);
    }
}

