<?php

/**
 * The admin-specific functionality of the plugin.
 *
 * @link       https://orphic.ca
 * @since      1.0.0
 *
 * @package    Wb_Onboard
 * @subpackage Wb_Onboard/admin
 */

/**
 * The admin-specific functionality of the plugin.
 *
 * Defines the plugin name, version, and two examples hooks for how to
 * enqueue the admin-specific stylesheet and JavaScript.
 *
 * @package    Wb_Onboard
 * @subpackage Wb_Onboard/admin
 * @author     Orphic Inc. <contact@orphic.ca>
 */
class Wb_Onboard_Admin
{

  /**
   * The ID of this plugin.
   *
   * @since    1.0.0
   * @access   private
   * @var      string    $plugin_name    The ID of this plugin.
   */
  private $plugin_name;

  /**
   * The version of this plugin.
   *
   * @since    1.0.0
   * @access   private
   * @var      string    $version    The current version of this plugin.
   */
  private $version;

  /**
   * Initialize the class and set its properties.
   *
   * @since    1.0.0
   * @param      string    $plugin_name       The name of this plugin.
   * @param      string    $version    The version of this plugin.
   */
  public function __construct($plugin_name, $version)
  {
    global $pagenow;

    $this->plugin_name = $plugin_name;
    $this->version = $version;

    // require_once(WB_ONBOARD_PLUGIN_DIR_PATH . '/admin/partials/wb-onboard-menu-page.php');
  }

  /**
   * Register the stylesheets for the admin area.
   *
   * @since    1.0.0
   */
  public function enqueue_styles()
  {

    /**
     * This function is provided for demonstration purposes only.
     *
     * An instance of this class should be passed to the run() function
     * defined in Wb_Onboard_Loader as all of the hooks are defined
     * in that particular class.
     *
     * The Wb_Onboard_Loader will then create the relationship
     * between the defined hooks and the functions defined in this
     * class.
     */

    wp_enqueue_style($this->plugin_name, plugin_dir_url(__FILE__) . 'css/wb-onboard-admin.css', array(), $this->version, 'all');
  }

  /**
   * Register the JavaScript for the admin area.
   *
   * @since    1.0.0
   */
  public function enqueue_scripts()
  {

    /**
     * This function is provided for demonstration purposes only.
     *
     * An instance of this class should be passed to the run() function
     * defined in Wb_Onboard_Loader as all of the hooks are defined
     * in that particular class.
     *
     * The Wb_Onboard_Loader will then create the relationship
     * between the defined hooks and the functions defined in this
     * class.
     */

    wp_enqueue_script($this->plugin_name, plugin_dir_url(__FILE__) . 'js/wb-onboard-admin.js', array('jquery'), $this->version, false);

    if (get_current_screen()->base === 'toplevel_page_wb-onboard-menu-page') {
      wp_enqueue_style('wb-admin-page-style', plugin_dir_url(__FILE__) . 'css/wb-admin-page-style.css', array(), $this->version, false);

      wp_enqueue_script('wb-react-page', WB_ONBOARD_PLUGIN_DIR_URL . 'build/index.js', array('wp-element', 'wp-api-fetch'), $this->version, true);
      wp_localize_script('wb-react-page', 'wb_onboard_options', get_option('wb_onboard_options'));
      wp_localize_script('wb-react-page', 'live_app_data', $this->get_live_app_data());
      wp_localize_script('wb-react-page', 'wb_onboard_vars', array(
        'site_url' => home_url(),
      ));
    }
  }

  public function get_live_app_data()
  {
    $task_api = new TasksAPI();
    $tasks_status = $task_api->get_tasks_status();
    $data = array(
      'site_url' => get_home_url(),
      'dashboard_url' => get_admin_url(),
      'is_live_website' => get_option('wb_is_done_creating_site') ? 'true' : 'false',
      'onboard_options' => get_option('wb_onboard_options'),
      'tasks' => $tasks_status,
      'form-connect-domaine-live-site' => get_option('form-connect-domaine-live-site') ? 'true' : 'false',
    );
    return $data;
  }

  public function wb_onboard_register_menu_page()
  {
    add_menu_page(
      __('Website helper', 'wb-onboard'),
      'Website helper',
      'read',
      'wb-onboard-menu-page',
      array($this, 'wb_onboard_menu_page_callback'),
      'dashicons-welcome-view-site',
      1
    );
  }

  public function wb_onboard_menu_page_callback()
  {
    require_once(WB_ONBOARD_PLUGIN_DIR_PATH . '/admin/partials/wb-onboard-menu-page.php');
  }

  public function wb_onboard_menu_page_add_classes($classes)
  {
    if (get_current_screen()->base === 'toplevel_page_wb-onboard-menu-page') {
      return "$classes is-wb-fullscreen-mode";
    }
  }

