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

  private $schema;

  /**
   * Override parent method
   * @return VTCore_Zeus_Pages_Style
   */
  protected function config() {

    $this->icon = 'pencil-square-o';
    $this->title = __('Style', BASE_THEME);

    $this->object = new VTCore_Zeus_Panels_Style(array(
      'features' => VTCore_Zeus_Init::getFeatures(),
      'schema' => VTCore_Zeus_Init::getSchema(),
      'process' => !empty($_POST['theme']),
    ));

    return $this;
  }


  /**
   * Overriding parent method for hijacking
   * the submit button for ajax
   * @return void|VTCore_Bootstrap_Form_BsInstance
   */
  protected function buildForm() {

    VTCore_Wordpress_Utility::loadAsset('wp-ajax');

    parent::buildForm();

    $button = $this->form->findChildren('attributes', 'name', 'themeSaveSubmit');
    $button = array_shift($button);

    $queues = $this->object->getConfig()->get('colors.contents');

    if (is_array($queues)) {
      $queues = array_keys($queues);
    }
    else {
      $queues = array();
    }

    if (is_object($button)) {
      $button
        ->addData('ajax-mode', 'post')
        ->addData('ajax-target', '#theme-configuration-form')
        ->addData('ajax-loading-text', __('Saving Schema', BASE_THEME))
        ->addData('ajax-object', 'VTCore_Zeus_Pages_Style')
        ->addData('ajax-action', 'vtcore_ajax_framework')
        ->addData('ajax-value', 'saveSchema')
        ->addData('ajax-queue', $queues)
        ->addClass('btn-ajax');

      $this->form->addChildren(new VTCore_Wordpress_Form_WpNonce(array(
        'action' => 'vtcore-ajax-nonce-admin',
      )));
    }

    return $this->form;

  }

  /**
   * Ajax callback function
   */
  public function renderAjax($post) {

    $_POST = $post['data'];
    $active = $_POST['theme']['schema-active'];
    $queue = $post['queue'];
    $render = false;

    if (!isset($_POST['theme'])
        || !isset($_POST['theme']['schema-active'])
        || !isset($post['queue'])
        || !isset($_POST['theme']['schemas'][$active])) {
      return $render;
    }

    // Use rapid transient only valid for a minute
    $this->object = get_transient('vtcore_zeus_style_ajax_object');

    if (empty($this->object)) {
      $this->config();
      set_transient('vtcore_zeus_style_ajax_object', $this->object, 1 * MINUTE_IN_SECONDS);
    }

    $this->object->buildAccordionContext();

    $form = new VTCore_Zeus_Schema_Panes($this->object->getConfig()->get('colors.contents.' . $queue . '.content'));
    $form
      ->addProcessor('post', new VTCore_Form_Post())
      ->processForm()
      ->processError(false, false);

    $this->errors = $form->getErrors();

    // Error found
    if (!empty($this->errors)) {

      foreach ($this->errors as $error) {
        $this->messages->setError($error);
      }

      $render['action'][] = array(
        'mode' => 'prepend',
        'target' => $post['target'],
        'content' => $this->messages->render()->__toString(),
      );

      $render['action'][] = array(
        'mode' => 'replace',
        'target' => '[panel-delta="' . $queue . '"]',
        'content' => $form->__toString(),
      );
    }

    // No error found proceed with saving
    else {

      $_POST['themeSaveSubmit'] = true;

      $this->save();

      $render['action'][] = array(
        'mode' => 'delete',
        'target' => $post['target'] . ' > .alert.alert-success',
      );

      $render['action'][] = array(
        'mode' => 'prepend',
        'target' => $post['target'],
        'content' => $this->messages->render()->__toString(),
      );

    }

    // Free Memory
    $form = null;
    unset($form);

    // Free memory
    $this->object = null;
    unset($this->object);

    return $render;

  }


  /**
   * Overriding parent method for customized save logic
   * @return $this
   */
  protected function save() {

    if (empty($this->errors)
        && isset($_POST['theme'])
        && isset($_POST['themeSaveSubmit'])
        && !isset($_POST['changeSchemaColor'])) {

      $this->schema = new VTCore_Zeus_Schema_Factory();

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

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

      // Merging schemas
      foreach ($this->schema->getSchemas() as $schema) {

        // Merging the post into the old stored data
        // This is needed due to the lazy loading ajax system
        // have the possibility not to have all the schema
        // panes loaded.
        if ($schema->getSchema('id') == $data['schema-active']) {

          $oldSchema = $schema->getData('color');

          foreach ($data['schemas'][$schema->getSchema('id')]['color'] as $key => $value) {
            $oldSchema[$key] = $value;
          }

          $data['schemas'][$schema->getSchema('id')]['color'] = $oldSchema;
        }

        // Recording the stored schemas back into database
        // so user wont ever lose configured schema data
        else {
          $data['schemas'][$schema->getSchema('id')]['color'] = $schema->getData('color');
        }
      }

      // Clear Customizer cache
      $this->hash = 'vtcore_zeus_customizer_' . ACTIVE_THEME . '-' . $data['schema-active'];
      delete_transient($this->hash);

      // Don't do Single update_options, it will overwrite (or remove) other
      // configuration that is not controlled by this form.
      foreach ($data as $key => $value) {
        set_theme_mod($key, $value);
      }

      $this->schema->clearCache();

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

      // Free Memory
      $this->schema = null;
      unset($this->schema);

    }

    return $this;
  }


  /**
   * Overriding parent method for customizing delete process
   * @return $this|void
   */
  protected function delete() {

    // Change Schema
    if (isset($_POST['changeSchemaColor'])) {
      set_theme_mod('schema-active', $_POST['theme']['schema-active']);
      $this->messages->setNotice(sprintf(__('Style Schema switched to %s', BASE_THEME), $_POST['theme']['schema-active']));

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


    // Reset Schema
    if (isset($_POST['resetSchemaColor'])) {
      $old_schema = get_theme_mod('schemas');
      if (isset($old_schema[$_POST['theme']['schema-active']]['color'])) {

        $this->messages->setNotice(sprintf(__('Schema %s reverted to its default value.', BASE_THEME), $_POST['theme']['schema-active']));

        // Clear Customizer cache
        $this->hash = 'vtcore_zeus_customizer_' . ACTIVE_THEME . '-' . $_POST['theme']['schema-active'];
        delete_transient($this->hash);

        unset($old_schema[$_POST['theme']['schema-active']]);
        unset($_POST['theme']);

        set_theme_mod('schemas', $old_schema);
      }

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

    parent::delete();
  }

}