<?php

namespace App\Presenters;

use Laracasts\Presenter\Presenter;

class PagePresenter extends Presenter
{
    public function url($segment = null)
    {
        $segment = (empty($segment)) ? '' : '/'.$segment;

        return \URL::route('page', ['slug' => $this->entity->slug]).$segment;
    }

    public function businessUrl($segment = null)
    {
        $segment = (empty($segment)) ? '' : '/'.$segment;

        return \URL::route('store', ['slug' => $this->entity->slug]).$segment;
    }

    public function readDesign()
    {
        $cacheKey = 'user_design_page_' . $this->entity->user_id . '_' . $this->entity->id;
        
        return \Cache::remember($cacheKey, now()->addMonth(), function () {
            return $this->entity->user->present()->readDesign('page-'.$this->entity->id);
        });
    }

    public function getAvatar($size = 100)
    {
        if (empty($this->entity->logo)) {
            return \Theme::asset()->img('theme/images/page/logo.jpg');
        }

        return \Image::url($this->entity->logo, $size);
    }

    public function getAvatarTheme2($size = 100)
    {
        if (empty($this->entity->theme2_logo)) {
            //return \Theme::asset()->img('theme/images/page/theme2-logo.png');
			if($this->entity->chamber_store==1){
				return \Theme::asset()->img('theme/images/chamber/black-logo.png');
			}
			return \Theme::asset()->img('theme/images/store/store-logo.png');
        }

        return \Image::url($this->entity->theme2_logo, $size);
    }

    public function joinedOn()
    {
        return str_replace(' ', 'T', $this->entity->created_at).'+05:30';
    }

    public function isAdmin($ignoreGlobalAdmin = false, $userid = null)
    {
        if (! \Auth::check() and ! $userid) {
            return false;
        }

        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        if (! $userid) {
            return false;
        }

        // if (!\Auth::check()) return false;

        if (\Auth::check()) {
            if (! $ignoreGlobalAdmin and \Auth::user()->isAdmin()) {
                return true;
            }
        }

        if ($this->entity->isOwner($userid)) {
            return true;
        }

        // $userid = \Auth::user()->id;
        $adminRepository = app('App\Repositories\PageAdminRepository');
        if ($adminRepository->isAdmin($this->entity->id, $userid)) {
            return true;
        }

        return false;
    }

    public function isModerator($userid = null)
    {
        if (! \Auth::check() and ! $userid) {
            return false;
        }

        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        if (! $userid) {
            return false;
        }

        // if (!\Auth::check()) return false;
        // $userid = \Auth::user()->id;

        $adminRepository = app('App\Repositories\PageAdminRepository');
        if ($adminRepository->isModerator($this->entity->id, $userid)) {
            return true;
        }

        return false;
    }

    public function isEditor($userid = null)
    {
        if (! \Auth::check() and ! $userid) {
            return false;
        }

        $userid = (empty($userid)) ? \Auth::user()->id : $userid;
        if (! $userid) {
            return false;
        }

        // if (!\Auth::check()) return false;
        // $userid = \Auth::user()->id;

        $adminRepository = app('App\Repositories\PageAdminRepository');
        if ($adminRepository->isEditor($this->entity->id, $userid)) {
            return true;
        }

        return false;
    }

    public function coverImage()
    {
        if (! empty($this->entity->cover)) {
            return \Image::url($this->entity->cover);
        }
    }

    public function field($id = null)
    {
        $details = (! empty($this->entity->info)) ? perfectUnserialize($this->entity->info) : [];

        if (empty($id)) {
            return $details;
        }

        if (isset($details[$id])) {
            return $details[$id];
        }

        return 'Nill';
    }

    public function fields()
    {
        return app('App\\Repositories\\CustomFieldRepository')->listAll('page');
    }