  public function wb_register_form_rest_api_routes()
  {
    //Add the GET 'wb-onboarding/v1/options' endpoint to the Rest API
    register_rest_route(
      'wb-onboarding/v1',
      '/options',
      array(
        'methods'  => 'GET',
        'callback' => array($this, 'wb_register_form_rest_api_read_options_callback'),
        'permission_callback' => array($this, 'wb_register_form_permission_callback')
      )
    );

    //Add the POST 'wb-onboarding/v1/options' endpoint to the Rest API
    register_rest_route(
      'wb-onboarding/v1',
      '/options',
      array(
        'methods'             => 'POST',
        'callback'            => array($this, 'wb_register_form_rest_api_update_options_callback'),
        'permission_callback' => array($this, 'wb_register_form_permission_callback')
      )
    );

    //Add the POST 'wb-onboarding/v1/create-website' endpoint to the Rest API
    register_rest_route(
      'wb-onboarding/v1',
      '/create-website',
      array(
        'methods'             => 'POST',
        'callback'            => array($this, 'wb_register_form_rest_api_create_website_callback'),
        'permission_callback' => array($this, 'wb_register_form_permission_callback')
      )
    );
  }

  public function wb_register_form_permission_callback()
  {
    return true;
    if (is_user_logged_in()) {
      $user = wp_get_current_user();
      $role = (array) $user->roles;
      if (isset($role[0]) && ($role[0] == 'wb_onboarding_user' || $role[0] == 'administrator')) {
        return true;
      }
    }
    return new WP_Error('rest_forbidden', esc_html__('You do not have REST permissions.', 'wb-onboarding'), array('status' => 401));
  }

  public function wb_register_form_rest_api_read_options_callback($data)
  {
    //Generate the response
    $response = [];
    $response['wb_onboard_form_data'] = json_decode(get_option('options_wb_onboard_form_data'));


    //Prepare the response
    $response = new WP_REST_Response($response);

    return $response;
  }

  public function wb_register_form_rest_api_update_options_callback($request)
  {
    $wb_onboard_form_data = $request->get_param('wb_onboard_form_data');

    //Update the options
    update_option('options_wb_onboard_form_data', json_encode($wb_onboard_form_data));

    $response = new WP_REST_Response('Data successfully added.', '200');

    return $response;
  }

  public function wb_register_form_rest_api_create_website_callback($request)
  {
    $params = $request->get_json_params();
    $is_preview = $params['is_preview'];
    $onboard_data = $params['onboard_data'];

    $form_data = json_decode(get_option('options_wb_onboard_form_data'), true);

    $result = array("status" => 'error');

    // Choose the right automatisation based on the current customer
    if ($onboard_data && $onboard_data['company_uuid'] == "67d4d57e-c5e3-49d4-8cbb-6201342e7d3d") {
      $automation = new MioCommerceOlympusAutomatisation($form_data, $onboard_data, $is_preview);
      $result = $automation->createWebsite();
    }

    // We are going live
    if (!$is_preview) {
      update_option('wb_is_done_creating_site', true);

      if (!str_contains(get_site_url(), 'localhost')) {
        // API call to tod APP to change status
        wp_remote_request(
          'https://app.themesondemand.com/api/websites/' . $onboard_data['user_uuid'] . '/' . $onboard_data['company_uuid'] . '/status?status=live',
          [
            "method" => 'PATCH'
          ]
        );
      }
    }


    if ($result['status'] === 'success') {
      return new WP_REST_Response($result, 200);
    } else {
      return new WP_REST_Response($result, 500);
    }
  }

  public function wb_edit_login_form()
  { ?>
    <style type="text/css">
      #login h1 a,
      .login h1 a {
        background-image: none;
        height: 65px;
        width: 320px;
        background-size: 86px 74px;
        background-repeat: no-repeat;
        padding-bottom: 30px;
      }
    </style>
  <?php }

  public function wb_edit_login_logo_url()
  {
    return home_url();
  }

  public function wb_edit_login_logo_url_title()
  {
    return 'TOD Website builder';
  }

  public function wb_redirect_onboarding_user()
  {
    if (is_user_logged_in()) {
      $user = wp_get_current_user();
      $role = (array) $user->roles;

      $screen = get_current_screen();
      if (isset($role[0]) && $role[0] == 'wb_onboarding_user' && isset($screen->id) && $screen->id !== 'toplevel_page_wb-onboard-menu-page') {
        wp_redirect(admin_url('admin.php?page=wb-onboard-menu-page'));
        exit();
      }
    }
  }

  public function wb_hide_wp_toolbar()
  {
    if (!is_user_logged_in()) return false;
    if (isset($_GET['hidetoolbar'])) {
      return false;
    }
    if (isset($_SERVER['HTTP_SEC_FETCH_DEST']) && $_SERVER['HTTP_SEC_FETCH_DEST'] == 'iframe') {
      return false;
    }
    return true;
  }

  public function register_wb_helper_widget()
  {
    if (wp_get_current_user()->user_login === 'admin' && defined('WB_SHOW_ADMIN_WIDGET')) { // Only show the widget to the admin account and when it is explicitly allowed
      wp_add_dashboard_widget(
        'wb_helper_widget',
        'WB admin helper',
        array($this, 'wb_helper_widget')
      );
    }
  }

