<?php

namespace App\Models;

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

class Review extends Model
{
    use HasFactory;

    protected $fillable = [
        'user_id',
        'order_id',
        'product_id',
        'rating',
        'comment',
        'reviewer_name',
        'reviewer_email',
        'is_verified_purchase',
        'helpful_count',
        'not_helpful_count',
        'status',
        'admin_note',
    ];

    protected $casts = [
        'rating' => 'integer',
        'is_verified_purchase' => 'boolean',
        'helpful_count' => 'integer',
        'not_helpful_count' => 'integer',
    ];

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

    public function order()
    {
        return $this->belongsTo(Order::class);
    }

    public function product()
    {
        return $this->belongsTo(Product::class);
    }

    public function images()
    {
        return $this->hasMany(ReviewImage::class)->orderBy('order');
    }

    public function votes()
    {
        return $this->hasMany(ReviewVote::class);
    }

    public function reply()
    {
        return $this->hasOne(ReviewReply::class);
    }

    /**
     * Scopes
     */
    public function scopeVerified($query)
    {
        return $query->where('is_verified_purchase', true);
    }

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

    public function scopeRecent($query)
    {
        return $query->latest();
    }

    public function scopeWithImages($query)
    {
        return $query->has('images');
    }

    public function scopeRating($query, $rating)
    {
        return $query->where('rating', $rating);
    }

    /**
     * Check if user has voted
     */
    public function hasVoted($userId)
    {
        return $this->votes()->where('user_id', $userId)->exists();
    }

    /**
     * Get user's vote
     */
    public function getUserVote($userId)
    {
        return $this->votes()->where('user_id', $userId)->first();
    }
}