<?php

/**
 * Gestion de la migration des anciens locks
 */
class Lockee_Migration extends Lockee_Singleton
{
  const STATUS_NEEDED = 'needed';
  const STATUS_LAUNCHED = 'launched';
  const STATUS_FINISHED = 'finished';
  const DEBUG_AJAX = false;
  const MIGRATION_LOCK_KEY = 'lockee_migration_lock';
  const MIGRATION_STATUS_KEY = 'lockee_migration_status';
  const MIGRATION_PROGRESS_KEY = 'lockee_migration_progress';

  /**
   * Initialize the migration
   */
  protected function init() {}

  /**
   * Add the migration page to the admin menu
   */
  public function add_migration_page()
  {
    if (!current_user_can('manage_options')) {
      return;
    }
    add_submenu_page(
      'edit.php?post_type=lockee_lock',
      __('Locks migration', 'lockee'),
      __('Locks migration', 'lockee'),
      'manage_options',
      'lockee-migration',
      array($this, 'render_migration_page')
    );
  }

  /**
   * Add a notice to inform users about the now locks post type
   */
  public function migration_notice()
  {
    if (!current_user_can('manage_options')) {
      return;
    }
    $has_visited_settings = get_option('lockee_settings_visited', false);

    if (!$has_visited_settings) {
      echo '<div class="notice notice-success is-dismissible">';
      echo '<h3>' . __('Welcome to the new Lockee locks management!', 'lockee') . '</h3>';
      echo '<p>' . __('Now, you can manage your locks in a dedicated post type. You can access to the new locks and its settings in the "Lockee" menu.', 'lockee') . '</p>';
      echo '<p>' . __('If you have previously used the Lockee plugin and created locks directly in posts or pages, you can migrate your old locks to the new post type "Lock" or activate an option in Lockee settings to continue to display the metabox "Lock" on posts and pages.', 'lockee') . '</p>';
      echo '<p>';
      echo __('Follow these links to make your choice:', 'lockee');
      echo ' <a href="' . esc_url(admin_url('edit.php?post_type=lockee_lock&page=lockee-migration')) . '">' . __('Locks migration', 'lockee') . '</a>';
      echo ' | ';
      echo '<a href="' . esc_url(admin_url('edit.php?post_type=lockee_lock&page=lockee-settings')) . '">' . __('Lockee settings', 'lockee') . '</a>';
      echo '</p>';
      echo '</div>';
    }
  }