  public function wb_helper_widget()
  {
    // Reset form section
    echo '<div class="wb-reset-section">';
    echo '<h3>Reset Options</h3>';
    echo '<form id="wb-reset-form">';

    // 1. Select the reset state
    echo '<div class="wb-form-group">';
    echo '<label for="wb-reset-state">Reset State:</label>';
    echo '<select id="wb-reset-state" name="reset_state">';
    echo '<option value="generic" selected>Generic (Default)</option>';
    echo '<option value="cleaning">Cleaning</option>';
    echo '<option value="cleaning-advanced">Cleaning Advanced</option>';
    echo '<option value="carwash">Carwash</option>';
    echo '<option value="carwash-advanced">Carwash Advanced</option>';
    echo '<option value="landscaping">Landscaping</option>';
    echo '<option value="landscaping-advanced">Landscaping Advanced</option>';
    echo '</select>';
    echo '</div>';

    // 2. Button to trigger the reset
    echo '<div class="wb-form-group">';
    echo '<button type="button" id="wb-reset-trigger" class="button button-primary">Trigger Reset</button>';
    echo '<span id="wb-reset-status" style="margin-left: 10px; display: none;"></span>';
    echo '</div>';
    echo '</form>';
    echo '</div>';

    // 3. Add the JavaScript for the AJAX function
  ?>
    <script type="text/javascript">
      jQuery(document).ready(function($) {
        $('#wb-reset-trigger').on('click', function() {
          var resetState = $('#wb-reset-state').val();
          var $statusSpan = $('#wb-reset-status');

          // Show loading status
          $statusSpan.text('Processing...').show();

          // Call AJAX function
          $.ajax({
            url: ajaxurl,
            type: 'POST',
            data: {
              action: 'wb_trigger_reset',
              reset_state: resetState,
              security: '<?php echo wp_create_nonce('wb_reset_nonce'); ?>'
            },
            success: function(response) {
              console.log(response);
              if (response.success) {
                $statusSpan.text('Reset completed successfully!').css('color', 'green');
              } else {
                $statusSpan.text('Error: ' + response.data).css('color', 'red');
              }
            },
            error: function() {
              $statusSpan.text('Connection error. Please try again.').css('color', 'red');
            }
          });
        });
      });
    </script>
<?php

    // Rest of the widget code goes here
  }



  public function handle_reset_ajax()
  {
    // Check nonce for security
    if (!check_ajax_referer('wb_reset_nonce', 'security', false)) {
      wp_send_json_error('Security check failed');
    }

    // Get the reset state
    $reset_state = isset($_POST['reset_state']) ? sanitize_text_field($_POST['reset_state']) : 'generic';

    update_option('wb_is_done_creating_site', false);
    $demoData = file_get_contents(WB_ONBOARD_PLUGIN_DIR_PATH . '/feature/default-data/miocommerce/olympus/generic.json');

    switch ($reset_state) {
      case 'cleaning':
        $demoData = file_get_contents(WB_ONBOARD_PLUGIN_DIR_PATH . '/feature/default-data/miocommerce/olympus/cleaning.json');
        break;
      case 'cleaning-advanced':
        $demoData = file_get_contents(WB_ONBOARD_PLUGIN_DIR_PATH . '/feature/default-data/miocommerce/olympus/cleaning-advanced.json');
        break;
      case 'carwash':
        $demoData = file_get_contents(WB_ONBOARD_PLUGIN_DIR_PATH . '/feature/default-data/miocommerce/olympus/carwash.json');
        break;
      case 'carwash-advanced':
        $demoData = file_get_contents(WB_ONBOARD_PLUGIN_DIR_PATH . '/feature/default-data/miocommerce/olympus/carwash-advanced.json');
        break;
      case 'landscaping':
        $demoData = file_get_contents(WB_ONBOARD_PLUGIN_DIR_PATH . '/feature/default-data/miocommerce/olympus/landscaping.json');
        break;
      case 'landscaping-advanced':
        $demoData = file_get_contents(WB_ONBOARD_PLUGIN_DIR_PATH . '/feature/default-data/miocommerce/olympus/landscaping-advanced.json');
        break;
    }

    $demoData = str_replace('http://localhost:8888/olympus-blocks', get_home_url(), $demoData);

    $demoData = str_replace('%%CONTACT_SCRIPT%%', "", $demoData);
    $demoData = str_replace('%%FLOATING_DOCK_SCRIPT%%', "", $demoData);
    $demoData = str_replace('%%THEME%%', "accelerator", $demoData);

    update_option('options_wb_onboard_form_data', $demoData);
    update_option('options_wb_onboard_form_step_n', 0);

    update_option('form-connect-domaine-live-site', false);

    wp_send_json_success('Reset completed');
  }


  public function log($message)
  {
    $pluginlog = plugin_dir_path(__FILE__) . 'debug.log';
    $message =  $message . PHP_EOL;
    error_log($message, 3, $pluginlog);
  }
}
