<?php

class Wb_Api
{

  const WB_ONBOARD_OPTIONS = 'wb_onboard_options';

  public function register_routes()
  {
    register_rest_route('wb-onboard/v1', '/magic-link', array(
      'methods' => 'POST',
      'callback' => array($this, 'generate_magic_link'),
      'permission_callback' => array($this, 'check_api_credentials')
    ));

    register_rest_route('wb-onboard/v1', '/block-website', array(
      'methods' => 'POST',
      'callback' => array($this, 'block_website'),
      'permission_callback' => array($this, 'check_api_credentials')
    ));
  }

  public function check_api_credentials($request)
  {
    $params = $request->get_json_params();
    $auth_user = isset($params['api_user']) ? $params['api_user'] : '';
    $auth_password = isset($params['api_password']) ? $params['api_password'] : '';

    return $auth_user === WORDPRESS_API_USER &&
      $auth_password === WORDPRESS_API_PASSWORD;
  }

  // https://{site_url}/wp-json/wb-onboard/v1/magic-link
  public function generate_magic_link($request)
  {

    $params = $request->get_json_params();
    $theme = $params['theme'];
    $industry = $params['industry'];
    $company_name = $params['company_name'];
    $website_url = $params['website_url'];
    $email = $params['email'];
    $name = $params['name'];
    $company_uuid = $params['company_uuid'];
    $company_slug = $params['company_slug'];
    $client_key_guid = $params['client_key_guid'];
    $init_form_data = $params['init_form_data'];
    $user_uuid = $params['user_uuid'];
    $website_dashboard_url = $params['website_dashboard_url'];

    // Créer ou récupérer l'utilisateur editor
    //todo: better name for the user
    $user = get_user_by('login', 'editor_user');
    if (!$user) {
      $user_id = wp_create_user(
        'editor_user',
        wp_generate_password(),
        $email || 'editor@' . parse_url(get_site_url(), PHP_URL_HOST)
      );

      if (!is_wp_error($user_id)) {
        $user = get_user_by('ID', $user_id);
        $user->set_role('wb_onboarding_user');
      }
    }

    if (is_wp_error($user)) {
      return new WP_Error('user_creation_failed', 'Failed to create or get user');
    }

    // Stocker le token actuel pour pouvoir supprimer l'ancien
    $current_token = get_user_meta($user->ID, 'current_magic_token', true);
    if ($current_token) {
      delete_transient('magic_link_' . $current_token);
    }

    list($theme, $variation) = $this->check_theme($theme);

    $options_created = update_option(self::WB_ONBOARD_OPTIONS, array(
      'theme' => $theme,
      'variation' => $variation,
      'industry' => $industry,
      'company_name' => $company_name,
      'website_url' => $website_url,
      'email' => $email,
      'name' => $name,
      'company_uuid' => $company_uuid,
      'temp_site_url' => get_home_url(),
      'company_slug' => $company_slug,
      'client_key_guid' => $client_key_guid,
      'user_uuid' => $user_uuid,
      'website_dashboard_url' => $website_dashboard_url
    ));

    if (isset($init_form_data) && $init_form_data) {
      if (in_array($industry, ['1', '2', '3', '7', '9', '18', '19', '37', '38'])) {
        if ($variation == "advanced") {
          $defaultData = file_get_contents(WB_ONBOARD_PLUGIN_DIR_PATH . '/feature/default-data/miocommerce/olympus/cleaning-advanced.json');
        } else {
          $defaultData = file_get_contents(WB_ONBOARD_PLUGIN_DIR_PATH . '/feature/default-data/miocommerce/olympus/cleaning.json');
        }
      } else if (in_array($industry, ['5', '4', '13', '41'])) {
        if ($variation == "advanced") {
          $defaultData = file_get_contents(WB_ONBOARD_PLUGIN_DIR_PATH . '/feature/default-data/miocommerce/olympus/carwash-advanced.json');
        } else {
          $defaultData = file_get_contents(WB_ONBOARD_PLUGIN_DIR_PATH . '/feature/default-data/miocommerce/olympus/carwash.json');
        }
      } else if (in_array($industry, ["21", "31", "39"])) {
        if ($variation == "advanced") {
          $defaultData = file_get_contents(WB_ONBOARD_PLUGIN_DIR_PATH . '/feature/default-data/miocommerce/olympus/landscaping-advanced.json');
        } else {
          $defaultData = file_get_contents(WB_ONBOARD_PLUGIN_DIR_PATH . '/feature/default-data/miocommerce/olympus/landscaping.json');
        }
      } else {
        $defaultData = file_get_contents(WB_ONBOARD_PLUGIN_DIR_PATH . '/feature/default-data/miocommerce/olympus/generic.json');
      }

      $contactScript = "";
      if ($client_key_guid && $company_slug) {
        $contactScript = "<div id='miocommerce-integration'></div><script>(function(p,l,a,t,f,o,r) {p['miocommerce-integration']=f;p[f]= function() {(p[f].q=p[f].q||[]).push(arguments)},p[f].l=1*new Date();o=l.createElement(a),r=l.getElementsByTagName(a)[0];o.async=1;o.src=t+'?t='+1*new Date();r.parentNode.insertBefore(o,r)})(window,document,'script','//int.miocommerce.com/int/platform.boot.min.js','miocommerce');miocommerce('miocommerce','" . $client_key_guid . "','contact-us','" . $company_slug . "','en');</script>";
      }
      $defaultData = str_replace('%%CONTACT_SCRIPT%%', $contactScript, $defaultData);

      $floatingDockScript = "";
      if ($client_key_guid && $company_slug) {
        $floatingDockScript = "<script>(function(p,l,a,t,f,o,r) {p['miocommerce-buy-and-book']=f;p[f]= function() {(p[f].q=p[f].q||[]).push(arguments)},p[f].l=1*new Date();o=l.createElement(a),r=l.getElementsByTagName(a)[0];o.async=1;o.src=t+'?t='+1*new Date();r.parentNode.insertBefore(o,r)})(window,document,'script','//int.miocommerce.com/int/platform.buyandbook.boot.min.js','miocommerce2');miocommerce2('miocommerce2','" . $client_key_guid . "','buy-and-book','" . $company_slug . "','en');</script>";
      }
      $defaultData = str_replace('%%FLOATING_DOCK_SCRIPT%%', $floatingDockScript, $defaultData);

      $defaultData = str_replace('http://localhost:8888/olympus-blocks', get_home_url(), $defaultData);
      $defaultData = str_replace('%%THEME%%', $theme, $defaultData);
      update_option('options_wb_onboard_form_data', $defaultData);
      update_option('options_wb_onboard_form_step_n', 0);
    }

    // Générer un token unique
    $token = wp_generate_password(32, false);
    // 4 semaines = 4 * 7 * 24 * 60 * 60 = 2419200 secondes
    set_transient('magic_link_' . $token, $user->ID, 4 * WEEK_IN_SECONDS);

    // Sauvegarder le nouveau token
    update_user_meta($user->ID, 'current_magic_token', $token);

    // Construire le lien magique
    $magic_link = add_query_arg(array(
      'action' => 'magic_login',
      'token' => $token
    ), admin_url());

    return array(
      'magic_link' => $magic_link
    );
  }

