<?php

namespace App\Http\Controllers;

use App\Models\User;
use Inertia\Inertia;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Request;
use Illuminate\Database\Eloquent\Builder;
use App\Domain\Feeds\Queries\FeedQueryBuilder;
use App\Domain\Users\Service\ProfileDataService;
use App\Domain\Users\DataTransferObjects\UserData;
use App\Domain\Subscriptions\Service\SubscriptionService;
use Carbon\Carbon;

class ProfileController extends Controller
{

    public function __construct()
    {
        abort_if(Str::contains(request()->url(), 'inner_systemuser_api'), 404);
        $this->middleware('subs.paid')->except('profile');
    }

    public function profile($username)
    {

        $user = User::where('username', $username)->firstOrFail();
        $authUserActiveSubscription = nova_get_setting('vote_paid_mode') ? SubscriptionService::activeSubscription() : true;

        $packet = null;
        $packageCompleted = false;

        if($user->private && auth()->user()){
            $packet = $user->customPackage;
            if($packet){
                $check = \DB::table('users_package_customers')
                ->where('user_id', $user->id)
                ->where('customer_id', auth()->user()->id)
                ->where('package_id', $packet->id)
                ->where('time_end', '>', now())
                ->count();
                $packageCompleted = $check > 0 ? true : false;
            }
        }

        $userData = UserData::fromModel($user);
        if($userData->is_auth_user){
            $feeds = (new FeedQueryBuilder($user->feeds()))->enableAdvertising()->disableActiveFeed()->order()->build();
        }else{
            $feeds = (new FeedQueryBuilder($user->feeds()))->enableAdvertising()->order()->build();
        }

        $nextCursor = $feeds->nextCursor;
        $feeds = $feeds->transformData();

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

        $profileData = ProfileDataService::get($user);
        // $testPeriod = auth()->user()->testPeriodCheck();
        if(auth()->user()){
            $limitLeader = auth()->user()->subscribers()->where('leader', 1)->count() === nova_get_setting('vote_leader_count');
        }else{
            $limitLeader = false;
        }



        return Inertia::render('Profile/Index', [
            // 'testPeriod' => $testPeriod,
            'user' => array_merge([
                'about' => $user->about,
                'is_sub' => $user->is_sub,
            ], $userData->toArray()),
            'packet' => $packet,
            'authUserActiveSubscription' => $authUserActiveSubscription,
            'packageCompleted' => $packageCompleted,
            'feeds' => $feeds,
            'nextCursor' => $nextCursor,
            'limitLeader' => $limitLeader,
            'is_leader' => $profileData->is_leader,
            'close_account' => $profileData->close_account,
            'counts' => [
                'feeds' => $profileData->count_feeds,
                'subscribers' => $profileData->count_subscribers,
                'readers' => $profileData->count_readable,
            ]
        ]);
    }

    public function profileReaders($username)
    {
        $user = User::where('username', $username)->firstOrFail();
        $limitLeader = auth()->user()->subscribers()->where('leader', 1)->count() === nova_get_setting('vote_leader_count');

        $profileData = ProfileDataService::get($user);

        $packageCompleted = false;

        $authUserActiveSubscription = nova_get_setting('vote_paid_mode') ? SubscriptionService::activeSubscription() : true;

        if($user->private){
            $packet = $user->customPackage;
            if($packet){
                $check = \DB::table('users_package_customers')
                ->where('user_id', $user->id)
                ->where('customer_id', auth()->user()->id)
                ->where('package_id', $packet->id)
                ->where('time_end', '>', now())
                ->count();
                $packageCompleted = $check > 0 ? true : false;
            }

        }

        $myPaidListSubscribeTo = \DB::table('users_package_customers')
            ->latest()
            ->where('customer_id', auth()->user()->id)->get()->groupBy('user_id');

        $myPaidListSubscribeTo = $myPaidListSubscribeTo->map(function($item){
            $first = $item->first();
            $first->expired = Carbon::parse($first->time_end) < now();
            return Carbon::parse($first->time_end) < now();
        });
        // dd($myPaidListSubscribeTo);


        $leader = Request::get('leader');
        if($leader === '1'){
            $readers = $user->subscribersOn();
        }elseif ($leader === '0') {
            $readers = $user->subscribersOff();
        }else{
            $readers = $user->subscribers();
        }
        $readers = $readers->filter(Request::only('search'))
            ->orderBy('id', 'desc')
            ->cursorPaginate(User::PAGINATE);
        $nextCursor = get_cursor_hash($readers);

        $readers->transform(function ($user) {
            return array_merge([
                'is_leader' => (boolean) $user->pivot->leader,
            ], UserData::fromModel($user)->toArray());
        });

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

        return Inertia::render('Profile/Readers', [
            'nextCursor' => $nextCursor,
            'user' => array_merge([
                'about' => $user->about,
                'is_sub' => $user->is_sub,
            ], UserData::fromModel($user)->toArray()),
            'packageCompleted' => $packageCompleted,
            'filters' => Request::all('search', 'leader'),
            'readers' => $readers->items(),
            'limitLeader' => $limitLeader,
            'authUserActiveSubscription' => $authUserActiveSubscription,
            'is_leader' => $profileData->is_leader,
            'close_account' => $profileData->close_account,
            'myPaidListSubscribeTo' => $myPaidListSubscribeTo,
            'counts' => [
                'feeds' => $profileData->count_feeds,
                'subscribers' => $profileData->count_subscribers,
                'readers' => $profileData->count_readable,
            ]
        ]);

    }

