<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Laracasts\Presenter\PresentableTrait;

class Post extends Model
{
    use PresentableTrait;

    protected $table = 'posts';

    protected $presenter = 'App\\Presenters\\PostPresenter';

    /**
     * Static cache for post counts to prevent repeated queries
     */
    protected static $postCountCache = [];

    public function user()
    {
        return $this->belongsTo('App\\Models\\User', 'user_id');
    }

    public function page()
    {
        return $this->belongsTo('App\\Models\\Page', 'page_id');
    }

    public function toUser()
    {
        return $this->belongsTo('App\\Models\\User', 'to_user_id');
    }

    public function sharedUser()
    {
        return $this->belongsTo('App\\Models\\User', 'shared_from');
    }

    public function comments()
    {
        $comments = $this->hasMany('App\\Models\\Comment', 'type_id')->with('user')->where('type', '=', 'post')->orderBy('id', 'desc');

        $bannedUsers = app('App\\Repositories\\UserRepository')->listBannedIds();
        $comments = $comments->whereNotIn('user_id', $bannedUsers);

        return $comments;
    }

    public function likes()
    {
        return $this->hasMany('App\\Models\\Like', 'type_id')->where('type', '=', 'post');
    }

    /**
     * CRITICAL FIX: Optimize countLikes to use database count instead of loading all records
     */
    public function countLikes()
    {
        $cacheKey = "count_likes_post_{$this->id}";
        
        if (!isset(static::$postCountCache[$cacheKey])) {
            // Use database count instead of count($this->likes)
            $postLikes = $this->likes()->count();
            $postCommentsLinkes = app('App\\Repositories\\LikeRepository')->getCommentsLikeByPost($this->id);
            
            static::$postCountCache[$cacheKey] = $postLikes + $postCommentsLinkes;
        }
        
        return static::$postCountCache[$cacheKey];
    }

    /**
     * OPTIMIZED: Cache hasLiked result within request
     */
    public function hasLiked()
    {
        if (! \Auth::check()) {
            return false;
        }

        $cacheKey = "has_liked_post_{$this->id}_user_" . \Auth::user()->id;
        
        if (!isset(static::$postCountCache[$cacheKey])) {
            static::$postCountCache[$cacheKey] = app('App\\Repositories\\LikeRepository')->hasLiked('post', $this->id, \Auth::user()->id);
        }
        
        return static::$postCountCache[$cacheKey];
    }

    /**
     * OPTIMIZED: Get comments with better query optimization
     */
    public function getComments()
    {
        $cacheKey = "post_comments_{$this->id}_user_" . (\Auth::check() ? \Auth::user()->id : 0);
        
        if (!isset(static::$postCountCache[$cacheKey])) {
            $comments = $this->comments()->with('user')->where('type', '=', 'post');

            if (\Auth::check()) {
                $blockedUsers = app('App\\Repositories\\blockedUserRepository')->listIds(\Auth::user()->id);
                $comments = $comments->whereNotIn('user_id', $blockedUsers);
            }

            static::$postCountCache[$cacheKey] = $comments->orderBy('id', 'desc')->paginate(config('post-per-page'));
        }
        
        return static::$postCountCache[$cacheKey];
    }

    /**
     * CRITICAL FIX: Use database count instead of loading all comments
     */
    public function countComments()
    {
        $cacheKey = "count_comments_post_{$this->id}";
        
        if (!isset(static::$postCountCache[$cacheKey])) {
            // Use database count instead of $this->comments->count()
            static::$postCountCache[$cacheKey] = $this->comments()->count();
        }
        
        return static::$postCountCache[$cacheKey];
    }

    public function community()
    {
        return $this->belongsTo('App\\Models\\Community', 'community_id');
    }
	
	public function event()
    {
        return $this->hasOne('App\\Models\\PostEvents', 'post_id', 'id');
    }
    
    // Keep the old method as a backup if needed
    public function getEventData()
    {
       return app('App\\Repositories\\PostEventsRepository')->getByPostId($this->id);
    }

    public function postedIncommunity()
    {
        return $this->belongsTo('App\\Models\\Community', 'posted_in_community');
    }

    public function communityCategory()
    {
        return $this->belongsTo('App\\Models\\CommunityCategory', 'type_id');
    }

    /**
     * OPTIMIZED: Cache ownership check within request
     */
    public function isOwner()
    {
        if (! \Auth::check()) {
            return false;
        }
        
        $cacheKey = "is_owner_post_{$this->id}_user_" . \Auth::user()->id;
        
        if (!isset(static::$postCountCache[$cacheKey])) {
            static::$postCountCache[$cacheKey] = (\Auth::user()->id == $this->user_id);
        }
        
        return static::$postCountCache[$cacheKey];
    }

    /**
     * OPTIMIZED: Cache hasPosted result
     */
    public function hasPosted()
    {
        if (! \Auth::check()) {
            return false;
        }
        
        $cacheKey = "has_posted_{$this->id}_user_" . \Auth::user()->id;
        
        if (!isset(static::$postCountCache[$cacheKey])) {
            static::$postCountCache[$cacheKey] = app('App\\Repositories\\ModeratorRepository')->hasPosted($this->id, \Auth::user()->id);
        }
        
        return static::$postCountCache[$cacheKey];
    }

    /**
     * Clear post-specific cache
     */
    public function clearPostCache()
    {
        $keysToRemove = [];
        foreach (static::$postCountCache as $key => $value) {
            if (strpos($key, "_post_{$this->id}") !== false) {
                $keysToRemove[] = $key;
            }
        }
        
        foreach ($keysToRemove as $key) {
            unset(static::$postCountCache[$key]);
        }
    }
}
