<?php

namespace GriffinForms\Admin\App\Html\Widgets\PresentationArea\FormElements;

class PageRow extends \GriffinForms\Admin\App\Html\Widgets\PresentationArea\FormElements\Format
{

    protected $columns_width = 0;
    protected $bs_pagerow_container_classes = '';
    protected $bs_pagerow_heading_classes = 'h5 fw-medium mb-0';
    protected $bs_pagerow_description_classes = 'form-text text-muted mb-3';

    public function getHtml()
    {
        if ($this->item === false) {
            return;
        }

        $is_theme_set = $this->isThemeSet();
        // Only get row styles if theme is set
        $css = $is_theme_set ? $this->form_theme->getRowStyleCss() : '';
        $theme_class = !$is_theme_set ? ' gf-no-theme' : '';
        $additional_classes = !$is_theme_set && !empty($this->bs_pagerow_container_classes) ? ' ' . esc_attr($this->bs_pagerow_container_classes) : '';

        echo '<div id="' . esc_attr($this->getHtmlId($this->item_id)) . '" class="' . esc_attr('griffinforms-app-formlayout-pagerow d-flex align-items-start mb-3 p-2' . $theme_class . $additional_classes) . '"';
        $this->dataAttrs();
        echo ' style="' . esc_attr($css) . '" ';
        echo '>';

        $this->renderActionCluster($this->getContextActions(), array(
            'id'             => 'gf-row-icons-wrap',
            'label'          => __('Row actions', 'griffinforms-form-builder'),
            'meta_container' => true,
        ));

        echo '<div class="flex-fill">';

        echo '<div class="gf-builder-row-meta-shell">';
        // $this->rowName();
        $this->rowHeading();
        echo '</div>';

        echo '<div class="griffinforms-app-formlayout-pagerow-columns-container row mx-0" data-gf-itemid="' . absint($this->item_id) . '">';
        $this->rowColumns();
        $this->createRowColumnBtn();
        echo '</div>';

        echo '<div class="gf-builder-row-meta-shell">';
        $this->rowDescription();
        echo '</div>';

        echo '</div>';
        echo '</div>';
    }

    /**
     * Outputs an edit button icon for the row using the unified Buttons class and bsBtn utility.
     *
     * @return void
     */
    private function getContextActions()
    {
        $form_id = isset($_GET['form_id']) ? absint($_GET['form_id']) : 0;
        $editUrl = admin_url('admin.php?page=griffinforms-pagerow&id=' . $this->item_id . '&return=1');
        if ($form_id > 0) {
            $editUrl .= '&form_id=' . $form_id;
        }

        return array_merge(array(
            array(
                'id'      => 'drag',
                'label'   => __('Drag Row', 'griffinforms-form-builder'),
                'icon'    => 'drag_indicator',
                'icon_svg_file' => 'admin/images/toolbar-icons/builder/drag.svg',
                'class'   => 'gf-fe-drag-btn griffinforms-app-formlayout-pagerow-drag-handle',
                'action'  => 'drag',
                'context_type' => 'row',
            ),
            array(
                'id'      => 'edit',
                'label'   => __('Edit Row', 'griffinforms-form-builder'),
                'icon'    => 'edit',
                'icon_svg_file' => 'admin/images/toolbar-icons/builder/edit.svg',
                'href'    => $editUrl,
                'class'   => 'gf-edit-icon-btn',
                'action'  => 'edit',
                'context_type' => 'row',
            ),
            $this->getEmptyMetadataToggleAction(),
            array(
                'id'      => 'select-parent',
                'label'   => __('Select parent page', 'griffinforms-form-builder'),
                'icon'    => 'select_all',
                'icon_svg_file' => 'admin/images/toolbar-icons/builder/parent.svg',
                'href'    => '#',
                'class'   => 'gf-edit-icon-btn gf-select-parent-page-btn',
                'action'  => 'select-parent-page',
                'context_type' => 'row',
            ),
            $this->getDeleteMenuAction(
                'row',
                sprintf(__('Delete %s', 'griffinforms-form-builder'), $this->config->getFriendlyName('pagerow'))
            )
        ), $this->getMoveActions());
    }

