<?php

namespace Licenzo\Model;

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

use Licenzo\Framework\Database\Model;
use Licenzo\Casts\MoneyCast;

/**
 * Product Variation Model
 *
 * Represents product variations (pricing plans) in Licenzo
 */
class ProductVariation extends Model
{
    /**
     * Table name
     */
    protected $table = 'licenzo_product_variations';

    /**
     * Primary key
     */
    protected $primaryKey = 'id';

    // Price cycle constants
    const PRICE_CYCLE_ONETIME = 'onetime';
    const PRICE_CYCLE_MONTHLY = 'monthly';
    const PRICE_CYCLE_YEARLY = 'yearly';
    const PRICE_CYCLE_WEEKLY = 'weekly';
    const PRICE_CYCLE_LIFETIME = 'lifetime';

    // Support unit constants
    const SUPPORT_UNIT_DAY = 'day';
    const SUPPORT_UNIT_MONTH = 'month';
    const SUPPORT_UNIT_YEAR = 'year';

    /**
     * Fillable attributes
     */
    protected $fillable = [
        'uuid',
        'product_id',
        'provider_id',
        'name',
        'billing_cycle',
        'currency',
        'regular_price',
        'sale_price',
        'trial_days',
        'max_activations',
        'support_for_unit',
        'support_for',
    ];

    /**
     * Attributes that should be cast
     */
    protected $casts = [
        'id' => 'int',
        'provider_id' => 'string',
        'currency' => 'string',
        'regular_price' => MoneyCast::class,
        'sale_price' => MoneyCast::class,
        'trial_days' => 'int',
        'max_activations' => 'int',
        'support_for_unit' => 'string',
        'support_for' => 'int',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    public function getProviderIdAttribute($value)
    {
        return ($value === null || $value === '') ? null : (string) $value;
    }

    public function setProviderIdAttribute($value)
    {
        $this->attributes['provider_id'] = ($value === null || $value === '') ? null : (string) $value;
    }

    public function getBillingCycleAttribute($value)
    {
        return ($value === null || $value === '') ? static::PRICE_CYCLE_MONTHLY : (string) $value;
    }

    public function setBillingCycleAttribute($value)
    {
        $normalized = strtolower(trim((string) ($value ?? '')));
        $allowed = [
            static::PRICE_CYCLE_ONETIME,
            static::PRICE_CYCLE_WEEKLY,
            static::PRICE_CYCLE_MONTHLY,
            static::PRICE_CYCLE_YEARLY,
            static::PRICE_CYCLE_LIFETIME,
        ];

        $this->attributes['billing_cycle'] = in_array($normalized, $allowed, true)
            ? $normalized
            : static::PRICE_CYCLE_MONTHLY;
    }

    /**
     * Relationship: ProductVariation belongs to a Product
     */
    public function product()
    {
        return $this->belongsTo(Product::class, 'product_id', 'id');
    }
}
