<?php
if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

// Ajax Script
function wcusage_admin_options_update_scripts( $hook_suffix ) {

  if ( ! current_user_can( 'manage_options' ) ) {
    return;
  }

  // Only load on our settings page. Be resilient to screen ID differences.
  $is_wcu_settings_page = ( isset( $_GET['page'] ) && $_GET['page'] === 'wcusage_settings' );
  $screen_ok = false;
  if ( function_exists( 'get_current_screen' ) ) {
    $screen = get_current_screen();
    if ( isset( $screen->id ) ) {
      $screen_ok = ( $screen->id === 'coupon-affiliates_page_wcusage_settings' || false !== strpos( $screen->id, 'wcusage_settings' ) );
    }
  }
  if ( ! $is_wcu_settings_page && ! $screen_ok ) {
    return;
  }

  // Enqueue our script early (in head) and localize data.
  $rel_path  = '../../../js/admin-options-update.js';
  $script_url  = plugin_dir_url( __FILE__ ) . $rel_path;
  $script_path = plugin_dir_path( __FILE__ ) . $rel_path;
  $version = file_exists( $script_path ) ? filemtime( $script_path ) : false;

  wp_enqueue_script( 'wcusage-admin-options-update', $script_url, array( 'jquery' ), $version, false ); // false = load in head
  wp_localize_script( 'wcusage-admin-options-update', 'wcusageUpdate', array(
    'ajax_url' => admin_url( 'admin-ajax.php' ),
    'nonce'    => wp_create_nonce( 'wcusage_dashboard_settings_ajax_nonce' ),
  ) );
}
add_action( 'admin_enqueue_scripts', 'wcusage_admin_options_update_scripts', 5 );

/***************
***** UPDATE: Text Input
***************/
add_action( 'wp_ajax_wcu-update-text', 'wcu_update_text' );
function wcu_update_text() {

  if ( current_user_can( 'manage_options' ) ) {

    check_ajax_referer('wcusage_dashboard_settings_ajax_nonce'); // Check nonce

    $option = sanitize_text_field( $_POST['option'] );
    $value = sanitize_textarea_field( htmlentities( $_POST['value'] ) );
    $CustomNum = sanitize_text_field( $_POST['customnum'] );
    $CustomNum1 = sanitize_text_field( $_POST['customnum1'] );
    $CustomNum2 = sanitize_text_field( $_POST['customnum2'] );

    if( !isset( $option ) || $option == '' ) {
        die(
            json_encode(
                array(
                    'success' => false,
                    'message' => 'Missing required information.'
                )
            )
        );
    }

    $option_group = get_option('wcusage_options');

    if($CustomNum) {

      $value = html_entity_decode(stripslashes($value));

      if(!is_array($option_group[$option])) {
        $option_group[$option] = array();
      }
      $option_group[$option][$CustomNum1][$CustomNum2] = $value;
      update_option('wcusage_options', $option_group);

    } else {

      $value = html_entity_decode(stripslashes($value));
      $option_group[$option] = $value;
      update_option( 'wcusage_options', $option_group );

    }

    wcusage_check_if_option_refresh_stats($option); // Refresh Stats?

    die(
        json_encode(
            array(
                'success' => true,
                //'message' => 'Database updated successfully to: ' . $option
            )
        )
    );

  }

}

/***************
***** UPDATE: Toggles
***************/
add_action( 'wp_ajax_wcu-update-toggle', 'wcu_update_toggle' );
function wcu_update_toggle() {

  if ( current_user_can( 'manage_options' ) ) {

    check_ajax_referer('wcusage_dashboard_settings_ajax_nonce'); // Check nonce

    $option = sanitize_text_field( $_POST['option'] );
    $multi = sanitize_text_field( $_POST['multi'] );
    $value = sanitize_text_field( $_POST['value'] );
    $key = sanitize_text_field( $_POST['key'] );

    if( !isset( $option ) || $option == '' ) {
        die(
            json_encode(
                array(
                    'success' => false,
                    'message' => 'Missing required information.'
                )
            )
        );
    }

    $option_group = get_option('wcusage_options');

    if($multi) {
      $order_type_custom = $option_group[$option];
      $order_type_custom_current = $option_group[$option];
      if(!is_array($order_type_custom)) {
        $order_type_custom = array();
        if($order_type_custom_current) {
          $order_type_custom = array($order_type_custom_current => "on");
        }
      }
      if($value) {
        $order_type_custom[$key] = "on";
      } else {
        unset($order_type_custom[$key]);
      }
      $option_group[$option] = $order_type_custom;
    } else {
      if($value == true) {
        $thevalue = "1";
      }
      if($value == "false") {
        $thevalue = "0";
      }
      $option_group[$option] = $thevalue;
    }

    update_option( 'wcusage_options', $option_group );

    wcusage_check_if_option_refresh_stats($option); // Refresh Stats?

    die(
        json_encode(
            array(
                'success' => true,
                //'message' => 'Database updated successfully to: ' . $option . " - " . $new
            )
        )
    );

  }

}

