<?php

/**
 * Hook pour enregistrer l'API:
 * add_action('rest_api_init', array('Search_Bar_Orphic_UI', 'register_routes'));
 */

class Search_Bar_Orphic_UI
{
  /**
   * Clé pour les meta données de configuration
   */
  const META_KEY = '_orphic_search_bar_config';

  /**
   * Enregistre les routes de l'API REST
   */
  public static function register_routes()
  {
    // Route GET pour récupérer la configuration
    register_rest_route('orphic-ui/v1', '/search-bar/(?P<id>\d+)', array(
      'methods' => 'GET',
      'callback' => array(self::class, 'get_config'),
      'permission_callback' => '__return_true',
      'args' => array(
        'id' => array(
          'required' => true,
          'validate_callback' => function ($param) {
            return is_numeric($param);
          }
        )
      )
    ));

    register_rest_route('orphic-ui/v1', '/search-bar/(?P<id>\d+)', array(
      'methods' => 'POST',
      'callback' => array(self::class, 'update_config'),
      'permission_callback' => '__return_true',
      'args' => array(
        'id' => array(
          'required' => true,
          'validate_callback' => function ($param) {
            return is_numeric($param);
          }
        )
      )
    ));

    // Nouvelle route pour récupérer les types de posts
    register_rest_route('orphic-ui/v1', '/search-bar/post-types', array(
      'methods' => 'GET',
      'callback' => array(self::class, 'get_post_types'),
      'permission_callback' => '__return_true'
    ));

    // Route pour récupérer les pages du site
    register_rest_route('orphic-ui/v1', '/search-bar/pages', array(
      'methods' => 'GET',
      'callback' => array(self::class, 'get_pages'),
      'permission_callback' => '__return_true'
    ));
  }

  /**
   * Vérifie les permissions de l'utilisateur
   * 
   * @param WP_REST_Request $request
   * @return bool|WP_Error
   */
  public static function check_permissions($request)
  {
    $post_id = $request['id'];

    // Si le post n'existe pas, vérifie si l'utilisateur peut en créer un
    if (!get_post($post_id)) {
      return current_user_can('publish_posts');
    }

    return current_user_can('edit_post', $post_id);
  }

