<?php

namespace App\Models;

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

class Product extends Model
{
    protected $fillable = [
        'category_id',
        'name',
        'slug',
        'description',
        'description_detail',
        'delivery_info',
        'certificates_info',
        'price',
        'sale_price',
        'sku',
        'image',
        'gallery',
        'stock_quantity',
        'in_stock',
        'is_active',
        'is_featured',
        'is_organic',
        'brand',
        'farm_name',
        'origin',
        'weight',
        'rating',
        'review_count',
        'order',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'sale_price' => 'decimal:2',
        'gallery' => 'array',
        'in_stock' => 'boolean',
        'is_active' => 'boolean',
        'is_featured' => 'boolean',
        'is_organic' => 'boolean',
        'stock_quantity' => 'integer',
        'rating' => 'integer',
        'review_count' => 'integer',
        'order' => 'integer',
    ];

    /**
     * Get the category that owns the product
     */
    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }

    /**
     * Get the final price (sale_price if available, otherwise price)
     */
    public function getFinalPriceAttribute()
    {
        return $this->sale_price ?? $this->price;
    }

    /**
     * Get discount percentage
     */
    public function getDiscountPercentageAttribute()
    {
        if ($this->sale_price && $this->price > $this->sale_price) {
            return round((($this->price - $this->sale_price) / $this->price) * 100);
        }
        return 0;
    }

    /**
     * Scope to get only active products
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    /**
     * Scope to get only in-stock products
     */
    public function scopeInStock($query)
    {
        return $query->where('in_stock', true)->where('stock_quantity', '>', 0);
    }

    /**
     * Scope to get featured products
     */
    public function scopeFeatured($query)
    {
        return $query->where('is_featured', true);
    }

    /**
     * Get the reviews for the product
     */
    public function reviews(): HasMany
    {
        return $this->hasMany(Review::class);
    }

    /**
     * Get approved reviews for the product
     */
    public function approvedReviews(): HasMany
    {
        return $this->hasMany(Review::class)->where('is_approved', true);
    }

    /**
     * Get average rating from approved reviews
     */
    public function getAverageRatingAttribute()
    {
        $reviews = $this->approvedReviews;
        if ($reviews->count() > 0) {
            $avg = $reviews->avg('rating');
            return $avg ? round($avg * 2) / 2 : 0; // 0.5'lik adımlarla (örn: 4.5)
        }
        return $this->rating ?? 0;
    }

    /**
     * Check if user has purchased this product
     */
    public function hasUserPurchased($userId)
    {
        if (!$userId) {
            return false;
        }
        
        return \App\Models\OrderItem::whereHas('order', function($query) use ($userId) {
            $query->where('user_id', $userId)
                  ->whereIn('status', ['confirmed', 'processing', 'shipped', 'delivered']);
        })->where('product_slug', $this->slug)->exists();
    }
}
