<?php
/**
 * Subscribe form parser class
 *
 * @package wp-viral-click
 * @author InstaProduct
 * @link http://insta-product.com/
 */
if ( ! class_exists( 'IPJck_Form' )) 
{
  /**
   * Subscribe form parser
   */
  class IPJck_Form
  {
    /**
     * Parse form html
     *
     * @param  string $html
     * @return array
     */
    public static function parse( $html )
    {
      $html = stripslashes( $html );
      //Get form action
      $action = '';
      preg_match_all( '@action=\"([^\"]+)\"@', $html, $matches );
      if ( ! empty( $matches[1] )) {
        $action = array_shift( $matches[1] );
      }
      //Get input
      $fields  = array();
      $hiddens = array();
      preg_match_all( '@\<input([^\>]+)\>@', $html, $matches );
      if ( ! empty( $matches[1] )) 
      {
        foreach( $matches[1] as $input )
        {
          $regex = "@(\S+)=[\"\']?((?:.(?![\"\']?\s+(?:\S+)))+.)[\"\']?@";
          preg_match_all( $regex, $input, $inpmatch );

          if ( ! empty( $inpmatch[0] ) )
          {
            $type = $name = $value = '';
            foreach( $inpmatch[0] as $_match )
            {
              $_match = trim( $_match, '"' );
              $_match = trim( $_match, "'" );
              $parts  = explode( '=', $_match );
              if ( count( $parts ) > 2 ) {
                $key = array_shift( $parts );
                $val = implode( '=', $parts );
                $parts = array( $key, $val );
              }
              $key = $val = '';
              if ( ! empty( $parts )) {
                $key = array_shift( $parts );
              }
              if ( ! empty( $parts )) {
                $val = array_shift( $parts );
                $val = trim( $val );
                $val = trim( $val, '"' );
                $val = trim( $val, "'" );
              }
              if ( $key == 'type' ) {
                $type = $val;
              } elseif ( $key == 'name' ) {
                $name = $val;
              } elseif ( $key == 'value' ) {
                $value = $val;
              }
            }
            if ( $type == 'email' || $type == 'text' ) {
              $fields[] = $name;
            } elseif ( $type == 'hidden' ) {
              $hiddens[$name] = $value;
            }
          }
        }
      }
      return array(
        'action'    => $action,
        'fields'    => $fields,
        'hiddens'   => $hiddens
      );
    }
  }
}