// Ajax: Refresh Stats for certain updates updating
function wcusage_check_if_option_refresh_stats($option) {
  $options_to_refresh = wcusage_options_refresh_stats();
  if(in_array($option, $options_to_refresh)) {
    $option_group = get_option('wcusage_options');
    $option_group['wcusage_refresh_date'] = time();
    update_option( 'wcusage_options', $option_group );
  }
  do_action('wcusage_check_if_option_refresh_stats', $option);
}

// Hook into options update
function wcusage_check_portal_option_update($option) {
  if($option == "wcusage_field_portal_enable") {
    $option_group = get_option('wcusage_options');
    $wcusage_portal_slug = wcusage_get_setting_value('wcusage_portal_slug', 'affiliate-portal');
    if($option_group['wcusage_field_portal_enable'] == "1") {
      add_rewrite_rule('^' . $wcusage_portal_slug . '/?$', 'index.php?affiliate_portal=1', 'top');
    } else {
      // Remove the rewrite rule
      $rules = get_option('rewrite_rules');
      if(isset($rules['^' . $wcusage_portal_slug . '/?$'])) {
        unset($rules['^' . $wcusage_portal_slug . '/?$']);
        update_option('rewrite_rules', $rules);
      }
    }
    flush_rewrite_rules();
  }
  // If wcusage_portal_slug is updated and wcusage_field_portal_enable is enabled
  if($option == "wcusage_portal_slug") {
    $option_group = get_option('wcusage_options');
    if($option_group['wcusage_field_portal_enable'] == "1") {
      add_rewrite_rule('^' . $option_group['wcusage_portal_slug'] . '/?$', 'index.php?affiliate_portal=1', 'top');
      flush_rewrite_rules();
    }
  }
  // If wcusage_mla_portal_slug is updated and wcusage_field_portal_enable is enabled
  if($option == "wcusage_mla_portal_slug") {
    $option_group = get_option('wcusage_options');
    if($option_group['wcusage_field_portal_enable'] == "1") {
      add_rewrite_rule('^' . $option_group['wcusage_mla_portal_slug'] . '/?$', 'index.php?mla_affiliate_portal=1', 'top');
      flush_rewrite_rules();
    }
  }
}
add_action('wcusage_check_if_option_refresh_stats', 'wcusage_check_portal_option_update', 10, 2);

// Post: Refresh Stats for certain updates updating
add_action('updated_option', 'wcusage_check_if_option_refresh_stats_post', 10, 3);
function wcusage_check_if_option_refresh_stats_post($option_name, $old_value, $value) {
    $never_update_commission_meta = wcusage_get_setting_value('wcusage_field_enable_never_update_commission_meta', '0');
    if (!$never_update_commission_meta && 'wcusage_options' == $option_name) {
        $options_to_refresh = wcusage_options_refresh_stats();
        foreach ($options_to_refresh as $key_interest) {
            if(isset($old_value[$key_interest]) && isset($value[$key_interest])) {
              if ($old_value[$key_interest] == $value[$key_interest]) {
                continue;
              }
              $option_group = get_option('wcusage_options');
              $option_group['wcusage_refresh_date'] = time();
              update_option( 'wcusage_options', $option_group );
              break;
            }
        }
    }
}

// Options to refresh stats on
function wcusage_options_refresh_stats() {
  $options_to_refresh = array(
    "wcusage_field_affiliate",
    "wcusage_field_affiliate_fixed_order",
    "wcusage_field_affiliate_fixed_product",
    "wcusage_field_commission_before_discount",
    "wcusage_field_commission_include_shipping",
    "wcusage_field_commission_before_discount_custom",
    "wcusage_field_commission_include_fees",
    "wcusage_field_order_max_commission",
    "wcusage_field_commission_rounding_mode",
    "wcusage_field_show_tax",
    "wcusage_field_affiliate_deduct_percent",
    "wcusage_field_priority_commission",
    "wcusage_field_affiliate_deduct_percent_show",
    "wcusage_field_order_type_custom",
    "wcusage_field_order_sort"
  );
  return $options_to_refresh;
}