<?php
declare(strict_types=1);

namespace App\Modules\Forms\Models;

use App\Core\Model;
use App\Core\App;

class FormSchema extends Model
{
    protected static string $table = 'form_schemas';
    protected static bool $softDelete = false;
    protected static bool $timestamps = true;
    protected static array $fillable = [
        'form_code', 'name_ar', 'name_en', 'form_fee', 'validity_days',
        'schema_json', 'version', 'published_at', 'is_active',
    ];

    public function getSchema(): array
    {
        return json_decode($this->schema_json ?? '{"sections":[]}', true) ?? ['sections' => []];
    }

    public function getSections(): array
    {
        $schema = $this->getSchema();
        $sections = $schema['sections'] ?? [];
        usort($sections, fn($a, $b) => ($a['order'] ?? 999) <=> ($b['order'] ?? 999));
        return $sections;
    }

    public static function findByCode(string $code): ?static
    {
        $db = App::getInstance()->db();
        $row = $db->selectOne("SELECT * FROM form_schemas WHERE form_code = ? AND is_active = 1", [$code]);
        if (!$row) {
            return null;
        }
        $instance = new static($row);
        $instance->exists = true;
        return $instance;
    }

    public static function allActive(): array
    {
        $db = App::getInstance()->db();
        return $db->select("SELECT * FROM form_schemas WHERE is_active = 1 ORDER BY name_ar");
    }
}