  /**
   * Render the migration page
   */
  public function render_migration_page()
  {
    if (!current_user_can('manage_options')) {
      wp_die(__('You do not have permission to launch migration.', 'lockee'));
    }
    update_option('lockee_settings_visited', true);
    $this->delete_log_file();
    settings_errors('lockee_messages');
    $migration_status = $this->count_posts_to_migrate();
?>

    <div class="wrap">
      <h1><?php _e('Locks migration', 'lockee'); ?></h1>
      <p><?php _e('This page allows you to migrate old locks created directly in posts or pages to the new Lockee post type "Locks".', 'lockee'); ?></p>
      <p><?php _e('Migrating old locks allows you to group them all in one place for easier management.', 'lockee'); ?> <?php _e("Locks created directly in pages or posts cannot be added elsewhere with the new Gutenberg block (but it is still possible with the shortcode).", 'lockee'); ?></p>
      <div class="infobar">
        <?php
        echo $migration_status > 0 ?  sprintf(_n('%d lock could be migrated', '%d locks could be migrated', $migration_status, 'lockee'),  $migration_status) : __('No lock could be migrated', 'lockee');
        ?>
      </div>
      <form id="lockee-migration-form" class="lockee-migrate-form" method="post">
        <?php wp_nonce_field('lockee_migration_nonce', 'lockee_migration_nonce'); ?>
        <input type="hidden" name="action" value="lockee_migration">
        <button id="lockee-migrate-button"
          type="submit"
          class="button button-primary lockee-migrate-action"
          style="margin-top: 10px;"
          <?php echo $migration_status === 0 ? 'disabled' : ''; ?>>
          <?php _e('Start Migration', 'lockee'); ?>
        </button>
      </form>
      <div id="lockee-migration-progress" style="display: none; margin-top: 10px;">
        <div class="progress-bar">
          <div class="progress-bar-fill" style="width: 0%"></div>
          <div class="progress-bar-text">0%</div>
        </div>
        <p class="progress-message"></p>
      </div>
      <div id="lockee-migration-log" style="margin-top: 10px;">
        <h2><?php _e('Migrations History', 'lockee'); ?></h2>
        <p><?php _e('Below, you can find the logs of previous migrations. You can restore a migration by clicking on the "Restore" button next to each log entry.', 'lockee'); ?> <?php _e('This will restore the migrated locks to their previous state.', 'lockee'); ?> <?php _e('Use this feature with precaution.', 'lockee'); ?></p>
        <div id="lockee-migration-log-content" class="infobar" style="display: flex; flex-direction: column;">
          <?php
          $log_dir = plugin_dir_path(__DIR__) . 'logs/';
          $logs = glob($log_dir . '*.json');
          $logs = array_reverse($logs); // Sort logs by date, newest first

          if ($logs && count($logs) > 0) {
            foreach ($logs as $log_file) {
              $filename = basename($log_file);
              $restored = strpos($filename, '_restored') > -1;
              $restoredText = $restored ? __('already restored', 'lockee') : '';
              $parts = explode('_', $filename);
              $date = isset($parts[1]) ? date_i18n(
                get_option('date_format'),
                strtotime($parts[1])
              ) : '';
              $time = isset($parts[1]) ? date_i18n(
                get_option('time_format'),
                strtotime($parts[1])
              ) : '';
              $size = intval($parts[2]) ?? 0;

          ?>
              <div class="migration-log-list">
                <div style="flex:1;text-align:left;"><?php printf(__("Migration of %s at %s", "lockee"), $date, $time) ?> (<?php printf(_n('%s lock', '%s locks', $size, 'lockee'), $size); ?>) <strong><?php echo $restoredText ?></strong></div>
                <?php if (!$restored): ?>
                  <form method="post" class="lockee-migrate-form">
                    <?php wp_nonce_field('lockee_migration_nonce', 'lockee_migration_nonce'); ?>
                    <input type="hidden" name="action" value="lockee_restoration">
                    <input type="hidden" name="log_file" value="<?php echo esc_attr($filename); ?>">
                    <button class="button button-primary lockee-migrate-action"><?php _e("Restore", "lockee"); ?></button>
                  </form>
                <?php else: ?>
                  <span class="button button-primary" style="cursor: not-allowed; user-select:none;" disabled="true"><?php _e("Restore", "lockee"); ?></span>
                <?php endif; ?>
                <a href="<?php echo esc_url(plugins_url('../logs/' . $filename, __FILE__)); ?>" class="button-link" download><?php _e('Download', 'lockee') ?></a>
                <?php $this->render_delete_button($filename); ?>
              </div>
          <?php
            }
          } else {
            echo '<div class="migration-log-list" style="justify-content:center;">' . __('No migration log available.', 'lockee') . '</div>';
          }
          ?>
        </div>
      </div>
    </div>
    <script>
      lockeeMigrationReload = <?php echo get_option(self::MIGRATION_STATUS_KEY) === 'launched' ? 'true' : 'false'; ?>
    </script>
  <?php
  }

  /**
   * Render the delete button for a log file
   */
  private function render_delete_button($filename)
  {
  ?>
    <form method="post">
      <?php wp_nonce_field('lockee_migration_nonce', 'lockee_migration_nonce'); ?>
      <input type="hidden" name="action" value="lockee_delete_log">
      <input type="hidden" name="log_file" value="<?php echo esc_attr($filename); ?>">
      <button class="button-link button-link-delete lockee-migrate-action" onclick="if (!confirm('<?php echo esc_js(__('Are you sure you want to delete this log file? Be careful, this action is irreversible.', 'lockee')); ?>')) return false;"><?php _e("Delete", "lockee"); ?></button>
    </form>
<?php
  }

