<?php

namespace App\Http\Controllers;
use App\Models\User;
use Inertia\Inertia;
use App\Domain\Points\Models\Point;
use App\Domain\Feeds\Service\LiveFeed;
use Illuminate\Support\Facades\Request;
use App\Domain\Users\Models\UserPackage;
use Illuminate\Support\Facades\Redirect;
use App\Domain\Points\Enums\DirectionEnum;
use App\Notifications\UserCustomPaidSubscription;
use App\Domain\Subscriptions\Service\SubscriptionService;

class UserPackageController extends Controller
{
    public function __construct()
    {
        $this->middleware('subs.paid')->except('show');
    }

    public function update()
    {
        $id_packet = request()->post('id');
        if($id_packet){
            $customPackage = UserPackage::find($id_packet);
        }else{
            $customPackage = new UserPackage;
        }

        $customPackage->price = request()->post('price');
        $customPackage->user_id = auth()->user()->id;
        $customPackage->save();

        return Redirect::back()->with('success', 'Успешно обновлено');
    }

    public function subs() {

        $id_packet = request()->post('packet_id');
        $customPackage = UserPackage::find($id_packet);

        $balance = SubscriptionService::calculate(auth()->user()->id);
        if ($customPackage->price > $balance) {
            return Redirect::back()->with('error', 'Недостаточно средств!');
        }

        \DB::beginTransaction();

        $userPackage = User::find($customPackage->user_id);

        $check = \DB::table('users_subscribers')
            ->where('user_id', auth()->user()->id)
            ->where('subscriber_id', $customPackage->user_id)
            ->first();

            // в буд. по рефакторить, по сути сейчас этот код выполняется один раз
            // дальше пользователю нужно отписаться, и заново купить подписку!
        if(empty($check)){
            auth()->user()->subscribers()->toggle([$userPackage->id]);
            LiveFeed::addBySub($userPackage);
        }


        \DB::table('users_package_customers')->insert([
            'user_id' => $customPackage->user_id,
            'customer_id' => auth()->user()->id,
            'package_id' => $customPackage->id,
            'price' => $customPackage->price,
            // 'time_end' => now()->addMonths(),
            'time_end' => now()->addMinutes(10),
            'created_at' => now(),
        ]);


        $point = new Point;
        $point->user_id = auth()->user()->id;
        $point->point = $customPackage->price;
        $point->type = 'Оформлена подписка на пользователя: ' . $userPackage->name . ' (' . $userPackage->username . ')'; //YSV ENUM!
        $point->direction = DirectionEnum::EXPENSE();
        $point->save();

        $point = new Point;
        $point->user_id = $userPackage->id;
        $point->point = $customPackage->price;
        $point->type = 'Пользователь оформил платную подписку: ' . auth()->user()->name . ' (' . auth()->user()->username . ')'; //YSV ENUM!
        $point->direction = DirectionEnum::COMING();
        $point->save();

        \DB::commit();

        $message = [
            'user_id' => auth()->user()->id,
            'node_id' => null,
        ];
        $userPackage->notify(new UserCustomPaidSubscription($message));

        return Redirect::back()->with('success', 'Подписка на пользователя успешно оформлена');

    }
}
