<?php
// app/Models/Comment.php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Comment extends Model
{
    use HasFactory, SoftDeletes;

    protected $table = 'comments';

    protected $fillable = [
        'commentable',
        'user_id',
        'guest_name',
        'guest_email',
        'content',
        'likes',
        'dislikes',
        'status',
        'parent_id',
        'ip_address',
        'user_agent',
        'commentable_id',
        'commentable_type',
        'status'
    ];

    protected $casts = [
        'likes' => 'integer',
        'dislikes' => 'integer',
        'status' => 'string',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'deleted_at' => 'datetime'
    ];

    /**
     * Get the parent commentable model (content, page, etc.)
     */
    public function commentable()
    {
        return $this->morphTo();
    }

    /**
     * Get the user who wrote the comment
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the parent comment (for replies)
     */
    public function parent()
    {
        return $this->belongsTo(Comment::class, 'parent_id');
    }

    /**
     * Get the replies to this comment
     */
    public function replies()
    {
        return $this->hasMany(Comment::class, 'parent_id');
    }

    /**
     * Get all approved replies
     */
    public function approvedReplies()
    {
        return $this->replies()->where('status', 'approved');
    }

    /**
     * Check if comment is approved
     */
    public function isApproved()
    {
        return $this->status === 'approved';
    }

    /**
     * Check if comment is pending
     */
    public function isPending()
    {
        return $this->status === 'pending';
    }

    /**
     * Check if comment is spam
     */
    public function isSpam()
    {
        return $this->status === 'spam';
    }

    /**
     * Get comment author name
     */
    public function getAuthorNameAttribute()
    {
        if ($this->user) {
            return $this->user->name;
        }
        return $this->guest_name ?? 'Anonymous';
    }

    /**
     * Get comment author email
     */
    public function getAuthorEmailAttribute()
    {
        if ($this->user) {
            return $this->user->email;
        }
        return $this->guest_email;
    }

    /**
     * Get comment author avatar
     */
    public function getAuthorAvatarAttribute()
    {
        if ($this->user && $this->user->avatar) {
            return $this->user->avatar;
        }
        return 'https://www.gravatar.com/avatar/' . md5(strtolower(trim($this->author_email))) . '?d=mp';
    }

    /**
     * Get comment time in human readable format
     */
    public function getTimeAgoAttribute()
    {
        return $this->created_at->diffForHumans();
    }

    /**
     * Scope a query to only include approved comments
     */
    public function scopeApproved($query)
    {
        return $query->where('status', 'approved');
    }

    /**
     * Scope a query to only include pending comments
     */
    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    /**
     * Scope a query to only include spam comments
     */
    public function scopeSpam($query)
    {
        return $query->where('status', 'spam');
    }

    /**
     * Scope a query to only include root comments (not replies)
     */
    public function scopeRoot($query)
    {
        return $query->whereNull('parent_id');
    }

    /**
     * Scope a query to only include replies
     */
    public function scopeReplies($query)
    {
        return $query->whereNotNull('parent_id');
    }

    /**
     * Scope a query to filter by content type
     */
    public function scopeForContent($query, $contentId)
    {
        return $query->where('commentable_type', Content::class)
                     ->where('commentable_id', $contentId);
    }

    /**
     * Increment likes count
     */
    public function incrementLikes()
    {
        $this->increment('likes');
    }

    /**
     * Increment dislikes count
     */
    public function incrementDislikes()
    {
        $this->increment('dislikes');
    }

    /**
     * Get like/dislike ratio
     */
    public function getLikeRatioAttribute()
    {
        $total = $this->likes + $this->dislikes;
        if ($total === 0) {
            return 0;
        }
        return round(($this->likes / $total) * 100, 2);
    }

    /**
     * Check if comment has replies
     */
    public function getHasRepliesAttribute()
    {
        return $this->replies()->count() > 0;
    }

    /**
     * Get nested replies with depth limit
     */
    public function getNestedReplies($depth = 3, $currentDepth = 0)
    {
        if ($currentDepth >= $depth) {
            return collect();
        }

        $replies = $this->approvedReplies()->with(['user', 'replies'])->get();

        foreach ($replies as $reply) {
            $reply->setRelation('replies', $reply->getNestedReplies($depth, $currentDepth + 1));
        }

        return $replies;
    }

    /**
     * Mark as spam
     */
    public function markAsSpam()
    {
        $this->update(['status' => 'spam']);
    }

    /**
     * Mark as approved
     */
    public function markAsApproved()
    {
        $this->update(['status' => 'approved']);
    }

    /**
     * Mark as pending
     */
    public function markAsPending()
    {
        $this->update(['status' => 'pending']);
    }

    /**
     * Delete all replies
     */
    public function deleteReplies()
    {
        foreach ($this->replies as $reply) {
            $reply->delete();
        }
    }
}
