<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Announcements extends Model
{
    protected $fillable = [
        'parent_category',
        'title',
        'slug',
        'image',
        'content',
        'tags',
        'draft',
        'private',
        'author_id',
        'updated_at',
        'views',
        'likes',
    ];

    /**
     * Get the users who have viewed this announcement.
     */
    public function viewers()
    {
        return $this->belongsToMany(User::class, 'announcement_views', 'announcement_id', 'user_id')
                    ->withPivot('viewed_at', 'session_id');
    }

    /**
     * Get all views (including guest views) for this announcement.
     */
    public function allViews()
    {
        return $this->hasMany(\Illuminate\Database\Eloquent\Model::class, 'announcement_id', 'id')
                    ->from('announcement_views');
    }

    /**
     * Get the total unique view count for this announcement (users + guests).
     */
    public function getUniqueViewCountAttribute()
    {
        return \DB::table('announcement_views')
                  ->where('announcement_id', $this->id)
                  ->count();
    }

    /**
     * Check if a specific user has viewed this announcement.
     */
    public function hasBeenViewedByUser($userId)
    {
        return \DB::table('announcement_views')
                  ->where('announcement_id', $this->id)
                  ->where('user_id', $userId)
                  ->exists();
    }

    /**
     * Check if a specific session has viewed this announcement.
     */
    public function hasBeenViewedBySession($sessionId)
    {
        return \DB::table('announcement_views')
                  ->where('announcement_id', $this->id)
                  ->where('session_id', $sessionId)
                  ->exists();
    }

    /**
     * Get the users who have liked this announcement.
     */
    public function likers()
    {
        return $this->belongsToMany(User::class, 'announcement_likes', 'announcement_id', 'user_id')
                    ->withPivot('liked_at');
    }

    /**
     * Get all likes for this announcement.
     */
    public function allLikes()
    {
        return $this->hasMany(\Illuminate\Database\Eloquent\Model::class, 'announcement_id', 'id')
                    ->from('announcement_likes');
    }

    /**
     * Get the total unique like count for this announcement.
     */
    public function getUniqueLikeCountAttribute()
    {
        return \DB::table('announcement_likes')
                  ->where('announcement_id', $this->id)
                  ->count();
    }

    /**
     * Check if a specific user has liked this announcement.
     */
    public function hasBeenLikedByUser($userId)
    {
        return \DB::table('announcement_likes')
                  ->where('announcement_id', $this->id)
                  ->where('user_id', $userId)
                  ->exists();
    }
}
