<?php

namespace GriffinForms\Includes\MergeTokens\Resolvers;

use GriffinForms\Includes\MergeTokens\ResolverInterface;

class FormResolver implements ResolverInterface
{
    public function resolve(array $token, array $context): ?string
    {
        $attr = strtolower((string) ($token['attr'] ?? ''));

        $form = $context['form_object'] ?? null;
        if (!$form && isset($context['form_id']) && class_exists('\\GriffinForms\\Items\\Form')) {
            $form = new \GriffinForms\Items\Form();
            $form->loadItem((int) $context['form_id']);
        }

        if (!$form) {
            $form_meta = $context['form'] ?? $context['form_meta'] ?? [];
            return $this->resolveFromArray($attr, $form_meta);
        }

        switch ($attr) {
            case 'id':
                return (string) ($form->getProp('id') ?? $context['form_id'] ?? '');
            case 'name':
                return (string) ($form->getProp('name') ?? '');
            case 'heading':
                return (string) ($form->getProp('heading') ?? '');
            case 'description':
                return (string) ($form->getProp('description') ?? '');
        }

        return null;
    }

    private function resolveFromArray(string $attr, array $meta): ?string
    {
        if (empty($meta)) {
            return null;
        }

        if ($attr === 'id' && isset($meta['id'])) {
            return (string) $meta['id'];
        }
        if ($attr === 'name' && isset($meta['name'])) {
            return (string) $meta['name'];
        }
        if ($attr === 'heading' && isset($meta['heading'])) {
            return (string) $meta['heading'];
        }
        if ($attr === 'description' && isset($meta['description'])) {
            return (string) $meta['description'];
        }

        return null;
    }
}