  /**
   * AJAX handler to migrate remaining shortcodes
   */
  private function acquire_migration_lock()
  {
    $lock_key = self::MIGRATION_LOCK_KEY;
    if (get_transient($lock_key)) {
      return false;
    }
    set_transient($lock_key, true, 5 * MINUTE_IN_SECONDS);
    return true;
  }

  /**
   * Release the migration lock
   */
  private function release_migration_lock()
  {
    delete_transient(self::MIGRATION_LOCK_KEY);
  }

  /**
   * Enqueue scripts for migration
   */
  public function enqueue_migration_scripts($hook)
  {
    if ($hook !== 'lockee_lock_page_lockee-migration') {
      return;
    }

    wp_enqueue_script(
      'lockee-migration',
      plugins_url('js/migration.js', dirname(__FILE__)),
      array('jquery'),
      LOCKEE_VERSION,
      true
    );
    $this->add_css_styles();

    wp_localize_script('lockee-migration', 'lockeeMigration', array(
      'ajaxurl' => admin_url('admin-ajax.php'),
      'nonce' => wp_create_nonce('lockee_migration_nonce'),
      'i18n' => array(
        'migrating' => __('Migration in progress...', 'lockee'),
        'error' => __('An error occurred during migration.', 'lockee'),
        'success' => __('Migration completed successfully.', 'lockee')
      )
    ));
  }

  /**
   * AJAX handler for migration progress
   */
  public function ajax_migration_progress()
  {
    check_ajax_referer('lockee_migration_nonce', 'nonce');

    if (!current_user_can('manage_options')) {
      wp_send_json_error(__('You do not have permission to launch migration.', 'lockee'));
      return;
    }

    $migration_status = get_option(self::MIGRATION_STATUS_KEY, self::STATUS_NEEDED);

    $progress = $this->get_ajax_response();

    if ($progress) {
      wp_send_json_success($progress);
      return;
    }

    if ($migration_status === self::STATUS_FINISHED) {
      wp_send_json_success(array(
        'status' => 'completed',
        'message' => __('Migration completed successfully.', 'lockee')
      ));
      return;
    }

    if ($migration_status === self::STATUS_NEEDED) {
      wp_send_json_success(array(
        'status' => 'not_started',
        'message' => __('Migration not started yet.', 'lockee')
      ));
      return;
    }

    wp_send_json_success(array(
      'status' => 'progress',
      'message' => __('Migration in progress...', 'lockee')
    ));
  }

  private function update_ajax_response($type, $status, $current, $total)
  {
    update_option(self::MIGRATION_PROGRESS_KEY, array(
      'type' => $type,
      'status' => $status,
      'current' => $current,
      'total' => $total
    ));
  }

  /**
   *  Get the current AJAX response for migration progress
   */
  private function get_ajax_response()
  {
    $progress = get_option(self::MIGRATION_PROGRESS_KEY, array());

    $messages = array(
      'migration_start' => __('Starting migration...', 'lockee'),
      'migration_progress' => __('Converting old locks (%d/%d)', 'lockee'),
      'migration_completed' => __('Migration of old lock completed successfully.', 'lockee'),
      'restoration_start' => __('Starting restoration...', 'lockee'),
      'restoration_progress' => __('Restorating old locks (%d/%d)', 'lockee'),
      'restoration_completed' =>  __('Restoration of old lock completed successfully.', 'lockee')
    );

    if ($progress) {
      $progress['message'] = sprintf($messages[$progress['type'] . '_' . $progress['status']] ?? __('In progress...', 'lockee'), $progress['current'], $progress['total']);
      return $progress;
    }

    return $progress;
  }

