<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use App\Models\User;
use Inertia\Inertia;
use Illuminate\Http\Request as HttpRequest;
use App\Domain\Subscriptions\Models\Package;
use App\Domain\Feeds\Queries\FeedQueryBuilder;
use App\Domain\Subscriptions\Service\SubscriptionService;

class SettingController extends Controller
{

    const NOTIFICATION_THRESHOLD = 20;

    public function index()
    {
        $user = auth()->user();

        return Inertia::render('Settings/SettingsProfile', [
            'user' => [
                'id' => $user->id,
                'name' => $user->name,
                'username' => $user->username,
                'first_name' => $user->first_name,
                'last_name' => $user->last_name,
                'email' => $user->email,
                'user_char' => $user->user_char,
                'color' => $user->color,
                'sex' => $user->sex,
                'type' => $user->type,
                'phone' => $user->phone,
                'date_of_birth' => $user->date_of_birth,
                'photo_path' => $user->photo_path,
                'banner_path' => $user->banner_path,
                'about' => $user->about,
                'private' => $user->private,
                'inn' => $user->inn,
                'checking_account' => $user->checking_account,
                'bik' => $user->bik,
                // 'allow_adult_content' => $user->allow_adult_content,
            ],
        ]);
    }

    public function notify()
    {
        auth()->user()->unreadNotifications()->update(['read_at' => Carbon::now()]);

        $notifications = auth()->user()
            ->notifications()
            ->latest()
            ->take(self::NOTIFICATION_THRESHOLD)
            ->get();

        $notifications_transform = [];
        foreach ($notifications as $notification) {
            $d = [];
            $data = $notification->data;

            if($notification->notifiable_type === User::class){
                if($notification->type === 'App\Notifications\LikeAdded'){
                    $d['type'] = 'like';
                }
                if($notification->type === 'App\Notifications\CommentAdded'){
                    $d['type'] = 'comment';
                }
                if($notification->type === 'App\Notifications\Subscribed'){
                    $d['type'] = 'subs';
                }
                if($notification->type === 'App\Notifications\LeaderChoice'){
                    $d['type'] = 'leader';
                }
                if($notification->type === 'App\Notifications\UserCustomPaidSubscription'){
                    $d['type'] = 'custom-paid-subs';
                }
                if($notification->type === 'App\Notifications\PurchaseAdded'){
                    $d['type'] = 'purchase';
                }
                if($notification->type === 'App\Notifications\RemoveFeed'){
                    $d['type'] = 'remove-feed';
                }
                if($notification->type === 'App\Notifications\BannedMessageFeed'){
                    $d['type'] = 'banned-message-feed';
                }
                $user_who = User::find($data['user_id']);
                if(empty($user_who)){
                    $notification->delete();
                    continue;
                }

                $d['user'] =  [
                    'id' => $user_who->id,
                    'name' => $user_who->name,
                    'username' => $user_who->username,
                    'photo_path' => $user_who->photo_path,
                    'color' => $user_who->color,
                    'user_char' => $user_who->user_char,
                ];

                if(@$data['node_id']){
                     $feed = new FeedQueryBuilder;
                     $d['feed'] = $feed->selectByIds($data['node_id'])->disableActiveFeed()->withTrashed()->transformGet()->first();
                }else{
                    $d['feed'] = '';
                }

                $d['data'] = $data;
                $d['id'] = $notification->id;
                $d['created_at'] = $notification->created_at->diffForHumans();
            }
            $notifications_transform[] = $d;
        }

        return Inertia::render('Settings/SettingsNotify', [
            'notifications' => $notifications_transform,
        ]);
    }

    public function money()
    {
        $user = auth()->user();
        $points = $user
            ->points()
            ->orderBy('id', 'desc')
            ->cursorPaginate(User::PAGINATE);

        $nextCursor = get_cursor_hash($points);

        $points->each(function($line){
            $dt = explode(' ', $line->created_at);
            $line->date = $dt[0];
            $line->time = $dt[1];
            return $line;
        });

        if(request()->wantsJson()){
            return ['collections' => $points->items(), 'next' => $nextCursor];
        }
        return Inertia::render('Settings/SettingsMoney', [
            'points' => $points->items(),
            'nextCursor' => $nextCursor,
        ]);
    }

    public function tarif()
    {

        $user = auth()->user();
        $is_active = SubscriptionService::activeSubscription();
        $user_id = $user->id;
        $user_autosubscription = $user->autosubscription_site;

        $plans = Package::all();
        $lastSubscription = $user->subscription->first();

        if ($lastSubscription) {
            $lastSubscription->setRelation('package', $plans->where('id', $lastSubscription->package_id)->first());
            $lastSubscription->endDateTime = $lastSubscription->ends_at->format('Y-m-d');
        }

        return Inertia::render('Settings/SettingsTarif', [
            'plans' => $plans,
            'is_active_sub' => $is_active,
            'user_autosubscription' => $user_autosubscription,
            'user_id' => $user_id,
            'lastSubscription' => $lastSubscription,
        ]);
    }


    public function likes()
    {

        $feeds = (new FeedQueryBuilder(auth()->user()->likes()))->order()->build();
        $nextCursor = $feeds->nextCursor;
        $feeds = $feeds->transformData();

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

        return Inertia::render('Settings/SettingsLikes', [
            'feeds' => $feeds,
            'nextCursor' => $nextCursor,
        ]);
    }


