<?php
/**
 * Simple plugin system for configuration panels
 *
 *
 * @author jason.xie@victheme.com
 *
 */
abstract class VTCore_Zeus_Pages_Model {

  protected $form;
  protected $messages;
  protected $errors;
  protected $header;
  protected $object;
  protected $icon;
  protected $title;


  /**
   * Constructing class
   */
  public function __construct() {
    $this->messages = new VTCore_Bootstrap_BsMessages();
  }

  /**
   * Sub classes must extend this and insert
   * the configuration object and header.
   */
  abstract protected function config();


  /**
   * Menu call back method.
   * This is linked to Wordpress admin_menu action
   */
  public function buildPage() {

    // Booting assets
    wp_deregister_script('heartbeat');
    wp_enqueue_media();

    VTCore_Wordpress_Utility::loadAsset('wp-bootstrap');
    VTCore_Wordpress_Utility::loadAsset('theme-admin');
    VTCore_Wordpress_Utility::loadAsset('wp-media');
    VTCore_Wordpress_Utility::loadAsset('wp-ajax');
    VTCore_Wordpress_Utility::loadAsset('jquery-equalheight');
    VTCore_Wordpress_Utility::loadAsset('bootstrap-confirmation');

    $this->delete();

    // Populate the config objects
    // Child class must extend this method
    // and populate the config object and header
    $this->config();

    // Build the header
    $this->buildHeader();
    $this->header->render();

    // Build Form
    $this->buildForm();

    // Grab any errors
    $this->errors = $this->messages->getError();

    $this->save();

    $this->form->prependChild($this->messages->render());

    // Let other alter this form
    // Better use vtcore_zeus_alter_panel_config action!
    add_action('vtcore_zeus_theme_options_form_alter', $this->form);

    // Spit out the HTML Markup
    $this->form->render();

  }



  /**
   * Method for saving to database
   */
  protected function save() {
    // Save to database
    if (empty($this->errors)
        && isset($_POST['theme'])
        && isset($_POST['themeSaveSubmit'])) {

      $this->messages->setNotice(__('Configuration saved to database', BASE_THEME));

      $data = wp_unslash($_POST['theme']);
      $mods = get_theme_mods();

      $mods = VTCore_Utility::arrayMergeRecursiveDistinct($data, $mods);

      update_option('theme_mods_' . ACTIVE_THEME, $mods );

      // Remove customizer transient
      delete_transient('vtcore_zeus_customizer_context_' . ACTIVE_THEME);

      // Just promise to delete the cache on next page load
      update_option('vtcore_clear_cache', true);
    }

    return $this;
  }


  /**
   * Method for reseting the database
   */
  protected function delete() {
    // Reset the whole database
    if (isset($_POST['themeResetSubmit'])) {
      $this->messages->setNotice(__('Configuration deleted from database and retrieved the default configuration value.', BASE_THEME));


      $mods = get_theme_mods();

      $keys = explode('&', urldecode(http_build_query($_POST['theme'])));
      foreach ($keys as $query) {
        list($key, $value) = explode('=', $query);

        $key = str_replace(array('][', '[', ']'), array('.', '.', ''), $key);
        VTCore_Utility::removeArrayValueKeys($mods, $key);
      }

      update_option('theme_mods_' . ACTIVE_THEME, $mods );

      unset($_POST['theme']);

      // Just promise to remove cache on next page load
      update_option('vtcore_clear_cache', true);

      // Remove customizer transient
      delete_transient('vtcore_zeus_customizer_context_' . ACTIVE_THEME);
    }

    return $this;
  }




  /**
   * Build the page header
   */
  protected function buildHeader() {

    $this->header = new VTCore_Bootstrap_Grid_BsContainerFluid(array(
      'type' => 'div',
      'attributes' => array(
        'id' => 'theme-options-header',
      ),
    ));

    $this->header
      ->addChildren(new VTCore_Bootstrap_Grid_BsRow())
      ->lastChild()
      ->addChildren(new VTCore_Bootstrap_Grid_BsColumn(array(
        'grids' => array(
          'columns' => array(
            'mobile' => 12,
            'tablet' => 12,
            'small' => 12,
            'large' => 12,
          )
        ),
      )))
      ->lastChild()
      ->addChildren(new VTCore_Fontawesome_faIcon(array(
        'icon' => $this->icon,
        'shape' => 'circle',
        'position' => 'pull-left',
      )))
      ->addChildren(new VTCore_Bootstrap_Element_BsHeader(array(
        'text' => sprintf(__('%s Theme - %s', BASE_THEME), ucfirst(str_replace('_',  ' ', BASE_THEME)), $this->title),
        'small' => sprintf(__('version %s', BASE_THEME), VTCore_Zeus_Init::getThemeInfo('Version')),
      )));

    return $this;
  }