  /**
   * Check if migration is needed
   */
  public function check_if_migration_needed()
  {
    return $this->count_posts_to_migrate() > 0;
  }

  /**
   * Count the number of posts to migrate
   */
  public function count_posts_to_migrate()
  {
    global $wpdb;

    $count = $wpdb->get_var(
      "SELECT COUNT(DISTINCT p.ID)
       FROM {$wpdb->posts} p
       INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id AND pm.meta_key = 'lockee_code'
       WHERE p.post_type IN ('post', 'page')"
    );

    return (int)$count;
  }

  /**
   * Run the migration if needed
   */
  public function maybe_run_migration()
  {
    if (!isset($_POST['action']) || ($_POST['action'] !== 'lockee_migration' && $_POST['action'] !== 'lockee_restoration')) {
      return;
    }

    if (!check_admin_referer('lockee_migration_nonce', 'lockee_migration_nonce')) {
      wp_send_json_error(__('Unauthorized action.', 'lockee'));
      return;
    }

    if (!current_user_can('manage_options')) {
      wp_send_json_error(__('You do not have permission to launch migration.', 'lockee'));
      return;
    }

    if (!$this->acquire_migration_lock()) {
      wp_send_json_error(__('A migration is already in progress. Please wait.', 'lockee'));
      return;
    }

    if ($_POST['action'] === 'lockee_migration') {

      $migration_status = $this->count_posts_to_migrate();

      if ($migration_status === 0) {
        $this->release_migration_lock();
        wp_send_json_error(__('No migration needed.', 'lockee'));
        return;
      }

      update_option(self::MIGRATION_STATUS_KEY, self::STATUS_LAUNCHED);
      $this->update_ajax_response('migration', 'start', 0, 0);
      $this->update_old_content();
    } else if ($_POST['action'] === 'lockee_restoration') {
      $log_file = isset($_POST['log_file']) ? sanitize_text_field($_POST['log_file']) : '';
      if (empty($log_file)) {
        $this->release_migration_lock();
        wp_send_json_error(__('No log file specified for restoration.', 'lockee'));
        return;
      }
      update_option(self::MIGRATION_STATUS_KEY, self::STATUS_LAUNCHED);
      $this->update_ajax_response('restoration', 'start', 0, 0);
      $this->rollback_migration($log_file);
    }
  }

  /**
   *  Add an artificial delay for debugging purposes
   */
  private function add_artificial_delay()
  {
    if (self::DEBUG_AJAX) {
      usleep(500000); // 500ms
    }
  }

  /**
   * Cleanup migration transients and options
   */
  private function cleanup_migration_transients()
  {
    delete_transient(self::MIGRATION_LOCK_KEY);
    delete_option(self::MIGRATION_PROGRESS_KEY);
  }

  /**
   * Update old content to new format
   */
  private function update_old_content()
  {
    global $wpdb;

    $posts = $wpdb->get_results(
      "SELECT DISTINCT p.ID, p.post_title, p.post_content,
                MAX(CASE WHEN pm.meta_key = 'lockee_code' THEN pm.meta_value END) as lockee_code,
                MAX(CASE WHEN pm.meta_key = 'lockee_type' THEN pm.meta_value END) as lockee_type,
                MAX(CASE WHEN pm.meta_key = 'lockee_options' THEN pm.meta_value END) as lockee_options,
                MAX(CASE WHEN pm.meta_key = 'lockee_content' THEN pm.meta_value END) as lockee_content
         FROM {$wpdb->posts} p
         INNER JOIN {$wpdb->postmeta} pm ON p.ID = pm.post_id 
         WHERE (p.post_type = 'post' OR p.post_type = 'page')
         AND pm.meta_key IN ('lockee_code', 'lockee_type', 'lockee_options', 'lockee_content')
         GROUP BY p.ID
         HAVING MAX(CASE WHEN pm.meta_key = 'lockee_code' THEN pm.meta_value END) IS NOT NULL"
    );

    $this->update_remaining_posts($posts);
    update_option(self::MIGRATION_STATUS_KEY, self::STATUS_FINISHED);
    $this->update_ajax_response('migration', 'completed', 0, 0);
    $this->cleanup_migration_transients();
  }

