<?php

namespace App\Models;

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

class RatingLocationComment extends Model
{
    use HasFactory;

    protected $table = 'rating_location_comments';

    protected $fillable = [
        'title_id',
        'category',
        'parent_id',
        'name',
        'email',
        'user_name',  // برای سازگاری با ساختار موجود
        'user_email', // برای سازگاری با ساختار موجود
        'user_phone',
        'comment',
        'rating',
        'status',
        'ip_address',
        'user_agent',
        'helpful_count',
        'not_helpful_count',
        'likes_count',    // موجود در ساختار فعلی
        'dislikes_count', // موجود در ساختار فعلی
        'replies_count',
        'is_verified',
        'is_featured',
        'is_pinned',      // موجود در ساختار فعلی
        'admin_reply',
        'admin_reply_date',
        'approved_at',
        'approved_by'
    ];

    protected $casts = [
        'admin_reply_date' => 'datetime',
        'approved_at' => 'datetime',
        'created_at' => 'datetime',
        'updated_at' => 'datetime',
        'is_verified' => 'boolean',
        'is_featured' => 'boolean',
        'helpful_count' => 'integer',
        'not_helpful_count' => 'integer',
        'replies_count' => 'integer',
        'rating' => 'integer'
    ];

    protected $dates = [
        'admin_reply_date',
        'approved_at',
        'created_at',
        'updated_at'
    ];

    // Relationships
    public function location()
    {
        return $this->belongsTo(Location::class, 'title_id', 'title_id');
    }

    public function parent()
    {
        return $this->belongsTo(RatingLocationComment::class, 'parent_id');
    }

    public function replies()
    {
        return $this->hasMany(RatingLocationComment::class, 'parent_id');
    }

    public function helpfulVotes()
    {
        return $this->hasMany(CommentHelpfulVote::class, 'comment_id');
    }

    // Scopes
    public function scopeApproved($query)
    {
        return $query->where('status', 'approved');
    }

    public function scopePending($query)
    {
        return $query->where('status', 'pending');
    }

    public function scopeRejected($query)
    {
        return $query->where('status', 'rejected');
    }

    public function scopeFeatured($query)
    {
        return $query->where('is_featured', true);
    }

    public function scopeVerified($query)
    {
        return $query->where('is_verified', true);
    }

    public function scopeForLocation($query, $titleId)
    {
        return $query->where('title_id', $titleId);
    }

    public function scopeParentComments($query)
    {
        return $query->whereNull('parent_id');
    }

    public function scopeReplies($query)
    {
        return $query->whereNotNull('parent_id');
    }

    public function scopeRecent($query, $days = 30)
    {
        return $query->where('created_at', '>=', Carbon::now()->subDays($days));
    }

    public function scopeHighRated($query, $minRating = 4)
    {
        return $query->where('rating', '>=', $minRating);
    }

    public function scopeLowRated($query, $maxRating = 2)
    {
        return $query->where('rating', '<=', $maxRating);
    }

    // Accessors
    public function getFormattedDateAttribute()
    {
        return $this->created_at ? $this->created_at->diffForHumans() : '';
    }

    public function getStarRatingAttribute()
    {
        $rating = $this->rating ?? 0;
        $stars = '';
        for ($i = 1; $i <= 5; $i++) {
            $stars .= $i <= $rating ? '★' : '☆';
        }
        return $stars;
    }

    public function getIsReplyAttribute()
    {
        return !is_null($this->parent_id);
    }

    public function getHasRepliesAttribute()
    {
        return $this->replies_count > 0;
    }

    // Mutators
    public function setEmailAttribute($value)
    {
        $this->attributes['email'] = strtolower($value);
    }

    // Helper methods
    public function markAsHelpful($userId = null)
    {
        $this->increment('helpful_count');

        if ($userId) {
            $this->helpfulVotes()->create([
                'user_id' => $userId,
                'vote_type' => 'helpful'
            ]);
        }
    }

    public function markAsNotHelpful($userId = null)
    {
        $this->increment('not_helpful_count');

        if ($userId) {
            $this->helpfulVotes()->create([
                'user_id' => $userId,
                'vote_type' => 'not_helpful'
            ]);
        }
    }

    public function approve($adminId = null)
    {
        $this->update([
            'status' => 'approved',
            'approved_at' => now(),
            'approved_by' => $adminId
        ]);
    }

    public function reject()
    {
        $this->update([
            'status' => 'rejected'
        ]);
    }

    public function addReply($data)
    {
        $reply = $this->replies()->create($data);
        $this->increment('replies_count');
        return $reply;
    }
}