    public function profileSubs($username)
    {
        $user = User::where('username', $username)->firstOrFail();
        $limitLeader = auth()->user()->subscribers()->where('leader', 1)->count() === nova_get_setting('vote_leader_count');
        $profileData = ProfileDataService::get($user);
        $sub = Request::get('sub');

        $authUserActiveSubscription = nova_get_setting('vote_paid_mode') ? SubscriptionService::activeSubscription() : true;


        $packageCompleted = false;

        if($user->private){
            $packet = $user->customPackage;
            if($packet){
                $check = \DB::table('users_package_customers')
                ->where('user_id', $user->id)
                ->where('customer_id', auth()->user()->id)
                ->where('package_id', $packet->id)
                ->where('time_end', '>', now())
                ->count();
                $packageCompleted = $check > 0 ? true : false;
            }

        }

        if($sub !== null){
            $query = '';
            $typeSub = $sub === '1' ? '<>' : '=';

            $subscribers = $user->subscriber_reverse()
            ->withCount([
                'subscriber_reverse as pizda' => function (Builder $builder) use (&$query) {
                    $query = $builder;
                    $query->where('user_id', auth()->user()->id);
                },
            ])
           ->whereRaw("({$query->toSql()}) {$typeSub} ?", [$user->id, 0])

           ->filter(Request::only('search'))
           ->orderBy('id', 'desc')
           ->cursorPaginate(User::PAGINATE);
            $subscribers->transform(function ($user) use ($sub) {
                return array_merge([
                    'is_sub' => (boolean) $sub,
                ], UserData::fromModel($user)->toArray());
            });
        }else{
            $subscribers = $user->subscriber_reverse()
            ->withCount(['subscriber_reverse as is_sub' => function (Builder $query)  {
                $query->where('user_id', auth()->user()->id);
            }])
            ->withCasts(['is_sub' => 'boolean'])
            ->filter(Request::only('search'))
            ->orderBy('id', 'desc')
            ->cursorPaginate(User::PAGINATE);

            $subscribers->transform(function ($user) {
                return array_merge([
                    'is_sub' => $user->is_sub,
                ], UserData::fromModel($user)->toArray());
            });
        }

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

        return Inertia::render('Profile/Subs', [
            'user' => array_merge([
                'about' => $user->about,
                'is_sub' => $user->is_sub,
            ], UserData::fromModel($user)->toArray()),
            'packageCompleted' => $packageCompleted,
            'authUserActiveSubscription' => $authUserActiveSubscription,
            'filters' => Request::all('search', 'sub'),
            'limitLeader' => $limitLeader,
            'is_leader' => $profileData->is_leader,
            'subscribers' => $subscribers->items(),
            'close_account' => $profileData->close_account,
            'counts' => [
                'feeds' => $profileData->count_feeds,
                'subscribers' => $profileData->count_subscribers,
                'readers' => $profileData->count_readable,
            ]
        ]);
    }


}
