<?php

/**
 * API pour la gestion du leadership
 * 
 * @package WB_Onboard
 * @since 1.0.0
 */
class Wb_Api_Leader
{

  /**
   * Enregistrer les routes API pour le leadership
   */
  public function register_routes()
  {
    // Endpoint pour vérifier le statut de leadership
    register_rest_route('wb-onboard/v1', '/check-leader', array(
      'methods' => 'GET',
      'callback' => [$this, 'check_leader'],
      'permission_callback' => [$this, 'wb_register_leader_permission_callback']
    ));

    // Endpoint pour prendre le leadership
    register_rest_route('wb-onboard/v1', '/claim-leader', array(
      'methods' => 'POST',
      'callback' => [$this, 'claim_leader'],
      'permission_callback' => [$this, 'wb_register_leader_permission_callback']
    ));
  }

  /**
   * Vérifier le statut de leadership
   * 
   * @param WP_REST_Request $request
   * @return WP_REST_Response
   */
  public function check_leader($request)
  {
    $page_id = $request->get_param('page_id');
    $current_leader = WB_Leader_Service::get_current_leader();
    $stats = WB_Leader_Service::get_stats();

    $response_data = [
      'is_leader' => false,
      'can_claim' => false,
      'current_leader' => null,
      'stats' => $stats
    ];

    if ($page_id) {
      $response_data['is_leader'] = WB_Leader_Service::is_leader($page_id);
    }

    // Peut prendre le leadership si aucun leader ou si c'est déjà nous
    $response_data['can_claim'] = !$current_leader || ($page_id && WB_Leader_Service::is_leader($page_id));

    if ($current_leader) {
      $response_data['current_leader'] = [
        'page_id' => substr($current_leader['page_id'], -8), // Afficher seulement les 8 derniers caractères
        'user_id' => $current_leader['user_id'],
        'time_active' => time() - $current_leader['last_activity'],
        'claimed_at' => $current_leader['claimed_at']
      ];
    }

    return wp_send_json_success($response_data, 200);
  }

  /**
   * Prendre le leadership
   * 
   * @param WP_REST_Request $request
   * @return WP_REST_Response
   */
  public function claim_leader($request)
  {
    $page_id = $request->get_param('page_id');
    $force = $request->get_param('force') === true || $request->get_param('force') === 'true';

    if (empty($page_id)) {
      return wp_send_json_error('Page ID is required', 400);
    }

    $success = false;
    $action = '';

    if ($force) {
      // Force claim (bouton "Devenir leader")
      $success = WB_Leader_Service::force_claim_leadership($page_id);
      $action = 'force_claimed';
    } else {
      // Claim automatique (si aucun leader ou renouvellement)
      $success = WB_Leader_Service::claim_leadership($page_id);
      $action = 'auto_claimed';
    }

    if ($success) {
      $current_leader = WB_Leader_Service::get_current_leader();

      return wp_send_json_success([
        'leader' => true,
        'action' => $action,
        'page_id' => substr($page_id, -8),
        'message' => $force ? 'Leadership forcé avec succès' : 'Leadership pris automatiquement',
        'leader_info' => $current_leader
      ], 200);
    } else {
      $current_leader = WB_Leader_Service::get_current_leader();

      return wp_send_json_success([
        'leader' => false,
        'action' => 'claim_failed',
        'page_id' => substr($page_id, -8),
        'message' => 'Un autre utilisateur est déjà leader',
        'current_leader' => $current_leader ? [
          'page_id' => substr($current_leader['page_id'], -8),
          'user_id' => $current_leader['user_id'],
          'time_active' => time() - $current_leader['last_activity']
        ] : null
      ], 200);
    }
  }

  /**
   * Vérification des permissions pour les endpoints de leadership
   * 
   * @return bool|WP_Error
   */
  public function wb_register_leader_permission_callback()
  {
    return true; // Même logique que les autres APIs pour l'instant

    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));
  }
}
