<?php

namespace Salesloo\Libraries;

class Form_Parser
{

    static $__forms;

    public static function process($html)
    {
        if ($html !== '') {

            $dom = new \DOMDocument;
            @$dom->loadHTML('' . $html);

            $xpath = new \DOMXpath($dom);

            $forms = $xpath->query('//form');

            foreach ($forms as $i => $form) {
                self::$__forms[$i]['method'] = $form->getAttribute('method');
                self::$__forms[$i]['action'] = $form->getAttribute('action');

                $fields = $xpath->query('.//input | .//select | .//textarea | .//label', $form);
                self::$__forms[$i]['fields'] = (new static)->getElements($fields);
            }

            return self::$__forms;
        }

        return false;
    }

    private function getElements($elements)
    {

        $result = array();

        foreach ($elements as $i => $element) {

            switch ($element->tagName) {

                case "input":
                case "select":
                case "textarea":

                    if ($element->getAttribute('type') == 'submit') break;

                    $arrayKey = ($element->getAttribute('id') !== "") ? $element->getAttribute('id') : $i;

                    $result[] = $arrayKey;

                case "label":

                    if ($element->getAttribute('for'))
                        $result[$element->getAttribute('for')]['label'] = $element->nodeValue;

                    break;
            }
        }

        return $result;
    }
}