    public function likeStatus($userid)
    {
        $userid = (int) $userid;
        if ($userid <= 0) {
            try {
                $userid = \Auth::check() ? (int) \Auth::id() : 0;
            } catch (\Throwable $e) {
                $userid = 0;
            }
        }
        $pageId = (int) ($this->entity->id ?? 0);

        // Fast path: use request-scoped feed map when available (avoids per-item exists() queries).
        try {
            if ($userid > 0 && $pageId > 0) {
                $mapKey = 'feed_page_has_liked_map:u' . $userid;
                $map = request()->attributes->get($mapKey);
                if (is_array($map) && array_key_exists($pageId, $map)) {
                    if (! empty($map[$pageId])) {
                        return 'liked';
                    }
                    // If explicitly false in the map, skip DB and proceed to invited check.
                }
            }
        } catch (\Throwable $e) {
            // Ignore and fall back to repository
        }

        $liked = app('App\\Repositories\\LikeRepository')->hasLiked('page', $pageId, $userid);

        if ($liked) {
            return 'liked';
        }

        $invited = app('App\\Repositories\\InvitedMemberRepository')->isInvited('page', $pageId, $userid);
        if ($invited) {
            return 'invited';
        }

        return false;
    }

    public function productRatingsCount($productId)
    {
        $productRatingsCount = app('App\\Repositories\\BusinessRatingsRepository')->getratingsTotalByProductId($productId);

        $reviewsCount = $this->productReviewsCount($productId);

        if ($productRatingsCount > 0) {
            $productRatingsCount = number_format($productRatingsCount / $reviewsCount, 1);
        }

        return $productRatingsCount;
    }

    public function productReviewsCount($productId)
    {
        return $productReviews = app('App\\Repositories\\BusinessRatingsRepository')->getratingsCountByProductId($productId);
    }

    public function businessRatingsCount($businessId)
    {
        $businessRatingsCount = app('App\\Repositories\\BusinessRatingsRepository')->getratingsTotalByBusinessId($businessId);

        $reviewsCount = $this->businessReviewsCount($businessId);

        if ($businessRatingsCount > 0) {
            $businessRatingsCount = number_format($businessRatingsCount / $reviewsCount, 1);
        }

        return $businessRatingsCount;
    }

    public function businessReviewsCount($businessId)
    {
        return $businessReviews = app('App\\Repositories\\BusinessRatingsRepository')->getratingsCountByBusinessId($businessId);
    }

    public function businessAdmins($businessId)
    {
        return $businessAdmins = app('App\\Repositories\\PageAdminRepository')->getList($businessId);
    }

    public function getFeviconAvatar()
    {
        if (empty($this->entity->fevicon_image)) {
            return $this->getAvatar();
        }

        return \Image::url($this->entity->fevicon_image);
    }

    public function getCategories()
    {
        return $businessAdmins = app('App\\Repositories\\BusinessProductsCategoriesRepository')->getByBusinessId($this->entity->id);
    }

    public function getProductByCategory($category_id)
    {
        return $products = app('App\\Repositories\\BusinessProductsRepository')->getByBusinessCategoryId($this->entity->id, $category_id);
    }

    public function getThemeSetting()
    {
        return $products = app('App\\Repositories\\BusinessDesignSettingsRepository')->getByBusinessId($this->entity->id);
    }

    public function getAllProducts()
    {
        return $businessAdmins = app('App\\Repositories\\BusinessProductsRepository')->getByBusinessIdQuanitity($this->entity->id);
    }

    public function getAllProductsLimited($limit=8)
    {
        return $businessAdmins = app('App\\Repositories\\BusinessProductsRepository')->getAllProductsLimited($this->entity->id,$limit);
    }
	
	public function storeCartCOunt()
	{
        $user = \Auth::user();
        if (! $user) {
            return 0;
        }

        $businessId = (int) $this->entity->id;
        $userId = (int) $user->id;
        $communityId = (int) ($this->entity->community_id ?? 0);
        $cacheKey = 'store_cart_cnt_b' . $businessId . '_u' . $userId . '_c' . $communityId;

        return (int) \Cache::remember($cacheKey, now()->addSeconds(10), function () use ($businessId, $userId, $communityId) {
            return app('App\\Repositories\\BusinessProductsCartRepository')->getCartCountByBusiness($businessId, $userId, $communityId);
        });
	}
	
	public function isKycCompleted()
	{
		if($this->entity->kyc_completed==1){
			return true;
		}
		return false;
	}
	
	public function lifeTimeSalesRevenue()
	{
		$page =$this->entity;
		return app('App\\Repositories\\BusinessProductsOrdersRepository')->getMyStoreRevenue($page->user_id,$page->id);
	}
}