    private function getMoveActions()
    {
        return array(
            array(
                'id'       => 'move-vertical',
                'label'    => __('Move row', 'griffinforms-form-builder'),
                'class'    => 'gf-fe-action-composite--vertical',
                'children' => array(
                    array(
                        'id'           => 'move-up',
                        'label'        => __('Move row up', 'griffinforms-form-builder'),
                        'icon'         => 'expand_less',
                        'icon_svg_file' => 'admin/images/toolbar-icons/builder/up.svg',
                        'class'        => 'gf-row-move-btn gf-row-move-up',
                        'action'       => 'move-row-up',
                        'context_type' => 'row',
                    ),
                    array(
                        'id'           => 'move-down',
                        'label'        => __('Move row down', 'griffinforms-form-builder'),
                        'icon'         => 'expand_more',
                        'icon_svg_file' => 'admin/images/toolbar-icons/builder/down.svg',
                        'class'        => 'gf-row-move-btn gf-row-move-down',
                        'action'       => 'move-row-down',
                        'context_type' => 'row',
                    ),
                ),
            )
        );
    }

    private function getEmptyMetadataToggleAction()
    {
        return array(
            'id'           => 'toggle-empty-metadata',
            'label'        => __('Show or hide optional metadata', 'griffinforms-form-builder'),
            'icon'         => 'short_text',
            'icon_svg_file' => 'admin/images/toolbar-icons/builder/add-heading-description.svg',
            'class'        => 'gf-edit-icon-btn gf-toggle-empty-metadata-btn',
            'action'       => 'toggle-empty-metadata',
            'context_type' => 'row',
        );
    }

    private function rowName()
    {
        echo '<div id="' . esc_attr($this->getHtmlId('name') . '-' . $this->item_id) . '">';
        $this->textUpdateField(
            'name',
            array('placeholder' => __('Name cannot be empty', 'griffinforms-form-builder'), 'required' => 'required'),
            array('font-size' => '10px')
        );
        echo '</div>';
    }

    private function rowHeading()
    {
        $is_theme_set = $this->isThemeSet();
        $css = $is_theme_set ? $this->form_theme->getRowHeadingCss() : '';
        $heading_classes = '';

        if (!$is_theme_set && !empty($this->bs_pagerow_heading_classes)) {
            $heading_classes = $this->bs_pagerow_heading_classes;
        }

        $this->optionalMetadataField(
            'heading',
            array(
                'ghost_label'     => __('Add heading', 'griffinforms-form-builder'),
                'wrapper_id'      => $this->getHtmlId('heading-' . $this->item_id),
                'wrapper_classes' => 'gf-hide-in-compact',
                'field_classes'   => $heading_classes,
                'attrs'           => array(
                    'placeholder' => __('Optional heading', 'griffinforms-form-builder'),
                    'data-gf-metadata-editor' => 'true',
                ),
                'style'           => array($css),
            )
        );
    }

    private function rowDescription()
    {
        $is_theme_set = $this->isThemeSet();
        $css = $is_theme_set ? $this->form_theme->getRowDescriptionCss() : '';
        $description_classes = '';

        if (!$is_theme_set && !empty($this->bs_pagerow_description_classes)) {
            $description_classes = $this->bs_pagerow_description_classes;
        }

        $this->optionalMetadataField(
            'description',
            array(
                'mode'            => 'textarea',
                'ghost_label'     => __('Add description', 'griffinforms-form-builder'),
                'wrapper_id'      => $this->getHtmlId('description-' . $this->item_id),
                'wrapper_classes' => 'gf-hide-in-compact',
                'field_classes'   => $description_classes,
                'attrs'           => array(
                    'placeholder' => __('Optional description', 'griffinforms-form-builder'),
                    'rows' => '2',
                    'data-gf-metadata-editor' => 'true',
                ),
                'style'           => array($css),
            )
        );
    }

    private function rowColumns()
    {
        $column_ids = $this->item->getProp('rowcolumns');
        
        if (empty($column_ids) or !is_array($column_ids)) {
            return;
        }

        foreach ($column_ids as $column_id) {
            $column = new RowColumn($column_id, $this->item_id, $this->item, $this->form_theme);

            if ($column->getProp('item') !== false) {
                $this->columns_width += $column->item->getProp('width');
            }
            
            $column->getHtml();
        }
    }

    private function createRowColumnBtn()
    {
        $hide_class = '';

        if ((12 - $this->columns_width) < 3) {
            $hide_class = 'visually-hidden';
        }

        echo '<div class="griffinforms-app-formlayout-pagerow-create-column-btn-container col p-3 d-flex justify-content-center align-items-center ' . esc_attr($hide_class) . '">';
        $this->buttons->staticinserterBtn([
            'class' => 'griffinforms-app-formlayout-pagerow-create-column-btn',
            'icon'  => 'add',
        ]);
        echo '</div>';
    }
}
