<?php

namespace App\Http\Controllers;

use Inertia\Inertia;
use App\Notifications\LikeAdded;
use App\Domain\Feeds\Models\Feed;
use App\Domain\Points\Models\Point;
use App\Notifications\PurchaseAdded;
use Illuminate\Support\Facades\Redirect;
use App\Domain\Points\Enums\DirectionEnum;
use App\Domain\Feeds\Queries\FeedQueryBuilder;
use App\Domain\Feeds\Service\FeedMediaTransform;
use App\Domain\Subscriptions\Service\SubscriptionService;

class FeedsController extends Controller
{

    public function __construct()
    {
        $this->middleware('subs.paid')->except('comments', 'commentsShowChildren', 'add_view_feed');
    }

    public function index()
    {
        $feeds = (new FeedQueryBuilder(auth()->user()->live_feeds()))->enableAdvertising()->build();
        $nextCursor = $feeds->nextCursor;
        $feeds = $feeds->transformData();

        if(request()->wantsJson()){
            return ['collections' => $feeds, 'next' => $nextCursor];
        }

        return Inertia::render('Feed/Index', [
            'feeds' => $feeds,
            'nextCursor' => $nextCursor,
            'active_button' => ''
        ]);
    }

    public function onlyImages()
    {
        $feeds = (new FeedQueryBuilder(auth()->user()->live_feeds()))->enableAdvertising()->addType('image')->build();
        $nextCursor = $feeds->nextCursor;
        $feeds = $feeds->transformData();

        if(request()->wantsJson()){
            return ['collections' => $feeds, 'next' => $nextCursor];
        }

        return Inertia::render('Feed/Index', [
            'feeds' => $feeds,
            'nextCursor' => $nextCursor,
            'active_button' => 'image'
        ]);
    }

    public function onlyVideos()
    {
        $feeds = (new FeedQueryBuilder(auth()->user()->live_feeds()))->enableAdvertising()->addType('video')->build();
        $nextCursor = $feeds->nextCursor;
        $feeds = $feeds->transformData();

        if(request()->wantsJson()){
            return ['collections' => $feeds, 'next' => $nextCursor];
        }

        return Inertia::render('Feed/Index', [
            'feeds' => $feeds,
            'nextCursor' => $nextCursor,
            'active_button' => 'video'
        ]);
    }
    public function onlyMusics()
    {
        $feeds = (new FeedQueryBuilder(auth()->user()->live_feeds()))->enableAdvertising()->addType('music')->build();
        $nextCursor = $feeds->nextCursor;
        $feeds = $feeds->transformData();

        if(request()->wantsJson()){
            return ['collections' => $feeds, 'next' => $nextCursor];
        }

        return Inertia::render('Feed/Index', [
            'feeds' => $feeds,
            'nextCursor' => $nextCursor,
            'active_button' => 'music'
        ]);
    }


    public function toggleLike($feed_id)
    {
        $auth_user = auth()->user();
        $feed = Feed::findOrFail($feed_id);
        $check = \DB::table('users_feeds_like')->where('user_id', $auth_user->id)->where('feed_id', $feed_id)->first();
        // $check_notifications = \DB::table('notifications')
        // ->where('notifiable_id', $auth_user->id)
        // ->where('entity_once', $feed_id)
        // ->where('once', 1)
        // ->first();

        $auth_user->likes()->toggle([$feed_id]);

        if(!$check && $feed->user_id !== $auth_user->id){
            $message = [
                'user_id' => $auth_user->id,
                'node_id' => $feed_id,
            ];
            $feed->user->notify(new LikeAdded($message));
        }

        return Redirect::back();
    }

    public function audioLike($media_id)
    {
        sleep(1);
        auth()->user()->audioLike()->toggle([$media_id]);
        return Redirect::back();
    }

    public function purchase($feed_id)
    {
        \DB::beginTransaction();
        $feed = Feed::findOrFail($feed_id);
        $price_feed = (int) $feed->price;
        $balance = SubscriptionService::calculate(auth()->user()->id);
        $check = \DB::table('user_feed_purchase')->where('user_id', auth()->user()->id)->where('feed_id', $feed_id)->first();
        if ($check) {
            return ['error' => 1, 'msg' => 'Вы уже купили данный продукт'];
        }
        if ($feed->user()->is(auth()->user())) {
            return ['error' => 1, 'msg' => 'Ошибка'];
        }
        if ($price_feed > $balance) {
            return ['error' => 1, 'msg' => 'Недостаточно средств'];
        }
        $user = auth()->user();
        $user->purchases()->attach($feed_id, ['amount' => $price_feed]);

        $point = new Point;
        $point->user_id = $user->id;
        $point->feed_id = $feed->id;
        $point->point = $price_feed;
        $point->type = 'Покупка - ' . $feed->type; //YSV ENUM!
        $point->direction = DirectionEnum::EXPENSE();
        $point->save();

        $point = new Point;
        $point->user_id = $feed->user_id;
        $point->feed_id = $feed->id;
        $point->point = $price_feed;
        $point->type = 'Покупка - ' . $feed->type; //YSV ENUM!
        $point->direction = DirectionEnum::COMING();
        $point->save();

        $new_medias = $this->replace(null, $feed);

        $message = [
            'user_id' => auth()->user()->id,
            'node_id' => $feed->id,
            'price' => $price_feed,
        ];
        $feed->user->notify(new PurchaseAdded($message));

        \DB::commit();

        return $new_medias;
    }

    public function replace($feed_id = null, $feed = null)
    {
        if(empty($feed)){
            $feed = Feed::findOrFail($feed_id);
        }

        $preview = '';
        $medias = [];

        if($feed->is_paid === 1){
            $mediaTransform = new FeedMediaTransform($feed);
            $mediaTransform = $mediaTransform->paid()->spot();
            $preview = $mediaTransform['preview'];
            $medias = $mediaTransform['medias'];
        }

      return ['preview' => $preview, 'collection' => $medias];

    }


    public function purchase_check($feed_id)
    {
        $check = \DB::table('user_feed_purchase')->where('user_id', auth()->user()->id)->where('feed_id', $feed_id)->first();
        if ($check) {
            return 1;
        }
        return 0;
    }


    public function add_view_feed($feed_id)
    {
        if(!auth()->check()){
            return 0;
        }

        $check = \DB::table('users_feeds_view')->where('user_id', auth()->user()->id)->where('feed_id', $feed_id)->first();
        if(!$check){
            \DB::table('users_feeds_view')->insert([
                'user_id' => auth()->user()->id,
                'feed_id' => $feed_id
            ]);
            $feed = Feed::findOrFail($feed_id);
            $feed->increment('views_count');
            return 1;
        }else{
            return 0;
        }

    }

    public function destroy(Feed $feed)
    {
        if ($feed->user()->is(auth()->user())) {
            $feed->delete();
        }

        return Redirect::route('profile.user', auth()->user()->username)->with('success', 'Запись успешно удалена!');
    }


}
