<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Product extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'name', 'slug', 'description', 'short_description', 'type', 'version',
        'image', 'price', 'price_extended', 'regular_enabled', 'extended_enabled',
        'is_active', 'is_featured', 'platforms', 'license_rules',
        'update_channel', 'repo_path', 'max_activations', 'allow_domain_activation',
        'allow_ip_activation', 'require_device_fingerprint',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'is_featured' => 'boolean',
        'allow_domain_activation' => 'boolean',
        'allow_ip_activation' => 'boolean',
        'require_device_fingerprint' => 'boolean',
        'platforms' => 'array',
        'license_rules' => 'array',
        'price'            => 'decimal:2',
        'price_extended'   => 'decimal:2',
        'regular_enabled'  => 'boolean',
        'extended_enabled' => 'boolean',
    ];

    public function versions()
    {
        return $this->hasMany(ProductVersion::class);
    }

    public function latestVersion()
    {
        return $this->hasOne(ProductVersion::class)->ofMany([
            'released_at' => 'max',
        ], function ($q) {
            $q->where('is_active', true)->where('channel', 'stable');
        });
    }

    public function licenses()
    {
        return $this->hasMany(License::class);
    }

    public function orderItems()
    {
        return $this->hasMany(OrderItem::class);
    }

    /** Return the correct price for a given license type */
    public function priceFor(string $licenseType): float
    {
        if ($licenseType === 'unlimited' && $this->price_extended !== null) {
            return (float) $this->price_extended;
        }
        return (float) $this->price;
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }
}