    public function payouts()
    {

        $user = auth()->user();
        // $requisites = [];
        // $bankRequisites = $user->bank_requisites->first();
        // if($bankRequisites){
        //     $requisites['id'] = $bankRequisites->id;
        //     $requisites['number'] = $bankRequisites->number;
        // }
        $withdrawals = $user->withdrawals()
        ->orderBy('id', 'desc')
        ->cursorPaginate(User::PAGINATE);


        $nextCursor = get_cursor_hash($withdrawals);

        $statusCode = [
            'pending' => 'Запрос отправлен',
            'success' => 'Запрос выполнен',
            'cancel' => 'Отмена выплаты',
        ];

        $withdrawals->each(function($line) use($statusCode) {
            $dt = explode(' ', $line->created_at);
            $line->datePart = $dt[0];
            $line->timePart = $dt[1];
            $line->meta =  'Статус: ' . $statusCode[$line->status];
            $line->history_payment_details = nl2br($line->history_payment_details);
            return $line;
        });

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

        return Inertia::render('Settings/SettingsPayouts', [
            // 'requisites' => $requisites,
            'isVerified' => $user->isVerified(),
            'withdrawals' => $withdrawals->items()
        ]);

    }

    public function packet()
    {
        $user = auth()->user();
        $userPackage = $user->customPackage;

        $purchased_subscriptions_by_users = \DB::table('users_package_customers')
        ->where('user_id', auth()->user()->id)->orderBy('customer_id')->orderBy('time_end', 'desc')->get();

        $purchased_subscriptions_by_users = $purchased_subscriptions_by_users->groupBy('customer_id');




        $subscriptions_by_users = \DB::table('users_package_customers')
        ->join('users_subscribers', 'users_package_customers.customer_id', '=', 'users_subscribers.user_id')
        ->select('users_package_customers.*', 'users_subscribers.autosubscription', 'users_subscribers.user_id as usId', 'users_subscribers.subscriber_id as subsId')
        ->where('users_package_customers.customer_id', auth()->user()->id)
        ->orderBy('users_package_customers.user_id')
        ->orderBy('users_package_customers.time_end', 'desc')
        ->get();

        $subscriptions_by_users = $subscriptions_by_users->filter(function ($item) {
            return $item->user_id === $item->subsId && $item->customer_id === $item->usId;
        });


        // $subscriptions_by_users = \DB::table('users_package_customers')
        // ->where('customer_id', auth()->user()->id)
        // ->orderBy('user_id')
        // ->orderBy('time_end', 'desc')
        // ->get();

        $subscriptions_by_users = $subscriptions_by_users->groupBy('user_id');


        $buyers = $this->getPacketUsers($purchased_subscriptions_by_users);

        $subscriptions = $this->getPacketUsers($subscriptions_by_users);




        return Inertia::render('Settings/SettingsPacket', [
            'user' => $user,
            'packet' => $userPackage,
            'buyers' => $buyers->values()->toArray(),
            'subscriptions' => $subscriptions->values()->toArray(),
        ]);
    }


    protected function getPacketUsers($subscriptions)
    {

        $ids_customer = $subscriptions->keys();
        $users_customer = User::whereIn('id', $ids_customer)->get();

        return $subscriptions->map(function ($items, $id) use($users_customer) {
            $new = [];
            $new['active'] = false;
            $new['autosubscription'] = false;
            $new['user'] = $users_customer->where('id', $id)->first()
            ->only([
                'id', 'first_name', 'last_name',
                'color', 'user_char', 'username', 'photo_path'
            ]);
            foreach($items as $item){
                // dd($items);
                $carbon = \Carbon\Carbon::parse($item->time_end);
                $active = now() < $carbon;
                if($active){
                    $new['active'] = $active;
                }
                $new['autosubscription'] = $item->autosubscription ?? false;
                $new['lists'][] = ['time_end' => $carbon->format('d.m.Y'), 'price' => $item->price, 'active' => $active];
            }
            return $new;

        });
        // dd($test);

        // return $subscriptions->map(function ($item) use($users_customer,$type) {
        //     $carbon = \Carbon\Carbon::parse($item->time_end);

        //     return [
        //         'id' => $item->id,
        //         'price' => $item->price,
        //         'time_end' => $carbon->format('d.m.Y'),
        //         'active' => now() < $carbon,
        //         'user' => $users_customer->first(function ($value) use($item,$type) {
        //             return $value->id == $item->{$type};
        //         })->toArray()
        //     ];
        // });
    }

    public function verification(HttpRequest $request)
    {

        $document = $request->user()->getMedia('documents');

        $first_document = $document->first();
        $doc_uuid = null;
        if($first_document){
            $doc_uuid = $first_document->uuid;
        }

        $user = auth()->user();
        $isPhoneVerify = $user->phone_verified;
        $isPassportVerified = $user->passport_verified;

        if (!empty($user->phone_verify_token) && $user->phone_verify_token_expire && $user->phone_verify_token_expire->gt(now())) {
            $isToken = true;
        }else{
            $isToken = false;
        }

        return Inertia::render('Settings/SettingsVerification', [
            'docUuid' => $doc_uuid,
            'isToken' => $isToken,
            'isPhoneVerify' => $isPhoneVerify,
            'isPassportVerified' => $isPassportVerified,
            'phone' => $request->user()->phone,
        ]);
    }

    public function writeToUs(HttpRequest $request)
    {
        return Inertia::render('Settings/SettingsWriteToUs', [

        ]);
    }

    public function documentsInfo()
    {
        return Inertia::render('Settings/SettingsDocuments', [

        ]);
    }

}
