<?php

namespace App\Models\Control;

use CodeIgniter\Model;
use Config\Lookups;

/**
 * Control DB. Subscription tiers the platform sells to hotels — see
 * CreatePlansTable. `features` is stored as a JSON-encoded array of
 * strings; featuresList()/setFeaturesList() are the only places that
 * should encode/decode it, so no controller or view touches json_encode
 * directly.
 */
class PlanModel extends Model
{
    protected $table            = 'plans';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = true;
    protected $returnType       = 'object';
    protected $useTimestamps    = true;

    protected $allowedFields = [
        'name',
        'slug',
        'price',
        'billing_interval',
        'max_rooms',
        'description',
        'features',
        'is_active',
        'sort_order',
    ];

    public function __construct()
    {
        parent::__construct();

        $intervals = array_keys((new Lookups())->planBillingIntervals);

        $this->validationRules = [
            'name'             => 'required|max_length[100]',
            'slug'             => 'required|alpha_dash|max_length[100]|is_unique[plans.slug,id,{id}]',
            'price'            => 'required|decimal',
            'billing_interval' => 'required|in_list[' . implode(',', $intervals) . ']',
            'max_rooms'        => 'permit_empty|integer|greater_than[0]',
        ];
    }

    public function active(): array
    {
        return $this->where('is_active', 1)->orderBy('sort_order', 'asc')->findAll();
    }

    /** @return list<string> */
    public function featuresList(?object $plan): array
    {
        if ($plan === null || empty($plan->features)) {
            return [];
        }

        return json_decode($plan->features, true) ?? [];
    }

    /** @param list<string> $features */
    public function encodeFeatures(array $features): string
    {
        return json_encode(array_values(array_filter(array_map('trim', $features))));
    }
}
