<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class RateMyPay extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'user_id',
        'job_experience_id',
        'content',
        'is_anonymous',
        'payslip_path',
        'likes_count',
        'comments_count',
        'ratings_count',
        'average_rating',
    ];

    protected $casts = [
        'is_anonymous' => 'boolean',
        'average_rating' => 'decimal:2',
        'likes_count' => 'integer',
        'comments_count' => 'integer',
        'ratings_count' => 'integer',
    ];

    protected $appends = [
        'is_liked_by_user',
        'payslip_url',
        'base_salary',       
        'bonus',             
        'equity',            
        'benefits',          
        'currency',         
        'formatted_salary',
        // 'all_comments',
    ];

    // Relationships
    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    public function jobExperience(): BelongsTo
    {
        return $this->belongsTo(JobExperience::class);
    }

    public function communities(): BelongsToMany
    {
        return $this->belongsToMany(Community::class, 'community_rate_my_pay')
            ->withTimestamps();
    }

    public function ratings(): HasMany
    {
        return $this->hasMany(Rating::class, 'rate_my_pay_id');
    }

    public function comments(): HasMany
    {
        return $this->hasMany(PostComment::class)->whereNull('parent_id');
    }

    public function allComments(): HasMany
    {
        return $this->hasMany(PostComment::class);
    }

    public function likes(): HasMany
    {
        return $this->hasMany(PostLike::class, 'likeable_id')
            ->where('likeable_type', self::class);
    }

    // Accessors
   public function getBaseSalaryAttribute(): float
    {
        return $this->jobExperience->annual_base_salary ?? 0;
    }

    public function getBonusAttribute(): float
    {
        return $this->jobExperience->bonus_commission ?? 0;
    }

    public function getEquityAttribute(): float
    {
        return $this->jobExperience->equity ?? 0;
    }

    public function getBenefitsAttribute(): ?string
    {
        return $this->jobExperience->benefits;
    }

    public function getCurrencyAttribute(): string
    {
        return $this->jobExperience->currency ?? 'NGN';
    }

    public function getTotalCompensationAttribute(): float
    {
        return $this->jobExperience->total_compensation ?? 0;
    }

    public function getFormattedSalaryAttribute(): string
    {
        return  $this->currency . ' ' . number_format($this->base_salary);
    }

    public function getFormattedTotalCompensationAttribute(): string
    {
        return $this->currency . ' ' . number_format($this->total_compensation);
    }

    public function getBenefitsArrayAttribute(): array
    {
        return $this->benefits ? explode(', ', $this->benefits) : [];
    }

    public function getPayslipUrlAttribute(): ?string
    {
        return $this->payslip_path ? asset('storage/' . $this->payslip_path) : null;
    }

    public function getAuthorNameAttribute(): string
    {
        return $this->is_anonymous ? 'Anonymous' : $this->user->name;
    }

    // public function getAllCommentsAttribute()
    // {
    //     // Check if the relationship is already loaded
    //     if ($this->relationLoaded('allComments')) {
    //         return $this->allComments;
    //     }

    //     return $this->allComments()->get(); 
    // }

    // Methods
    public function updateRatingStats(): void
    {
        $this->update([
            'ratings_count' => $this->ratings()->count(),
            'average_rating' => $this->ratings()->avg('rating') ?: 0,
        ]);
    }

    public function isLikedBy(User $user): bool
    {
        return $this->likes()->where('user_id', $user->id)->exists();
    }

    public function canUserRate(User $user): bool
    {
        return !$this->ratings()->where('user_id', $user->id)->exists();
    }

    public function getUserRating(User $user): ?Rating
    {
        return $this->ratings()->where('user_id', $user->id)->first();
    }

    public function getIsLikedByUserAttribute(): bool
    {
        return auth()->check() && $this->isLikedBy(auth()->user());
    }

    // Community Methods
    public function addToCommunity(Community $community): void
    {
        $this->communities()->attach($community->id);
    }

    public function addToCommunities(array $communityIds): void
    {
        $this->communities()->attach($communityIds);
    }

    public function removeFromCommunity(Community $community): void
    {
        $this->communities()->detach($community->id);
    }

    public function isInCommunity(Community $community): bool
    {
        return $this->communities()->where('community_id', $community->id)->exists();
    }

    public function getCommunityNamesAttribute(): string
    {
        return $this->communities->pluck('name')->join(', ');
    }

    // Scopes
    public function scopeInCommunity($query, $communityId)
    {
        return $query->whereHas('communities', function($q) use ($communityId) {
            $q->where('communities.id', $communityId);
        });
    }

    public function scopeInCommunities($query, array $communityIds)
    {
        return $query->whereHas('communities', function($q) use ($communityIds) {
            $q->whereIn('communities.id', $communityIds);
        });
    }

    public function scopeGlobal($query)
    {
        return $query->whereDoesntHave('communities');
    }
}