<?php

namespace apexl\Io\modules\display\components;

use apexl\Io\includes\Entity;
use apexl\Io\includes\Routes;

class EntityFilteredDisplayTable extends EntityDisplayTable
{
    protected FilterForm $filterForm;

    public function __construct(Entity $entity = null, $replacements = [], $withButtons = true, $buttonFormat='buttons')
    {
        parent::__construct($entity, $replacements);
        if ($entity !== null) {
            $this->setFilters('orderBy[]='.$entity->primaryKey.'&orderBy[]=DESC');

            if ($withButtons) {
                if ($buttonFormat == 'dropmenu') {
                    $this->addCommonButtonsAsDropdown();
                } else {
                $this->addCommonButtons();
            }
        }
    }
    }

    public function addFilterForm($routeName, $title = null, $header = 5, $modal=false, $modalTitle="", $filterFormClass=null)
    {
        $this->filterForm = (new FilterForm())
            ->src(Routes::getRoutePattern($routeName))
            ->title($title)
            ->header($header);
        if ($filterFormClass) {
            $this->filterForm->addClass($filterFormClass);
        }

        if ($modal) {
            $modal = (new Modal())->setButtonContent('<i class="fa fa-bars-filter"></i>')->addComponent($this->filterForm)->setTitle('Filter')->addClass('modal-filter');
            if ($modalTitle) {
                $modal->setTitle($modalTitle);
            }
            $this->addSupportComponent($modal);
        } else {
            $this->addSupportComponent($this->filterForm);
        }

        return $this;
    }

    public function removeFilterForm()
    {
        foreach ($this->supportComponents as $id => $supportComponent) {
            if ($supportComponent instanceof FilterForm) { // Standard filter forms
                unset($this->supportComponents[$id]);
            } elseif ($supportComponent instanceof Modal) { // Modal filter forms
                foreach ($supportComponent->getComponents() as $component) {
                    if ($component instanceof FilterForm) {
                        unset($this->supportComponents[$id]);
                    }
                }
            }
        }
    }

    public function addHeaderModal($modalTitle, $contentComponents, $icon='circle-question')
    {
        $modal = (new Modal())->setButtonContent('<i class="fa-regular fa-'.$icon.'"></i>')->addComponents($contentComponents)->setTitle($modalTitle)->addClass('modal-help');
        $this->addSupportComponent($modal);

        return $this;
    }

}
