<?php

namespace Licenzo\Model;

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

use Licenzo\Framework\Database\Model;
use Licenzo\Services\Integrations\ProviderAliasService;

/**
 * Product Model
 *
 * Represents products in Licenzo
 */
class Product extends Model
{
    /**
     * Table name
     */
    protected $table = 'licenzo_products';

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

    // Type constants
    const TYPE_SINGLE = 'single';
    const TYPE_VARIATION = 'variation';

    // Status constants
    const STATUS_ACTIVE = 'active';
    const STATUS_INACTIVE = 'inactive';
    const STATUS_DRAFT = 'draft';
    const STATUS_ARCHIVED = 'archived';

    // Provider constants
    const PROVIDER_WOOCOMMERCE = 'woocommerce';
    const PROVIDER_MANUAL = 'manual';
    const PROVIDER_STRIPE = 'stripe';
    const PROVIDER_SURECART = 'surecart';
    const PROVIDER_PAYPAL = 'paypal';
    const PROVIDER_EDD = 'edd';

    /**
     * Fillable attributes
     */
    protected $fillable = [
        'name',
        'description',
        'status',
        'product_link',
        'provider_id',
        'provider_product_name',
        'uuid',
        'slug',
        'provider',
        'type',
    ];

    /**
     * Attributes that should be cast
     */
    protected $casts = [
        'id'         => 'int',
        'provider_id' => 'string',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    /**
     * Keep provider aliases normalized at write boundary.
     */
    public function setProviderAttribute($value)
    {
        $this->attributes['provider'] = ProviderAliasService::normalize((string) $value, static::PROVIDER_MANUAL);
    }

    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;
    }

    /**
     * Relationship: Product has many ProductVariations
     */
    public function variations()
    {
        return $this->hasMany(ProductVariation::class, 'product_id');
    }
}
