<?php

namespace Licenzo\Model;

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

use Licenzo\Framework\Database\Model;

class SubscriptionMeta extends Model
{
    protected $table = 'licenzo_meta';

    protected $fillable = [
        'entity_type', 'entity_id', 'meta_key', 'meta_value'
    ];

    protected $casts = [
        'id' => 'int',
        'entity_id' => 'int',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    // Auto-set entity_type on create
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->entity_type)) {
                $model->entity_type = 'subscription';
            }
        });
    }

    // Relationships
    public function subscription()
    {
        return $this->belongsTo(Subscription::class, 'entity_id');
    }

    // Scopes
    public function scopeForSubscription($query, $subscriptionId)
    {
        return $query->where('entity_type', 'subscription')
                     ->where('entity_id', $subscriptionId);
    }

    // Instance Helpers
    public function getValue()
    {
        $decoded = json_decode($this->meta_value, true);
        return json_last_error() === JSON_ERROR_NONE ? $decoded : $this->meta_value;
    }

    public function setValue($value)
    {
        $this->meta_value = is_array($value) || is_object($value)
            ? json_encode($value)
            : $value;
    }

    // Static Helpers
    public static function getMeta($subscriptionId, $key, $default = null)
    {
        $meta = static::where('entity_type', 'subscription')
                    ->where('entity_id', $subscriptionId)
                    ->where('meta_key', $key)
                    ->first();

        return $meta ? $meta->getValue() : $default;
    }

    public static function setMeta($subscriptionId, $key, $value)
    {
        $meta = static::where('entity_type', 'subscription')
                    ->where('entity_id', $subscriptionId)
                    ->where('meta_key', $key)
                    ->first();

        if ($meta) {
            $meta->setValue($value);
            $meta->save();
        } else {
            $value = is_array($value) || is_object($value) ? json_encode($value) : $value;
            static::create([
                'entity_type' => 'subscription',
                'entity_id' => $subscriptionId,
                'meta_key' => $key, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
                'meta_value' => $value, // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
            ]);
        }

        return true;
    }

    public static function deleteMeta($subscriptionId, $key)
    {
        return static::where('entity_type', 'subscription')
                   ->where('entity_id', $subscriptionId)
                   ->where('meta_key', $key)
                   ->delete();
    }

    public static function getAllMeta($subscriptionId)
    {
        $metas = static::where('entity_type', 'subscription')
                     ->where('entity_id', $subscriptionId)
                     ->get();

        $result = [];
        foreach ($metas as $meta) {
            $result[$meta->meta_key] = $meta->getValue();
        }

        return $result;
    }
}
