<?php

namespace GriffinForms\Admin\Html\Elements;

class itemInformation extends \GriffinForms\Admin\Html\Format
{
    protected $lang;
    protected $sql;
    protected $item_type;
    protected $item_id;
    protected $form_id;
    
    public function html()
    {
        $this->otherForms();
    }
    
    protected function otherForms()
    {
        $method = 'formsWithThis' . $this->item_type;
        $count = absint($this->$method()) - 1;
        
        if ($count === 0) {
            echo '<span class="text-success">';
            echo esc_html($this->lang->noformsWithItem($this->item_type));
            echo '</span>';
        } else {
            echo '<span class="text-danger">';
            echo esc_html($this->lang->formsWithItem($this->item_type, $count));
            echo '</span>';
        }
    }
    
    protected function formsWithThisFormpage()
    {
        $forms = $this->sql->getParents('form', 'formpages', $this->item_id);
        
        return $forms;
    }
    
    protected function formsWithThisPagerow()
    {
        $formpages = $this->sql->getParents('formpage', 'pagerows', $this->item_id);
        $forms = array();
        
        foreach ($formpages as $formpage) {
            array_push($forms, $this->sql->getParents('form', 'formpages', $formpage));
        }
        
        return $forms;
    }
    
    protected function formsWithThisRowcolumn()
    {
        $pagerows = $this->sql->getParents('pagerow', 'rowcolumns', $this->item_id);
        $formpages = array();
        $forms = array();
        
        foreach ($pagerows as $pagerow) {
            $parents = $this->sql->getParents('formpage', 'pagerows', $pagerow);
            $formpages = array_merge($formpages, $parents);
        }
        
        foreach ($formpages as $formpage) {
            $parents = $this->sql->getParents('form', 'formpages', $formpage);
            $forms = array_merge($forms, $parents);
        }
        
        return $forms;
    }
    
    protected function formsWithThisField()
    {
        $forms = $this->sql->getItems('form', array('id', 'name'));
        $form_fields = array();
        $forms_count = 0;
        
        foreach ($forms as $form) {
            $form_fields[$form->id] = $this->sql->allField($form->id);
        }
        
        foreach ($form_fields as $form_id => $field_ids) {
            if (in_array($this->item_id, $field_ids)) {
                $forms_count += 1;
            }
        }
        
        return $forms_count;
    }
    
    public function __construct($item_type, $item_id, $form_id)
    {
        $this->item_type = $item_type;
        $this->item_id = $item_id;
        $this->form_id = $form_id;
        $this->setAll();
        $this->setLang('formpages');
        $this->setHelper('sql', 'formpages');
    }
}