  /**
   * Update remaining posts to new format
   */
  private function update_remaining_posts($posts)
  {
    $total = count($posts) ?? 0;
    $current = 0;
    $batch_size = 10;
    $operations = [];

    $this->update_ajax_response('migration', 'progress', $current, $total);

    if ($total == 0) {
      return;
    }

    $batches = array_chunk($posts, $batch_size);

    foreach ($batches as $batch) {
      foreach ($batch as $post) {
        if (!empty($post->lockee_code)) {
          $lockee_content = $post->lockee_content ?? '';
          $new_lock_id = wp_insert_post(array(
            'post_title'   => 'Cadenas - ' . $post->post_title,
            'post_type'    => 'lockee_lock',
            'post_status'  => 'publish',
            'post_content' => $lockee_content,
          ));

          if ($new_lock_id) {

            $block = '<!-- wp:lockee/lock-block {"lockId":"' . $new_lock_id . '"} /-->';
            $new_content = $post->post_content . "\n" . $block;

            wp_update_post([
              'ID' => $post->ID,
              'post_content' => $new_content,
            ]);

            $meta_updates = $this->update_lock_type_and_options($post->lockee_type, $post->lockee_code, $post->lockee_options);
            $this->move_meta_keys($post->ID, $new_lock_id);
            $this->update_many_meta($new_lock_id, $meta_updates);

            $operations[] = array(
              'old_id' => $post->ID,
              'new_id' => $new_lock_id,
              'lockee_type' => $meta_updates['lockee_type'],
              'lockee_code' => $meta_updates['lockee_code'],
              'lockee_options' => $meta_updates['lockee_options'],
              'lockee_content' => $post->lockee_content ?? ''
            );
          }
        }
        $this->replace_olds_by_new($post->ID, $new_lock_id);
        $current++;
        $this->add_artificial_delay();
        $this->update_ajax_response('migration', 'progress', $current, $total);
      }
    }
    $this->log_migration_action($operations);
    $this->update_ajax_response('migration', 'completed', $current, $total);
  }

  /**
   * Rollback a migration based on the log file
   */
  private function rollback_migration($log_file)
  {
    $log_path = plugin_dir_path(__DIR__) . 'logs/' . sanitize_file_name($log_file);
    if (!file_exists($log_path)) {
      return false;
    }
    $log_data = json_decode(file_get_contents($log_path), true);
    if (!$log_data || !is_array($log_data)) {
      return false;
    }

    if (!isset($log_data['status']) || $log_data['status'] !== 'migrated') {
      return false;
    }

    $elements = $log_data['elements'] ?? [];

    $total = count($elements) ?? 0;
    $current = 0;
    $batch_size = 10;

    $this->update_ajax_response('restoration', 'progress', $current, $total);

    if ($total == 0) {
      return;
    }

    $batches = array_chunk($elements, $batch_size);

    foreach ($batches as $batch) {
      foreach ($batch as $entry) {
        $new_post_found = false;
        if (empty($entry['old_id'])) {
          continue;
        }
        if (!empty($entry['new_id'])) {
          $new_post = get_post($entry['new_id']);
          if ($new_post instanceof WP_Post) {
            $new_post_found = true;
            $this->move_meta_keys($entry['new_id'], $entry['old_id']);
            $old_content = $new_post->post_content;
            wp_delete_post($entry['new_id'], true);
          }
        }

        if (!$new_post_found) {
          update_post_meta($entry['old_id'], 'lockee_type', $entry['lockee_type']);
          update_post_meta($entry['old_id'], 'lockee_code', $entry['lockee_code']);
          update_post_meta($entry['old_id'], 'lockee_options', $entry['lockee_options']);

          $old_content = $entry['lockee_content'] ?? '';
        }

        update_post_meta($entry['old_id'], 'lockee_content', $old_content);

        $old_post = get_post($entry['old_id']);
        $content = $old_post->post_content;

        $content = preg_replace(
          '/<!-- wp:lockee\/lock-block\s+(\{.*?"lockId":"' . preg_quote($entry['new_id'], '/') . '".*?\})\s*\/-->/',
          '',
          $content
        );

        wp_update_post([
          'ID' => $entry['old_id'],
          'post_content' => $content,
        ]);

        $this->replace_olds_by_new($entry['new_id'], $entry['old_id'], true);
        $current++;
        $this->add_artificial_delay();
        $this->update_ajax_response('restoration', 'progress', $current, $total);
      }
    }
    update_option(self::MIGRATION_STATUS_KEY, self::STATUS_FINISHED);
    $this->update_ajax_response('restoration', 'completed', $current, $total);
    $this->cleanup_migration_transients();
    $newlogname = str_replace('.json', '_restored.json', $log_path);
    rename($log_path, $newlogname);
    $log_data['status'] = 'restored';
    file_put_contents($newlogname, json_encode($log_data, JSON_PRETTY_PRINT) . PHP_EOL, FILE_APPEND);
  }

