<?php

namespace GriffinForms\Frontend\Html\Forms;

class RowColumn extends \GriffinForms\Frontend\Html\Forms\Format
{
    protected $bs_rowcolumn_container_classes = '';

    public function html()
    {
        $is_theme_set = $this->data['is_theme_set'] ?? false;
        $css_class = 'col-md-' . $this->item->getProp('width');
        if (!$is_theme_set && !empty($this->bs_rowcolumn_container_classes)) {
            $css_class .= ' ' . esc_attr($this->bs_rowcolumn_container_classes);
        }
        $html = '<div class="' . esc_attr($css_class) . '">';
        $html .= $this->fields();
        $html .= '</div>';
        return $html;
    }
    
    private function fields()
    {
        $field_ids = $this->item->getProp('fields');
                
        if (empty($field_ids) or !is_array($field_ids)) {
            return;
        }
        
        $html = '<div class="griffinforms-rowcolumn-children-container col-md-12">';
        
        foreach ($field_ids as $field_id) {

            if (!$this->sql->itemExists('field', $field_id) or $field_id === '') {
                continue;
            }
            
            $field_type = $this->sql->getFieldType($field_id);
            $field_class = $this->config->getFrontendFieldClass((string) $field_type);

            if ($field_class === '' || !class_exists($field_class)) {
                $html .= $this->unavailableFieldHtml($field_id, (string) $field_type);
                continue;
            }

            $field = new $field_class($field_id, $this->data);
            $html .= $field->html();
        }
        $html .= '</div>';
        return $html;
    }

    protected function unavailableFieldHtml(int $field_id, string $field_type): string
    {
        $this->log->add(
            'warning',
            'field',
            $field_id,
            get_current_user_id(),
            sprintf('Unavailable frontend field renderer for field type "%s".', $field_type),
            'package_provider'
        );

        return sprintf(
            '<div class="griffinforms-field-unavailable alert alert-warning" data-gf-field-id="%1$d" data-gf-field-type="%2$s">%3$s</div>',
            absint($field_id),
            esc_attr($field_type),
            esc_html__('This field is unavailable because its renderer is not currently loaded.', 'griffinforms-form-builder')
        );
    }
}