  /**
   * Met à jour la configuration de la barre de recherche
   * 
   * @param WP_REST_Request $request
   * @return WP_REST_Response
   */
  public static function update_config($request)
  {
    $post_id = $request['id'];
    $config = $request->get_param('config');

    // Log de débogage

    if (!isset($config['title'])) {
      return new WP_REST_Response(
        array(
          'success' => false,
          'message' => 'Configuration invalide : title est requis',
          'debug' => $config
        ),
        400
      );
    }

    $title = $config['title'];
    $post = get_post($post_id);

    if (!$post) {
      return new WP_REST_Response(
        array(
          'success' => false,
          'message' => 'Post non trouvé',
          'debug' => array('post_id' => $post_id)
        ),
        404
      );
    }

    $post_data = array(
      'ID' => $post_id,
      'post_title' => $title,
      'post_name' => sanitize_title($title),
      'post_type' => 'search_bar_orphic_ui',
      'post_status' => 'publish'
    );

    $update_post_result = wp_update_post($post_data, true);

    if (is_wp_error($update_post_result)) {
      return new WP_REST_Response(
        array(
          'success' => false,
          'message' => 'Erreur lors de la mise à jour du titre',
          'debug' => array(
            'error' => $update_post_result->get_error_message(),
            'post_data' => $post_data
          )
        ),
        500
      );
    }

    // Validation et nettoyage des données de recherche
    if (isset($config['search_config'])) {
      // Assurer que post_types est un tableau valide
      if (isset($config['search_config']['post_types'])) {
        $config['search_config']['post_types'] = array_values(
          array_filter(
            (array)$config['search_config']['post_types'],
            function ($post_type) {
              return post_type_exists($post_type);
            }
          )
        );
      } else {
        $config['search_config']['post_types'] = array();
      }

      // Validation et nettoyage des taxonomies
      if (isset($config['search_config']['taxonomies'])) {
        $taxonomies = (array)$config['search_config']['taxonomies'];
        $cleaned_taxonomies = array();

        foreach ($taxonomies as $post_type => $tax_array) {
          // Vérifier si le post type existe
          if (!post_type_exists($post_type)) {
            continue;
          }

          // Récupérer les taxonomies valides pour ce post type
          $valid_taxonomies = get_object_taxonomies($post_type);

          // Filtrer et nettoyer les taxonomies
          $cleaned_taxonomies[$post_type] = array_values(
            array_filter(
              (array)$tax_array,
              function ($taxonomy) use ($valid_taxonomies) {
                return in_array($taxonomy, $valid_taxonomies);
              }
            )
          );

          // Si le tableau est vide après nettoyage, ne pas l'inclure
          if (empty($cleaned_taxonomies[$post_type])) {
            unset($cleaned_taxonomies[$post_type]);
          }
        }

        $config['search_config']['taxonomies'] = $cleaned_taxonomies;
      } else {
        $config['search_config']['taxonomies'] = array();
      }

      // Valider les valeurs booléennes
      $config['search_config']['is_ajax_search'] = isset($config['search_config']['is_ajax_search'])
        ? (bool)$config['search_config']['is_ajax_search']
        : false;

      $config['search_config']['is_url_custom_search'] = isset($config['search_config']['is_url_custom_search'])
        ? (bool)$config['search_config']['is_url_custom_search']
        : false;

      // Valider l'URL personnalisée
      $config['search_config']['url_custom_search'] = isset($config['search_config']['url_custom_search'])
        ? esc_url_raw($config['search_config']['url_custom_search'])
        : '';

      //svg
      $config['style_config']['button_icon'] = isset($config['style_config']['button_icon'])
        ? str_replace('"', '\'', $config['style_config']['button_icon'])
        : '';
    }

    // Crée une copie de la configuration sans le titre
    $config_to_save = array(
      'search_config' => $config['search_config'] ?? array(),
      'display_config' => array(),
      'style_config' => $config['style_config'] ?? array()
    );

    // Log de débogage avant la sauvegarde

    $result = update_post_meta($post_id, self::META_KEY, wp_json_encode($config_to_save, JSON_UNESCAPED_UNICODE));

    if (false === $result) {
      $existing_meta = get_post_meta($post_id, self::META_KEY, true);
      if ($existing_meta === wp_json_encode($config_to_save, JSON_UNESCAPED_UNICODE)) {
        return new WP_REST_Response(
          array(
            'success' => true,
            'message' => 'Configuration à jour (aucun changement nécessaire)',
            'post_id' => $post_id,
            'config' => $config_to_save,
            'title' => $title
          ),
          200
        );
      }

      delete_post_meta($post_id, self::META_KEY);
      $result = add_post_meta($post_id, self::META_KEY, wp_json_encode($config_to_save, JSON_UNESCAPED_UNICODE), true);

      if (false === $result) {
        return new WP_REST_Response(
          array(
            'success' => false,
            'message' => 'Erreur lors de la sauvegarde de la configuration'
          ),
          500
        );
      }
    }

    return new WP_REST_Response(
      array(
        'success' => true,
        'message' => 'Configuration sauvegardée avec succès',
        'post_id' => $post_id,
        'config' => $config_to_save,
        'title' => get_the_title($post_id)
      ),
      200
    );
  }

