<?php

class WDIControllerSettings_wdi {

  function __construct() {

  }

  public function execute() {
    $this->display();
  }

  public function display() {
    $this->reset_access_token();
    $this->basic_instagram_api_connect();

    require_once(WDI_DIR . '/admin/models/WDIModelSettings_wdi.php');
    $model = new WDIModelSettings_wdi();
    require_once(WDI_DIR . '/admin/views/WDIViewSettings_wdi.php');
    $view = new WDIViewSettings_wdi($model);

    $message = WDILibrary::get('message', '');
    if ( !empty($message) ) {
      echo WDILibrary::message($message, 'error');
    }
    $view->display();
  }

  private function reset_access_token() {
    $reset_access_token = WDILibrary::get('wdi_reset_access_token_input', '');
    if ( !empty($reset_access_token) && $reset_access_token == '1' ) {
      global $wpdb;
      $wpdb->query('DELETE FROM ' . $wpdb->prefix . 'options WHERE option_name = "wdi_instagram_options"');
      $wpdb->query('DELETE FROM ' . $wpdb->prefix . 'options WHERE option_name = "wdi_first_user_username"');
      WDILibrary::redirect(add_query_arg(array( 'page' => 'wdi_settings' ), admin_url('admin.php')));
    }
  }

  private function basic_instagram_api_connect() {
    if ( !empty($_REQUEST['wdi_access_token']) && !empty($_REQUEST['user_id']) ) {
      $wdi_options = wdi_get_options();
      $user_id = WDILibrary::get('user_id', '');
      $user_name = WDILibrary::get('username', '');
      $expires_in = WDILibrary::get('expires_in', '');
      $access_token = WDILibrary::get('wdi_access_token', '');
      $wdi_options['wdi_start_in'] = time();
      $wdi_options['wdi_user_id'] = $user_id;
      $wdi_options['wdi_user_name'] = $user_name;
      $wdi_options['wdi_expires_in'] = $expires_in;
      $wdi_options['wdi_access_token'] = $access_token;
      update_option(WDI_OPT, $wdi_options);
      // @TODO add success message.
      WDILibrary::redirect(add_query_arg(array( 'page' => 'wdi_settings' ), admin_url('admin.php')));
    }
  }
}