  /**
   * Update lock type and options based on the old format
   */
  private function update_lock_type_and_options($lock_type, $lock_code, $lock_options)
  {
    require_once plugin_dir_path(__FILE__) . 'class-lockee-utils.php';
    $modified = Lockee_Utils::process_old_type_and_options($lock_type, $lock_options);
    $type = $modified['type'];
    $options = $modified['options'];
    $code = $lock_code;

    return array(
      'lockee_code' => $code,
      'lockee_type' => $type,
      'lockee_options' => $options
    );
  }

  /**
   * Add multiple meta values for a post
   */
  private function update_many_meta($post_id, $meta_updates)
  {
    foreach ($meta_updates as $key => $value) {
      update_post_meta($post_id, $key, $value);
    }
  }

  /**
   * Move meta values from old post to new post
   */
  private function move_meta_keys($old_post_id, $new_post_id)
  {
    global $wpdb;
    $wpdb->query(
      $wpdb->prepare(
        "DELETE FROM {$wpdb->postmeta} WHERE post_id = %d AND meta_key LIKE %s",
        $new_post_id,
        'lockee\_%'
      )
    );

    $wpdb->query(
      $wpdb->prepare(
        "UPDATE {$wpdb->postmeta} SET post_id = %d WHERE post_id = %d AND meta_key LIKE %s",
        $new_post_id,
        $old_post_id,
        'lockee\_%'
      )
    );
  }

  /**
   * Replace old lock shortcodes with new ones in post content
   */
  private function replace_olds_by_new($old_id, $new_id, $withBlock = false)
  {
    global $wpdb;
    if (empty($old_id) || empty($new_id)) {
      return;
    }
    $search1 = '[lockee id="' . $old_id . '"]';
    $search2 = "[lockee id='" . $old_id . "']";
    $search3 = '[lockee id=' . $old_id . ']';
    $replace = '[lockee id=' . $new_id . ']';

    $replaces = [
      ['search' => $search1, 'replace' => $replace],
      ['search' => $search2, 'replace' => $replace],
      ['search' => $search3, 'replace' => $replace],
    ];
    $where = [
      '%' . $search1 . '%',
      '%' . $search2 . '%',
      '%' . $search3 . '%',
    ];

    if ($withBlock) {
      $block_pattern = '<!-- wp:lockee/lock-block {"lockId":"' . $old_id . '"} /-->';
      $replaces[] = ['search' => $block_pattern, 'replace' => $replace];
      $where[] = '%' . $block_pattern . '%';
    }

    $set = 'post_content';
    foreach ($replaces as $r) {
      $set = "REPLACE($set, %s, %s)";
    }
    $sql = "UPDATE {$wpdb->posts} SET post_content = $set WHERE " . implode(' OR post_content LIKE ', array_fill(0, count($where), '%s'));

    $params = [];
    foreach ($replaces as $r) {
      $params[] = $r['search'];
      $params[] = $r['replace'];
    }
    $params = array_merge($params, $where);

    $wpdb->query($wpdb->prepare($sql, ...$params));
  }

