<?php

/**
 * Plugin Name: Updater Client
 * Description: Vérifie les mises à jour via une API externe.
 * Version: 1.0
 * Author: Toi
 */


class Updater {

  public function __construct() {
    add_filter('pre_set_site_transient_update_plugins', [$this, 'check_for_updates']);
    add_action('current_screen', [$this, 'maybe_force_update_check']);
    add_action('upgrader_process_complete', [$this, 'update_complete'], 10, 2);
  }

  public function check_for_updates($transient) {
    if (!is_object($transient)) {
      $transient = new stdClass();
    }

    if (!function_exists('get_plugin_data')) {
      require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }

    // Vérifier si le fichier existe
    if (!file_exists(WP_PLUGIN_DIR . '/' . ORPHIC_UI_NAME::PLUGIN_BASE)) {
      return $transient;
    }

    $plugin_data = get_plugin_data(WP_PLUGIN_DIR . '/' . ORPHIC_UI_NAME::PLUGIN_BASE);
    $installed_version = $plugin_data['Version'];

    // 1. Vérifier s'il y a une mise à jour
    $check_update = wp_remote_get(ORPHIC_UI_URL . 'wp-json/opm/v1/has-updates?version=' . $installed_version);
    $update_data = json_decode(wp_remote_retrieve_body($check_update), true);

    if (empty($update_data['update'])) {
      return $transient;
    }

    // 2. Vérifier la licence
    $verify_response = wp_remote_post(ORPHIC_UI_URL . 'wp-json/opm/v1/verify-download', [
      'body' => [
        'token' => get_option(ConstBlockOrphicOptionValue::TOKEN),
        'website' => get_site_url(),
        'date' => date('Y-m-d')
      ]
    ]);

    $verify_data = json_decode(wp_remote_retrieve_body($verify_response), true);
    // On n'ajoute la mise à jour que si la licence est valide
    if (empty($verify_data['Code'])) {
      $transient->response[ORPHIC_UI_NAME::PLUGIN_BASE] = (object) [
        'id' => ORPHIC_UI_NAME::PLUGIN_BASE,
        'new_version' => $update_data['new_version'],
        'package' => $update_data['package'],
        'url' => 'orphic.ca'
      ];
      update_option(ConstBlockOrphicOptionValue::LICENSE_STATUS, 1);
    } else {
      add_action('after_plugin_row_' . ORPHIC_UI_NAME::PLUGIN_BASE, [$this, 'show_license_notice'], 10, 3);
      update_option(ConstBlockOrphicOptionValue::LICENSE_STATUS, 0);
    }
    // Sauvegarder le statut de la licence pour l'affichage du message

    return $transient;
  }

  public function show_license_notice($plugin_file, $plugin_data, $status) {
    $license_status = get_option(ConstBlockOrphicOptionValue::LICENSE_STATUS, []);
    if ($license_status == 1) {
      return;
    }

    $message = __('An update is available! To access it, please activate your license in the plugin settings. <a href="' . admin_url('admin.php?page=orphic-wp-block') . '">' . __('Activate my license', 'orphic-ui') . '</a>', 'orphic-ui');

    printf(
      '<tr class="plugin-update-tr active">
        <td colspan="4" class="plugin-update colspanchange">
          <div class="update-message notice inline notice-warning notice-alt">
            <p>%s</p>
          </div>
        </td>
      </tr>',
      wp_kses_post($message)
    );
  }

  public function update_complete($upgrader, $options) {

    // Vérifier si c'est notre plugin qui est mis à jour
    if ($options['action'] === 'update' && $options['type'] === 'plugin') {
      if (isset($options['plugins'])) {
        // Mise à jour en masse de plugins
        $our_plugin = ORPHIC_UI_NAME::PLUGIN_BASE;

        if (!in_array($our_plugin, $options['plugins'])) {
          return;
        }
      }

      // Récupérer le token et faire la requête de mise à jour
      $token = get_option(ConstBlockOrphicOptionValue::TOKEN);
      if (empty($token)) {
        return;
      }

      // Récupérer la nouvelle version depuis le package mis à jour
      $plugin_data = $upgrader->skin->new_plugin_data;
      $new_version = isset($plugin_data['Version']) ? $plugin_data['Version'] : '';

      if (empty($new_version)) {
        // Fallback: lire directement le fichier plugin.php qui vient d'être mis à jour
        if (!function_exists('get_plugin_data')) {
          require_once(ABSPATH . 'wp-admin/includes/plugin.php');
        }
        $plugin_data = get_plugin_data(WP_PLUGIN_DIR . '/' . ORPHIC_UI_NAME::PLUGIN_BASE);
        $new_version = $plugin_data['Version'];
      }

      $response = wp_remote_post(ORPHIC_UI_URL . 'wp-json/opm/v1/update-website', [
        'body' => [
          'token' => $token,
          'website' => get_site_url(),
          'version' => $new_version
        ]
      ]);

      if (is_wp_error($response)) {
      } else {
        $response_data = json_decode(wp_remote_retrieve_body($response), true);
      }
    } else {
      error_log('Orphic Update Complete - Not our update type: ' . $options['action'] . ' - ' . $options['type']);
    }
  }

  public function maybe_force_update_check($screen) {
    if ($screen->base === 'plugins') {
      delete_site_transient('update_plugins');
    }
  }
}
