<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'slug',
        'image',
        'brand',
        'category',
        'description',
        'product_description',
        'api_code',
        'buyer_sku_code',
        'seller_name',
        'category_id',
        'price',
        'selling_price',
        'is_active',
        'seller_product_status',
        'unlimited_stock',
        'stock',
        'multi',
        'start_cut_off',
        'end_cut_off',
        'sort_order',
        'last_synced_at',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'selling_price' => 'decimal:2',
        'is_active' => 'boolean',
        'seller_product_status' => 'boolean',
        'unlimited_stock' => 'boolean',
        'multi' => 'boolean',
        'stock' => 'integer',
        'sort_order' => 'integer',
        'last_synced_at' => 'datetime',
    ];

    /**
     * Boot the model.
     */
    protected static function boot()
    {
        parent::boot();

        // Auto-generate slug from name
        static::creating(function ($product) {
            if (empty($product->slug)) {
                $product->slug = Str::slug($product->name);
            }
        });

        static::updating(function ($product) {
            if ($product->isDirty('name') && empty($product->slug)) {
                $product->slug = Str::slug($product->name);
            }
        });
    }

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

    /**
     * Scope: Only active products.
     */
    public function scopeActive($query)
    {
        return $query->where('is_active', true)
            ->where('seller_product_status', true);
    }

    /**
     * Scope: Products in stock.
     */
    public function scopeInStock($query)
    {
        return $query->where(function ($q) {
            $q->where('unlimited_stock', true)
              ->orWhere('stock', '>', 0);
        });
    }

    /**
     * Scope: By category.
     */
    public function scopeByCategory($query, $categoryId)
    {
        return $query->where('category_id', $categoryId);
    }

    /**
     * Scope: By brand.
     */
    public function scopeByBrand($query, string $brand)
    {
        return $query->where('brand', $brand);
    }

    /**
     * Scope: Search by name or SKU.
     */
    public function scopeSearch($query, string $search)
    {
        return $query->where(function ($q) use ($search) {
            $q->where('name', 'like', "%{$search}%")
              ->orWhere('buyer_sku_code', 'like', "%{$search}%")
              ->orWhere('api_code', 'like', "%{$search}%");
        });
    }

    /**
     * Scope: Order by sort order.
     */
    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order', 'asc')
            ->orderBy('price', 'asc')
            ->orderBy('name', 'asc');
    }

    /**
     * Get product by buyer SKU code.
     */
    public static function findByBuyerSku(string $buyerSkuCode): ?self
    {
        return static::where('buyer_sku_code', $buyerSkuCode)->first();
    }

    /**
     * Get product by API code.
     */
    public static function findByApiCode(string $apiCode): ?self
    {
        return static::where('api_code', $apiCode)->first();
    }

    /**
     * Check if product is available for purchase.
     */
    public function isAvailable(): bool
    {
        return $this->is_active 
            && $this->seller_product_status 
            && ($this->unlimited_stock || $this->stock > 0);
    }

    /**
     * Get profit margin.
     */
    public function getProfitAttribute(): float
    {
        return $this->selling_price - $this->price;
    }

    /**
     * Get profit percentage.
     */
    public function getProfitPercentageAttribute(): float
    {
        if ($this->price == 0) {
            return 0;
        }
        
        return (($this->selling_price - $this->price) / $this->price) * 100;
    }

    /**
     * Format price to Rupiah.
     */
    public function getFormattedPriceAttribute(): string
    {
        return 'Rp ' . number_format($this->price, 0, ',', '.');
    }

    /**
     * Format selling price to Rupiah.
     */
    public function getFormattedSellingPriceAttribute(): string
    {
        return 'Rp ' . number_format($this->selling_price, 0, ',', '.');
    }

    /**
     * Get stock status text.
     */
    public function getStockStatusAttribute(): string
    {
        if ($this->unlimited_stock) {
            return 'Unlimited';
        }
        
        if ($this->stock > 10) {
            return 'In Stock';
        }
        
        if ($this->stock > 0) {
            return 'Low Stock';
        }
        
        return 'Out of Stock';
    }

    /**
     * Get the route key for the model.
     */
    public function getRouteKeyName(): string
    {
        return 'slug';
    }

    /**
     * Update product from Digiflazz API data.
     */
    public function updateFromApi(array $data): bool
    {
        return $this->update([
            'name' => $data['product_name'] ?? $this->name,
            'price' => $data['price'] ?? $this->price,
            'seller_name' => $data['seller_name'] ?? $this->seller_name,
            'seller_product_status' => $data['seller_product_status'] ?? $this->seller_product_status,
            'unlimited_stock' => $data['unlimited_stock'] ?? $this->unlimited_stock,
            'stock' => $data['stock'] ?? $this->stock,
            'multi' => $data['multi'] ?? $this->multi,
            'start_cut_off' => $data['start_cut_off'] ?? $this->start_cut_off,
            'end_cut_off' => $data['end_cut_off'] ?? $this->end_cut_off,
            'product_description' => $data['desc'] ?? $this->product_description,
            'last_synced_at' => now(),
        ]);
    }

    /**
     * Create product from Digiflazz API data.
     */
    public static function createFromApi(array $data, int $categoryId): self
    {
        return static::create([
            'name' => $data['product_name'],
            'brand' => $data['brand'],
            'category' => $data['category'],
            'buyer_sku_code' => $data['buyer_sku_code'],
            'api_code' => $data['buyer_sku_code'], // sama dengan buyer_sku_code
            'price' => $data['price'],
            'selling_price' => $data['price'], // default sama dengan price, bisa diubah manual
            'seller_name' => $data['seller_name'],
            'seller_product_status' => $data['seller_product_status'],
            'unlimited_stock' => $data['unlimited_stock'],
            'stock' => $data['stock'],
            'multi' => $data['multi'],
            'start_cut_off' => $data['start_cut_off'],
            'end_cut_off' => $data['end_cut_off'],
            'product_description' => $data['desc'],
            'category_id' => $categoryId,
            'is_active' => true,
            'last_synced_at' => now(),
        ]);
    }

 public function reviews()
{
    return $this->hasMany(Review::class);
}

public function approvedReviews()
{
    return $this->hasMany(Review::class)->where('status', 'approved');
}

/**
 * Get average rating (from cache)
 */
public function getAverageRatingAttribute()
{
    return $this->attributes['average_rating'] ?? 0;
}

/**
 * Get total reviews (from cache)
 */
public function getTotalReviewsAttribute()
{
    return $this->attributes['total_reviews'] ?? 0;
}

/**
 * Calculate and update rating cache
 */
public function updateRatingCache()
{
    $stats = $this->approvedReviews()
        ->selectRaw('AVG(rating) as avg_rating, COUNT(*) as total')
        ->first();

    $this->update([
        'average_rating' => round($stats->avg_rating ?? 0, 2),
        'total_reviews' => $stats->total ?? 0,
    ]);

    return $this;
}

/**
 * Get rating breakdown
 */
public function getRatingBreakdown()
{
    return $this->approvedReviews()
        ->selectRaw('rating, COUNT(*) as count')
        ->groupBy('rating')
        ->orderBy('rating', 'desc')
        ->pluck('count', 'rating')
        ->toArray();
}

/**
 * Get rating percentage for specific star
 */
public function getRatingPercentage($rating)
{
    if ($this->total_reviews == 0) {
        return 0;
    }

    $breakdown = $this->getRatingBreakdown();
    $count = $breakdown[$rating] ?? 0;

    return round(($count / $this->total_reviews) * 100, 1);
}
}