<?php

namespace App\Domain\Users\Service;


use Illuminate\Database\Eloquent\Builder;

class ProfileDataService
{
    public static function get($user)
    {

        $gues = auth()->user();
        if($gues){
            $gues = auth()->user()->id;
        }else{
            $gues = null;
        }

        $user->loadCount(['subscriber_reverse as is_sub' => function (Builder $query) use($gues)  {
            $query->where('user_id', $gues);
        },'subscribers as is_reader' => function (Builder $query) use($gues) {
            $query->where('subscriber_id', $gues);
        }])->withCasts(['is_sub' => 'boolean', 'is_reader' => 'boolean']);

        $is_leader = false;

        if($user->is_sub && auth()->user()){
            $leader = auth()->user()->subscribers()->where('subscriber_id', $user->id)->first();
            if($leader){
                $is_leader = (boolean)$leader->pivot->leader;
            }
        }

        $count_feeds = $user->feeds()->count();
        $count_readable = $user->subscribers()->count();
        $count_subscribers = $user->subscriber_reverse()->count();

        $is_auth_user = $user->id === $gues;
        if($is_auth_user){
            $close_account = false;
        }else{
            $close_account = $user->private == true && ($user->is_sub == 0 || $user->is_reader == 0);
        }

        $object = new \stdClass();
        $object->user = $user;
        $object->count_feeds = $count_feeds;
        $object->count_readable = $count_readable;
        $object->count_subscribers = $count_subscribers;
        $object->close_account = $close_account;
        $object->is_leader = $is_leader;

        return $object;
    }
}