  private function check_theme($theme)
  {
    $returned_theme = 'ace';
    $returned_variation = 'premium';

    $themes = array('ace', 'accelerator', 'triumph');
    $variations = array('premium', 'advanced');

    $theme_exploded = explode("-", $theme);

    if (isset($theme_exploded[0])) {
      if (in_array($theme_exploded[0], $themes)) {
        $returned_theme = $theme_exploded[0];
      }
    }

    if (isset($theme_exploded[1])) {
      if (in_array($theme_exploded[1], $variations)) {
        $returned_variation = $theme_exploded[1];
      }
    }

    return [$returned_theme, $returned_variation];
  }

  public function block_website($request)
  {
    $params = $request->get_json_params();
    //if option is not set, set it to false
    if (!get_option('wb_onboard_website_is_blocked')) {
      update_option('wb_onboard_website_is_blocked', false);
    }

    switch ($params['action']) {
      case 'block-website':
        error_log('Blocked website');
        update_option('wb_onboard_website_is_blocked', true);
        $this->clear_flyingpress_cache();
        wp_send_json_success(array('website_is_blocked' => true));
        die();
        break;
      case 'unblock-website':
        error_log('Unblocked website');
        update_option('wb_onboard_website_is_blocked', false);
        $this->clear_flyingpress_cache();
        wp_send_json_success(array('website_is_blocked' => false));
        die();
        break;
    }
  }

  /**
   * Clear FlyingPress cache if the plugin is active
   */
  private function clear_flyingpress_cache()
  {
    // Vérifier si FlyingPress est actif et si la fonction existe
    if (function_exists('flying_press_purge_everything')) {
      flying_press_purge_everything();
      error_log('FlyingPress cache cleared');
    } else if (class_exists('FlyingPress\Purge')) {
      // Alternative si la classe FlyingPress\Purge existe
      try {
        \FlyingPress\Purge::purge_everything();
        error_log('FlyingPress cache cleared via class');
      } catch (Exception $e) {
        error_log('Error clearing FlyingPress cache: ' . $e->getMessage());
      }
    } else {
      error_log('FlyingPress not found or not active');
    }
  }
}