  /**
   * Récupère la configuration d'une barre de recherche
   * 
   * @param WP_REST_Request $request
   * @return WP_REST_Response
   */
  public static function get_config($request)
  {
    $post_id = $request['id'];
    $post = get_post($post_id);

    if (!$post) {
      return new WP_REST_Response(
        array(
          'success' => false,
          'message' => 'Barre de recherche non trouvée'
        ),
        404
      );
    }

    $config = get_post_meta($post_id, self::META_KEY, true);
    $config = json_decode($config, true);

    if (empty($config)) {
      return new WP_REST_Response(
        array(
          'success' => false,
          'message' => 'Configuration non trouvée'
        ),
        404
      );
    }

    // Décoder le SVG si présent
    if (isset($config['style_config']['button_icon'])) {
      $config['style_config']['button_icon'] = html_entity_decode($config['style_config']['button_icon'], ENT_QUOTES | ENT_HTML5, 'UTF-8');
    }

    // Assurer la cohérence des données
    if (!isset($config['search_config'])) {
      $config['search_config'] = array();
    }

    // Initialiser les valeurs par défaut si nécessaire
    if (!isset($config['search_config']['post_types'])) {
      $config['search_config']['post_types'] = array();
    }

    if (!isset($config['search_config']['taxonomies'])) {
      $config['search_config']['taxonomies'] = array();
    }

    if (!isset($config['search_config']['is_ajax_search'])) {
      $config['search_config']['is_ajax_search'] = false;
    }

    if (!isset($config['search_config']['is_url_custom_search'])) {
      $config['search_config']['is_url_custom_search'] = false;
    }

    if (!isset($config['search_config']['url_custom_search'])) {
      $config['search_config']['url_custom_search'] = '';
    }

    return new WP_REST_Response(
      array(
        'success' => true,
        'config' => $config
      ),
      200
    );
  }

  /**
   * Récupère la liste des types de posts disponibles
   */
  public static function get_post_types()
  {
    // Types de posts WordPress à exclure
    $excluded_types = array(
      'attachment',
      'revision',
      'nav_menu_item',
      'custom_css',
      'customize_changeset',
      'oembed_cache',
      'user_request',
      'wp_block',
      'wp_template',
      'wp_template_part',
      'wp_global_styles',
      'wp_navigation',
      'wp_font_family',
      'wp_font_face',
      'search_bar_orphic_ui' // Notre propre type de post
    );

    global $wp_post_types;
    $formatted_types = array();

    foreach (array_keys($wp_post_types) as $post_type) {
      // Exclure les types non désirés
      if (in_array($post_type, $excluded_types)) {
        continue;
      }

      $post_type_obj = $wp_post_types[$post_type];

      // Ne garder que les types publics avec une UI
      if (!$post_type_obj->public || !$post_type_obj->show_ui) {
        continue;
      }

      // Récupérer les taxonomies associées au type de post
      $taxonomies = get_object_taxonomies($post_type, 'objects');
      $formatted_taxonomies = array();

      foreach ($taxonomies as $tax) {
        // Ne garder que les taxonomies publiques
        if ($tax->public) {
          $formatted_taxonomies[] = array(
            'value' => $tax->name,
            'label' => $tax->labels->singular_name
          );
        }
      }

      $formatted_types[] = array(
        'value' => $post_type,
        'label' => $post_type_obj->labels->singular_name,
        'taxonomies' => $formatted_taxonomies
      );
    }

    return new WP_REST_Response(array(
      'success' => true,
      'post_types' => $formatted_types
    ));
  }

  /**
   * Récupère la liste des pages du site avec leurs URLs
   */
  public static function get_pages()
  {
    $formatted_pages = array();

    // Récupérer les pages normales
    $pages = get_pages(array(
      'sort_column' => 'menu_order,post_title',
      'post_status' => 'publish'
    ));

    foreach ($pages as $page) {
      $formatted_pages[] = array(
        'value' => get_page_link($page->ID),
        'label' => $page->post_title,
        'id' => $page->ID,
        'slug' => $page->post_name,
        'type' => 'page'
      );
    }

    return new WP_REST_Response(array(
      'success' => true,
      'pages' => $formatted_pages
    ));
  }
}