  /**
   * Generate a random token
   */
  private function generate_token($length = 32, $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
  {
    $randomString = '';
    $charactersLength = strlen($characters);
    for ($i = 0; $i < $length; $i++) {
      $randomString .= $characters[random_int(0, $charactersLength - 1)];
    }
    return $randomString;
  }

  /**
   * Log migration actions
   */
  private function log_migration_action($data)
  {
    $log_dir = plugin_dir_path(__DIR__) . 'logs/';
    $token = $this->generate_token();
    $size = sizeof($data);
    $time = time();
    if (!file_exists($log_dir)) {
      mkdir($log_dir, 0755, true);
    }
    $jsonData = [
      'date' => date('Y-m-d H:i:s', $time),
      'size' => $size,
      'hash' => $token,
      'status' => 'migrated',
      'elements' => $data
    ];
    $log_file = $log_dir . 'migration_' . date('Ymd-His', $time) . '_' . $size . '_' . $token . '.json';
    file_put_contents($log_file, json_encode($jsonData, JSON_PRETTY_PRINT) . PHP_EOL, FILE_APPEND);
  }

  /**
   * Delete a log file
   */
  private function delete_log_file()
  {
    if ($_POST && $_POST['action'] === 'lockee_delete_log') {
      $log_file = isset($_POST['log_file']) ? sanitize_text_field($_POST['log_file']) : '';
      if (empty($log_file)) {
        add_settings_error('lockee_messages', 'lockee_migration_process', __('No log file specified for deletion.', 'lockee'), 'error');
        return;
      }

      $log_path = plugin_dir_path(__DIR__) . 'logs/' . sanitize_file_name($log_file);
      if (!file_exists($log_path)) {
        add_settings_error('lockee_messages', 'lockee_migration_process', __('Log file does not exist.', 'lockee'), 'error');
        return;
      }

      if (unlink($log_path)) {
        add_settings_error('lockee_messages', 'lockee_migration_process', __('Log file deleted successfully.', 'lockee'), 'updated');
      } else {
        add_settings_error('lockee_messages', 'lockee_migration_process', __('Failed to delete log file.', 'lockee'), 'error');
      }
      return;
    }
  }

  /**
   * Add CSS styles for the migration page
   */
  private function add_css_styles()
  {
    wp_add_inline_style('wp-admin', '
      .progress-bar {
        background-color: #f0f0f1;
        border: solid 1px #CCC;
        border-radius: 4px;
        height: 20px;
        margin: 10px 0;
        overflow: hidden;
        position: relative;
        width: 100%;
      }
      .progress-bar-fill {
        background-color: #2271b1;
        height: 100%;
        transition: width 0.3s ease-in-out;
        width: 0;
      }
      .progress-bar-text {
        color: #1d2327;
        font-size: 12px;
        font-weight: 600;
        left: 50%;
        position: absolute;
        top: 50%;
        transform: translate(-50%, -50%);
        text-shadow: 0 0 2px #fff;
      }
      .progress-message {
        color: #1d2327;
        font-size: 13px;
        margin-top: 5px;
      }
      .infobar {
        background: #f9f9f9;
        padding: 10px;
        border: 1px solid #ddd;
        border-radius: 4px;
        text-align: center;
      }
      .migration-log-list {
        display:flex;
        gap:1rem;
        flex-wrap:wrap;
        align-items:center;
        padding:0.5rem;
      }
      .migration-log-list:nth-child(even) {
        background-color: #EFEFEF;
      }
    ');
  }
}
