<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class Product extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name',
        'slug',
        'description',
        'price',
        'category_id',
        'image',
        'stock',
        'status',
        'user_id',
    ];

    protected $casts = [
        'price' => 'float',
        'stock' => 'integer',
    ];

    /**
     * Relasi ke kategori
     */
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

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

    /**
     * Accessor URL gambar produk
     */
    public function getImageUrlAttribute()
    {
        if ($this->image && Storage::disk('public')->exists($this->image)) {
            return asset('storage/' . $this->image);
        }

        return asset('images/default-product.png');
    }

    /**
     * Accessor status label
     */
    public function getStatusLabelAttribute()
    {
        switch ($this->status) {
            case 'baru':
                return 'Baru';
            case 'bekas':
                return 'Bekas';
            default:
                return ucfirst($this->status);
        }
    }

    /**
     * Accessor deskripsi singkat
     */
    public function getShortDescriptionAttribute()
    {
        return Str::limit(strip_tags($this->description), 80);
    }

    /**
     * Accessor format harga
     */
    public function getFormattedPriceAttribute()
    {
        return 'Rp ' . number_format($this->price, 0, ',', '.');
    }

    /**
     * Scope produk aktif
     */
    public function scopeActive($query)
    {
        return $query->where('status', 'baru');
    }

    /**
     * Scope filter cepat (opsional)
     */
    public function scopeFilter($query, $filters)
    {
        if (!empty($filters['category_id'])) {
            $query->where('category_id', $filters['category_id']);
        }

        if (!empty($filters['search'])) {
            $query->where(function ($q) use ($filters) {
                $q->where('name', 'like', '%' . $filters['search'] . '%')
                  ->orWhere('description', 'like', '%' . $filters['search'] . '%');
            });
        }

        if (!empty($filters['status'])) {
            $query->where('status', $filters['status']);
        }
    }

    /**
     * Scope tampilkan termasuk soft delete (optional)
     */
    public function scopeWithDeleted($query)
    {
        return $query->withTrashed();
    }

    /**
     * Cek apakah produk dihapus (soft delete)
     */
    public function getIsDeletedAttribute()
    {
        return $this->trashed();
    }

    /**
     * Validasi data produk
     */
    public static function validateProduct($data)
    {
        return Validator::make($data, [
            'name' => 'required|string|max:255',
            'description' => 'nullable|string',
            'price' => 'required|numeric|min:0',
            'stock' => 'required|integer|min:0',
            'status' => 'required|in:baru,bekas',
            'image' => 'nullable|image|mimes:jpg,jpeg,png,gif|max:2048',
            'category_id' => 'required|exists:categories,id',
            'user_id' => 'required|exists:users,id',
        ]);
    }

    /**
     * Booted events
     */
    protected static function booted()
    {
        static::creating(function ($product) {
            // Slug unik
            if (empty($product->slug)) {
                $product->slug = static::generateUniqueSlug($product->name);
            }

            // Status default
            if (empty($product->status)) {
                $product->status = 'baru';
            }
        });

        static::updating(function ($product) {
            // Perbarui slug jika nama berubah
            if ($product->isDirty('name')) {
                $product->slug = static::generateUniqueSlug($product->name, $product->id);
            }
        });
    }

    /**
     * Generate slug unik
     */
    protected static function generateUniqueSlug($name, $ignoreId = null)
    {
        $slug = Str::slug($name);
        $originalSlug = $slug;
        $counter = 1;

        while (static::where('slug', $slug)
            ->when($ignoreId, function ($query) use ($ignoreId) {
                return $query->where('id', '!=', $ignoreId);
            })
            ->exists()
        ) {
            $slug = "{$originalSlug}-{$counter}";
            $counter++;
        }

        return $slug;
    }
}