  /**
   * Build the main configuration form
   */
  protected function buildForm() {

    $this->form = new VTCore_Bootstrap_Form_BsInstance(array(
      'attributes' => array(
        'id' => 'theme-configuration-form',
        'method' => 'post',
        'action' => $_SERVER['REQUEST_URI'],
        'class' => array('container-fluid'),
        'autocomplete' => 'off',
      ),
    ));

    $this->form
      ->addChildren(new VTCore_Bootstrap_Grid_BsRow())
      ->lastChild()
      ->addChildren(new VTCore_Bootstrap_Grid_BsColumn(array(
        'grids' => array(
          'columns' => array(
            'mobile' => 12,
            'tablet' => 9,
            'small' => 9,
            'large' => 9,
          ),
        ),
      )))
      ->lastChild()
      ->addChildren($this->object->__toString());

    // Get the panel private validation results
    if ($this->object->getMessageObject()) {
      $errors = $this->object->getMessageObject()->getError();
      if ($this->object->getMessageObject()->getError()) {
        foreach ($this->object->getMessageObject()->getError() as $error) {
          $this->messages->setError($error);
        }
      }
    }



    $help_panel = $this->form
      ->lastChild()
      ->addChildren(new VTCore_Bootstrap_Grid_BsColumn(array(
        'grids' => array(
          'columns' => array(
            'mobile' => 12,
            'tablet' => 4,
            'small' => 3,
            'large' => 3,
          ),
        ),
      )))
      ->lastChild()
      ->addChildren(new VTCore_Bootstrap_Element_BsModal(array(
        //'show' => true,
        'attributes' => array(
          'id' => 'vtcore-zeus-help-modal',
        ),
      )))
      ->addChildren(new VTCore_Bootstrap_Element_BsPanel(array(
        'text' => __('Quick Help', BASE_THEME),
        'attributes' => array(
          'class' => array(
            'quick-help-panels'
          )
        ),
      )))
      ->lastChild()
      ->addContent(new VTCore_Bootstrap_Element_BsElement(array(
        'text' => __('Browse theme quick help links to assist you further when configuring this theme. If you need further assitance, please contact our <a href="mailto:support@victheme.com">our support team</a>.', BASE_THEME),
        'raw' => true,
      )))
      ->addChildren(new VTCore_Bootstrap_Element_BsListGroup())
      ->lastChild();


    // Build assistance help links
    $assistance = new VTCore_Zeus_Assistance();

    foreach ($assistance->getAssistanceItems() as $type => $item) {

      $assist = new VTCore_Bootstrap_Element_BsListObject();
      $assist
        ->addChildren(new VTCore_Html_Hyperlink(array(
          'attributes' => array(
          'target' => $item['target'],
          'href' => $item['url'],
          'data-type' => $item['type'],
          'data-toggle' => 'modal',
          'data-target' => '#vtcore-zeus-help-modal',
          ),
        )))
        ->lastChild()
        ->addChildren(new VTCore_Fontawesome_faIcon(array(
          'position' => 'pull-left',
          'icon' => 'question-circle',
        )))
        ->addChildren(new VTCore_Html_Element(array(
          'text' => $item['title'],
        )));

      $help_panel->addChildren($assist->__toString());
      unset($assist);

    }

    unset($help_panel);

    $this->form
      ->addChildren(new VTCore_Bootstrap_Form_BsSubmit(array(
        'attributes' => array(
          'name' => 'themeSaveSubmit',
          'value' => __('Save', BASE_THEME),
        ),
        'mode' => 'primary',
      )))
      ->addChildren(new VTCore_Bootstrap_Form_BsSubmit(array(
        'attributes' => array(
          'name' => 'themeResetSubmit',
          'value' => __('Reset', BASE_THEME),
        ),
        'mode' => 'danger',
        'confirmation' => true,
        'title' => __('Are you sure? This action is inreversible.', BASE_THEME),
      )));

    return $this->form;
  }
}