<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'code',
        'description',
        'is_active',
        'track_clicks',
    ];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'track_clicks' => 'boolean',
        ];
    }

    /**
     * Scope to filter products with click tracking enabled.
     */
    public function scopeTrackClicks($query)
    {
        return $query->where('track_clicks', true);
    }

    /**
     * Get all order items for this product.
     */
    public function orderItems(): HasMany
    {
        return $this->hasMany(OrderItem::class);
    }

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

    /**
     * Get materials available for this product (optional filtering).
     */
    public function materials(): BelongsToMany
    {
        return $this->belongsToMany(Material::class, 'product_material');
    }

    /**
     * Check if this product has specific materials assigned.
     */
    public function hasMaterials(): bool
    {
        return $this->materials()->count() > 0;
    }

    /**
     * Generate a unique code from name if not provided.
     */
    public static function generateCode(string $name): string
    {
        $words = explode(' ', strtoupper($name));
        $code = '';
        
        foreach ($words as $word) {
            if (strlen($word) > 0) {
                $code .= substr($word, 0, 1);
            }
        }
        
        // Make sure code is unique
        $baseCode = $code;
        $counter = 1;
        
        while (self::where('code', $code)->exists()) {
            $code = $baseCode . $counter;
            $counter++;
        }
        
        return $code;
    }
}
