<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Review extends Model
{
    protected $fillable = [
        'booking_id',
        'reviewer_id',
        'reviewee_id',
        'rating',
        'comment',
        'review_type',
    ];

    protected function casts(): array
    {
        return [
            'rating' => 'integer',
        ];
    }

    // Relationships

    /**
     * Get the booking for this review
     */
    public function booking(): BelongsTo
    {
        return $this->belongsTo(Booking::class);
    }

    /**
     * Get the user who wrote the review
     */
    public function reviewer(): BelongsTo
    {
        return $this->belongsTo(User::class, 'reviewer_id');
    }

    /**
     * Get the user who is being reviewed
     */
    public function reviewee(): BelongsTo
    {
        return $this->belongsTo(User::class, 'reviewee_id');
    }

    // Scopes

    /**
     * Scope for driver reviews
     */
    public function scopeDriverReviews($query)
    {
        return $query->where('review_type', 'driver_review');
    }

    /**
     * Scope for passenger reviews
     */
    public function scopePassengerReviews($query)
    {
        return $query->where('review_type', 'passenger_review');
    }

    /**
     * Scope for high ratings (4-5 stars)
     */
    public function scopeHighRating($query)
    {
        return $query->where('rating', '>=', 4);
    }

    // Helper Methods

    /**
     * Get star rating display
     */
    public function getStarsAttribute(): string
    {
        return str_repeat('⭐', $this->rating);
    }

    /**
     * Get rating color class
     */
    public function getRatingColorAttribute(): string
    {
        return match(true) {
            $this->rating >= 4 => 'text-green-600',
            $this->rating >= 3 => 'text-yellow-600',
            default => 'text-red-600'
        };
    }

    /**
     * Check if review is positive (4-5 stars)
     */
    public function isPositive(): bool
    {
        return $this->rating >= 4;
    }
}
