<?php

namespace Yuvayana\AcadlixImporter\REST\Admin;

use WP_Error;
use WP_REST_Server;

use Yuvayana\AcadlixImporter\Helper\Helper;
use Yuvayana\AcadlixImporter\Models\ImporterSync;
use Yuvayana\AcadlixImporter\Models\WpProQuizCategory;
use Yuvayana\AcadlixImporter\Models\WpProQuizMaster;
use Yuvayana\AcadlixImporter\Models\WpProQuizPrerequisite;
use Yuvayana\AcadlixImporter\Models\WpProQuizQuestion;
use Yuvayana\AcadlixImporter\Models\WpProQuizStatisticRef;
use Yuvayana\AcadlixImporter\Models\WpProQuizToplist;

defined('ABSPATH') || exit();

class AdminWpProQuizController
{

  protected $namespace = 'acadlix-importer/v1';
  protected $base = 'admin-wpproquiz';

  public function register_routes()
  {
    register_rest_route(
      $this->namespace,
      '/' . $this->base . '/post-import-category',
      [
        [
          'methods' => WP_REST_Server::EDITABLE,
          'callback' => [$this, 'post_import_category'],
          'permission_callback' => [$this, 'check_permission'],
        ],
      ]
    );

    register_rest_route(
      $this->namespace,
      '/' . $this->base . '/post-import-master',
      [
        [
          'methods' => WP_REST_Server::EDITABLE,
          'callback' => [$this, 'post_import_master'],
          'permission_callback' => [$this, 'check_permission'],
        ],
      ]
    );

    register_rest_route(
      $this->namespace,
      '/' . $this->base . '/post-import-question',
      [
        [
          'methods' => WP_REST_Server::EDITABLE,
          'callback' => [$this, 'post_import_question'],
          'permission_callback' => [$this, 'check_permission'],
        ],
      ]
    );


    register_rest_route(
      $this->namespace,
      '/' . $this->base . '/post-import-prerequisite',
      [
        [
          'methods' => WP_REST_Server::EDITABLE,
          'callback' => [$this, 'post_import_prerequisite'],
          'permission_callback' => function () {
            if (!function_exists('acadlix') && !acadlix()->pro) {
              return false;
            }
            return true;
          },
        ],
      ]
    );

    register_rest_route(
      $this->namespace,
      '/' . $this->base . '/post-import-statistic',
      [
        [
          'methods' => WP_REST_Server::EDITABLE,
          'callback' => [$this, 'post_import_statistic'],
          'permission_callback' => [$this, 'check_permission'],
        ],
      ]
    );

    register_rest_route(
      $this->namespace,
      '/' . $this->base . '/post-import-statistic-ref',
      [
        [
          'methods' => WP_REST_Server::EDITABLE,
          'callback' => [$this, 'post_import_statistic_ref'],
          'permission_callback' => [$this, 'check_permission'],
        ],
      ]
    );

    register_rest_route(
      $this->namespace,
      '/' . $this->base . '/post-import-toplist',
      [
        [
          'methods' => WP_REST_Server::EDITABLE,
          'callback' => [$this, 'post_import_toplist'],
          'permission_callback' => [$this, 'check_permission'],
        ],
      ]
    );

    register_rest_route(
      $this->namespace,
      '/' . $this->base . '/post-import-post',
      [
        [
          'methods' => WP_REST_Server::EDITABLE,
          'callback' => [$this, 'post_import_post'],
          'permission_callback' => [$this, 'check_permission'],
        ],
      ]
    );

    register_rest_route(
      $this->namespace,
      '/' . $this->base . '/post-import-reset',
      [
        [
          'methods' => WP_REST_Server::EDITABLE,
          'callback' => [$this, 'post_import_reset'],
          'permission_callback' => [$this, 'check_permission'],
        ],
      ]
    );
  }

  public function post_import_category($request)
  {
    $res = [];
    $pageSize = $request->get_param('pageSize');
    $completedSize = $request->get_param('completedSize');

    $category_count = WpProQuizCategory::count();
    $importer_sync_category_count = ImporterSync::ofCategory()->ofWpProQuiz()->count();
    Helper::instance()->acadlix_importer_update_option("acadlix_importer_category_show", "yes");

    // check if category already imported
    if ($category_count == $importer_sync_category_count) {
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_category_completed", "yes");
      $res = [
        'completed' => true,
        'completedSize' => $importer_sync_category_count
      ];
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_category_completed_size", $res['completedSize']);
      return rest_ensure_response($res);
    }
    // if not, import category
    $categories = WpProQuizCategory::skip($completedSize)->take($pageSize)->get();
    if ($categories->count() > 0) {
      foreach ($categories as $category) {
        $meta_value = '';
        $new_id = 0;
        $importer_sync = ImporterSync::ofCategory()->ofWpProQuiz()->where('old_id', $category->category_id)->first();
        if (!$importer_sync) {
          if ($category->type == 'QUIZ') {
            $meta_value = 'quiz';
            $new_category = acadlix()->model()->category()->create(["category_name" => $category->category_name]);
            if ($new_category) {
              $new_id = $new_category['term_id'];
            }
          }
          if ($category->type == 'QUESTION') {
            $meta_value = 'question';
            $subject = acadlix()->model()->subject()->create(["subject_name" => $category->category_name]);
            if ($subject) {
              $new_id = $subject->id;
            }
          }

          // create sync
          ImporterSync::create([
            'type' => 'category',
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key 
            'meta_key' => 'category_type',
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
            'meta_value' => $meta_value,
            'old_id' => $category->category_id,
            'new_id' => $new_id,
            'from' => ImporterSync::FROM_WP_PRO_QUIZ,
          ]);
        }
      }
    }

    if ($categories->count() < $pageSize) {
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_category_completed", "yes");
      $res = [
        'completed' => true,
        'completedSize' => $completedSize + $categories->count()
      ];
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_category_completed_size", $res['completedSize']);
      return rest_ensure_response($res);
    }

    Helper::instance()->acadlix_importer_update_option("acadlix_importer_category_completed", "no");
    $res = [
      'completed' => false,
      'completedSize' => $pageSize + $completedSize
    ];
    Helper::instance()->acadlix_importer_update_option("acadlix_importer_category_completed_size", $res['completedSize']);
    return rest_ensure_response($res);
  }

  public function post_import_master($request)
  {
    $res = [];
    $pageSize = $request->get_param('pageSize');
    $completedSize = $request->get_param('completedSize');

    $master_count = WpProQuizMaster::count();
    $importer_sync_master_count = ImporterSync::ofMaster()->ofWpProQuiz()->count();
    Helper::instance()->acadlix_importer_update_option("acadlix_importer_master_show", "yes");

    // check if master already imported
    if ($master_count == $importer_sync_master_count) {
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_master_completed", "yes");
      $res = [
        'completed' => true,
        'completedSize' => $importer_sync_master_count
      ];
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_master_completed_size", $res['completedSize']);
      return rest_ensure_response($res);
    }
    // if not, import master
    $masters = WpProQuizMaster::skip($completedSize)->take($pageSize)->get();
    if ($masters->count() > 0) {
      foreach ($masters as $master) {
        $importer_sync = ImporterSync::ofMaster()->ofWpProQuiz()->where('old_id', $master->id)->first();
        if (!$importer_sync) {
          $language_id = (int) get_option('default_term_acadlix_quiz_language', 0);
          $mode = ["normal", "normal", "check_and_continue", "question_below_each_other"];
          $display_result = ["do_not_display", "below_the_result", "in_the_button"];
          $r = [
            'Wp-Pro-Quiz' => 'Acadlix',
            '$categories' => 'subjects',
          ];
          $meta = [
            'mode' => $mode[$master->quiz_modus] ?? "normal",
            'advance_mode_type' => "advance_panel",
            'start_date' => "",
            'end_date' => "",
            'multi_language' => false,
            'quiz_settings' => [
              "enable_back_button" => $master->quiz_modus == 1 ? true : false,
              "enable_check_on_option_selected" => false,
              "skip_question" => $master->skip_question_disabled ? false : true,
              "auto_check" => false,
              "question_per_page" => $master->questions_per_page ?? 10,
              "hide_quiz_title" => $master->title_hidden ? true : false,
              "hide_restart_button" => $master->btn_restart_quiz_hidden ? true : false,
              "show_clear_response_button" => false,
              "enable_check_button" => $master->quiz_modus == 2 ? true : false,
              "quiz_timing_type" => "full_quiz_time",
              "quiz_time" => $master->time_limit ?? 0,
              "show_review_button" => $master->show_review_question ? true : false,
              "start_button_text" => "Start Quiz",
              "auto_start" => $master->autostart ? true : false,
              "show_finish_button" => false,
              "enable_login_register" => $master->start_only_registered_user ? true : false,
              "per_user_allowed_attempt" => $master->quiz_run_once ? $master->quiz_run_once_number : 0,
              "save_statistic" => $master->statistics_on ? true : false,
              "statistic_ip_lock" => $master->statistics_ip_lock ?? 0,
              "save_statistic_number_of_times" => 0,
              "show_only_specific_number_of_questions" => $master->show_max_question ? true : false,
              "specific_number_of_questions" => $master->show_max_question ? $master->show_max_question_value : 0,
              "enable_selectable_questions_rule" => false,
              "enable_inline_answer_options_layout" => false,
              "options_per_row" => 2,
              "scientific_calculator" => false,
              "result_feedback_by_ai" => false,
              "result_feedback_additional_prompt" => "",
              // question options
              "show_marks" => $master->show_points ? true : false,
              "display_subject" => $master->show_category ? true : false,
              "answer_bullet" => $master->numbered_answer ? true : false,
              "answer_bullet_type" => "numeric",
              "show_difficulty_level" => false,
              "random_question" => $master->question_random ? true : false,
              "random_option" => $master->answer_random ? true : false,
              "do_not_randomize_last_option" => false,
              "question_overview" => $master->show_review_question ? true : false,
              "hide_question_numbering" => $master->hide_question_numbering ? true : false,
              "sort_by_subject" => $master->sort_categories ? true : false,
              "attempt_and_move_forward" => false,
              "force_user_to_answer_each_question" => $master->forcing_question_solve ? true : false,
              "disable_hint" => false,
              // result options
              "hide_result" => false,
              "hide_negative_marks" => false,
              "hide_quiz_time" => $master->hide_result_quiz_time ? true : false,
              "show_speed" => false,
              "show_percentile" => false,
              "show_accuracy" => false,
              "show_average_score" => $master->show_average_result ? true : false,
              "show_subject_wise_analysis" => $master->show_category_score ? true : false,
              "subject_wise_text" => "Subject Wise Result",
              "hide_subject_wise_marks" => false,
              "show_marks_distribution" => false,
              "show_status_based_on_min_percent" => false,
              "minimum_percent_to_pass" => 0,
              "hide_answer_sheet" => $master->btn_view_question_hidden ? true : false,
              "show_per_question_time" => false,
              "leaderboard" => $master->toplist_activated ? true : false,
              "show_rank" => false,
              "result_comparision_with_topper" => false,
              "leaderboard_total_number_of_entries" => $master->toplist_data['toplistDataShowLimit'] ?? 0,
              "leaderboard_user_can_apply_multiple_times" => $master->toplist_data['toplistDataAddMultiple'] ? true : false,
              "leaderboard_apply_multiple_number_of_times" => 0,
              "display_leaderboard_in_quiz_result" => $master->toplist_data['toplistDataShowIn'] ? $display_result[$master->toplist_data['toplistDataShowIn']] : "do_not_display",
              "percent_based_result_text" => $master->result_grade_enabled ? true : false,
              "result_text" => $master->result_text,
              "admin_email_notification" => $master->email_notification > 0 ? true : false,
              "admin_to" => $master->admin_email["to"] ?? "",
              "admin_from" => $master->admin_email["from"] ?? "",
              "admin_subject" => $master->admin_email["subject"] ? str_replace(array_keys($r), $r, $master->admin_email["subject"]) : "",
              "admin_message" => $master->admin_email["message"] ? str_replace(array_keys($r), $r, $master->admin_email["message"]) : "",
              "student_email_notification" => $master->user_email_notification ? true : false,
              "student_to" => "",
              "student_from" => $master->user_email["from"] ?? "",
              "student_subject" => $master->user_email["subject"] ? str_replace(array_keys($r), $r, $master->user_email["subject"]) : "",
              "student_message" => $master->user_email["message"] ? str_replace(array_keys($r), $r, $master->user_email["message"]) : "",
              "enable_prerequisite" => $master->prerequisite ? true : false,
              "subject_wise_question" => false,
            ],
            'default_language_id' => $language_id,
            'language_data' => [
              [
                'language_id' => $language_id,
                'default' => true,
                'selected' => true,
                'instruction1' => "",
                'instruction2' => "",
                'term_and_condition_text' => "",
                'term_and_condition_warning_text' => "",
              ]
            ],
          ];
          $meta = !empty($meta) && is_array($meta)
            ? acadlix()->helper()->cpt()->acadlix_add_prefix_meta_keys($meta, 'quiz')
            : [];

          $quizId = acadlix()->model()->quiz()->insertQuiz([
            'post_title' => sanitize_text_field($master->name ?? ""),
            'post_content' => wp_kses_post($master->text ?? ""),
          ], $meta);

          if (is_wp_error($quizId)) {
            return new WP_Error(
              'quiz_creation_failed',
              __('Failed to create the quiz.', 'acadlix-importer'),
              ['status' => 500, 'error' => $quizId->get_error_message()]
            );
          }

          // add shortcode
          acadlix()->model()->quizShortcode()->create([
            'quiz_id' => $quizId
          ]);

          // handle category
          if ($master->category_id > 0) {
            $category = ImporterSync::ofCategory()
              ->OfQuizCategory()
              ->where('old_id', $master->category_id)
              ->first();
            if ($category) {
              $result = acadlix()->model()->quiz()->assignCategory($quizId, $category->new_id);
              if (is_wp_error($result)) {
                return new WP_Error(
                  'category_assign_creation_failed',
                  __('Cannot assign category to quiz.', 'acadlix-importer'),
                  ['status' => 500]
                );
              }
            }
          }

          $result = acadlix()->model()->quiz()->assignLanguage($quizId, $language_id);
          if (is_wp_error($result)) {
            return new WP_Error(
              'language_assign_creation_failed',
              __('Cannot assign language to quiz.', 'acadlix-importer'),
              ['status' => 500]
            );
          }
          // create sync
          ImporterSync::create([
            'type' => 'master',
            'old_id' => $master->id,
            'new_id' => $quizId,
            'from' => ImporterSync::FROM_WP_PRO_QUIZ,
          ]);
        }
      }
    }

    if ($masters->count() < $pageSize) {
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_master_completed", "yes");
      $res = [
        'completed' => true,
        'completedSize' => $completedSize + $masters->count()
      ];
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_master_completed_size", $res['completedSize']);
      return rest_ensure_response($res);
    }

    Helper::instance()->acadlix_importer_update_option("acadlix_importer_master_completed", "no");
    $res = [
      'completed' => false,
      'completedSize' => $pageSize + $completedSize
    ];
    Helper::instance()->acadlix_importer_update_option("acadlix_importer_master_completed_size", $res['completedSize']);
    return rest_ensure_response($res);
  }

  public function post_import_question($request)
  {
    $res = [];
    $pageSize = $request->get_param('pageSize');
    $completedSize = $request->get_param('completedSize');

    $question_count = WpProQuizQuestion::count();
    $importer_sync_question_count = ImporterSync::ofQuestion()->ofWpProQuiz()->count();
    Helper::instance()->acadlix_importer_update_option("acadlix_importer_question_show", "yes");

    // check if question already imported
    if ($question_count == $importer_sync_question_count) {
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_question_completed", "yes");
      $res = [
        'completed' => true,
        'completedSize' => $importer_sync_question_count
      ];
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_question_completed_size", $res['completedSize']);
      return rest_ensure_response($res);
    }
    // if not, import question
    WpProQuizQuestion::where("answer_type", "assessment_answer")->orWhere("quiz_id", 0)->delete();

    $quizMappings = ImporterSync::ofMaster()->ofWpProQuiz()->pluck('new_id', 'old_id');
    $subjectMapping = ImporterSync::ofCategory()->ofWpProQuiz()
      ->ofQuestionCategory()
      ->pluck('new_id', 'old_id');

    $existingOldIds = ImporterSync::ofQuestion()->ofWpProQuiz()->pluck('old_id')->toArray();
    $questions = WpProQuizQuestion::skip($completedSize)->take($pageSize)->get();

    $questions = $questions->reject(function ($question) use ($existingOldIds) {
      return in_array($question->id, $existingOldIds);
    });
    if ($questions->isNotEmpty()) {
      $syncData = [];
      foreach ($questions as $question) {
        $newQuizId = $quizMappings[$question->quiz_id] ?? null;
        if (!$newQuizId)
          continue;
        $newSubjectId = $subjectMapping[$question->category_id] ?? 0;
        $language_id = (int) get_option('default_term_acadlix_quiz_language', 0);

        $question_data = [
          "quiz_id" => $newQuizId,
          "subject_id" => $newSubjectId,
          "online" => $question->online ?? 1,
          "sort" => $question->sort ?? 1,
          "title" => $question->title ?? "",
          "points" => $question->points ?? 1,
          "negative_points" => $question->negative_points ?? 0,
          "different_points_for_each_answer" => $question->answer_points_activated ? true : false,
          "different_incorrect_msg" => $question->correct_same_text ? false : true,
          "hint_enabled" => $question->tip_enabled ? true : false,
          "paragraph_enabled" => false,
          "answer_type" => $question->answer_type ?? "singleChoice",
          "meta" => null,
        ];
        $newQuestion = acadlix()->model()->question()->create($question_data);
        $language_data = [
          "language_id" => $language_id,
          "default" => true,
          "question" => $question->question ?? null,
          "correct_msg" => $question->correct_msg ?? null,
          "incorrect_msg" => $question->incorrect_msg ?? null,
          "hint_msg" => $question->tip_msg ?? null,
          "answer_data" => $question->answer_data ?? null,
          "meta" => null,
        ];
        $newQuestion->question_languages()->create($language_data);

        // create sync
        $syncData[] = [
          'type' => 'question',
          'old_id' => $question->id ?? 0,
          'new_id' => $newQuestion->id,
          'from' => ImporterSync::FROM_WP_PRO_QUIZ,
        ];
      }
      ImporterSync::insert($syncData);
    }

    if ($questions->count() < $pageSize) {
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_question_completed", "yes");
      $res = [
        'completed' => true,
        'completedSize' => $completedSize + $questions->count()
      ];
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_question_completed_size", $res['completedSize']);
      return rest_ensure_response($res);
    }

    Helper::instance()->acadlix_importer_update_option("acadlix_importer_question_completed", "no");
    $res = [
      'completed' => false,
      'completedSize' => $pageSize + $completedSize
    ];
    Helper::instance()->acadlix_importer_update_option("acadlix_importer_question_completed_size", $res['completedSize']);
    return rest_ensure_response($res);
  }

  public function post_import_prerequisite($request)
  {
    $res = [];
    $pageSize = $request->get_param('pageSize');
    $completedSize = $request->get_param('completedSize');

    $prerequisite_count = WpProQuizPrerequisite::count();
    $importer_sync_prerequisite_count = ImporterSync::ofPrerequisite()->ofWpProQuiz()->count();
    Helper::instance()->acadlix_importer_update_option("acadlix_importer_prerequisite_show", "yes");

    // check if prerequisite already imported
    if ($prerequisite_count == $importer_sync_prerequisite_count) {
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_prerequisite_completed", "yes");
      $res = [
        'completed' => true,
        'completedSize' => $importer_sync_prerequisite_count
      ];
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_prerequisite_completed_size", $res['completedSize']);
      return rest_ensure_response($res);
    }
    // if not, import prerequisite
    $prerequisites = WpProQuizPrerequisite::skip($completedSize)->take($pageSize)->get();
    if ($prerequisites->count() > 0) {
      foreach ($prerequisites as $prerequisite) {
        $importer_sync = ImporterSync::ofPrerequisite()->ofWpProQuiz()
          ->where('old_id', $prerequisite->prerequisite_quiz_id)
          ->where("meta_key", "quiz_id")
          ->where("meta_id", $prerequisite->quiz_id)
          ->first();
        if (!$importer_sync) {
          $prerequisite_quiz_id = ImporterSync::ofMaster()->ofWpProQuiz()
            ->where("old_id", $prerequisite->prerequisite_quiz_id)
            ->first()
            ->new_id;
          $quiz_id = ImporterSync::ofMaster()->ofWpProQuiz()
            ->where("old_id", $prerequisite->quiz_id)
            ->first()
            ->new_id;

          $prerequisite_data = [
            "type" => "quiz",
            "type_id" => $prerequisite_quiz_id,
            "prerequisite_type" => "quiz",
            "prerequisite_id" => $quiz_id,
          ];
          $newPrerequisite = acadlix()->model()->prerequisite()->create($prerequisite_data);
          // create sync
          ImporterSync::create([
            'type' => 'prerequisite',
            'old_id' => $prerequisite->prerequisite_quiz_id,
            'new_id' => $newPrerequisite->id,
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
            'meta_key' => "quiz_id",
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
            "meta_value" => $prerequisite->quiz_id,
            'from' => ImporterSync::FROM_WP_PRO_QUIZ,
          ]);
        }
      }
    }

    if ($prerequisites->count() < $pageSize) {
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_prerequisite_completed", "yes");
      $res = [
        'completed' => true,
        'completedSize' => $completedSize + $prerequisites->count()
      ];
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_prerequisite_completed_size", $res['completedSize']);
      return rest_ensure_response($res);
    }

    Helper::instance()->acadlix_importer_update_option("acadlix_importer_prerequisite_completed", "no");
    $res = [
      'completed' => false,
      'completedSize' => $pageSize + $completedSize
    ];
    Helper::instance()->acadlix_importer_update_option("acadlix_importer_prerequisite_completed_size", $res['completedSize']);
    return rest_ensure_response($res);
  }

  public function post_import_statistic_ref($request)
  {
    $res = [];
    $pageSize = $request->get_param('pageSize');
    $completedSize = $request->get_param('completedSize');

    // $statistic_ref_count = WpProQuizStatisticRef::count();
    // $importer_sync_statistic_ref_count = ImporterSync::ofStatisticRef()->count();
    Helper::instance()->acadlix_importer_update_option("acadlix_importer_statistic_ref_show", "yes");

    // check if statistic_ref already imported
    // if ($statistic_ref_count == $importer_sync_statistic_ref_count) {
    //     Helper::instance()->acadlix_importer_update_option("acadlix_importer_statistic_ref_completed", "yes");
    //     $res = [
    //         'completed' => true,
    //         'completedSize' => $importer_sync_statistic_ref_count
    //     ];
    //     Helper::instance()->acadlix_importer_update_option("acadlix_importer_statistic_ref_completed_size", $res['completedSize']);
    //     return rest_ensure_response($res);
    // }


    // Preload all quiz and question mappings into arrays for fast lookups
    $quizMappings = ImporterSync::ofMaster()->ofWpProQuiz()->pluck('new_id', 'old_id');
    $questionMappings = ImporterSync::ofQuestion()->ofWpProQuiz()->pluck('new_id', 'old_id');

    // // Use indexed query for existing old IDs
    $existingOldIds = ImporterSync::ofStatisticRef()->ofWpProQuiz()->select('old_id')->get()->keyBy('old_id');

    // // Fetch statistics ref records in batches
    $statisticRefs = WpProQuizStatisticRef::skip($completedSize)->take($pageSize)->get();

    // // Filter out already imported records using a hashmap for faster lookup
    $statisticRefs = $statisticRefs->reject(function ($statisticRef) use ($existingOldIds) {
      return isset($existingOldIds[$statisticRef->statistic_ref_id]);
    });

    if ($statisticRefs->isNotEmpty()) {
      // Prepare bulk insert data
      $statisticRefData = [];
      $syncData = [];

      foreach ($statisticRefs as $statisticRef) {
        $newQuizId = $quizMappings[$statisticRef->quiz_id] ?? null;
        if (!$newQuizId)
          continue;

        $accuracy = $statisticRef->getAccuracy();
        $points = $statisticRef->getPoints();
        $result = $statisticRef->getResult();

        $statisticRefData[] = [
          'quiz_id' => $newQuizId,
          'user_id' => $statisticRef->user_id ?? 0,
          'quiz_time' => $statisticRef->quiz_time ?? 0,
          'status' => 'Pass',
          'accuracy' => $accuracy,
          'points' => (float) $points,
          'result' => (float) $result,
        ];
      }
      // Bulk insert into acadlix_statistics_ref
      acadlix()->model()->statisticRef()->insert($statisticRefData);

      $insertedIds = acadlix()->model()->statisticRef()->latest('id')
        ->limit(count($statisticRefData))
        ->pluck('id')->toArray();
      $newStatisticRefs = acadlix()->model()->statisticRef()->whereIn('id', $insertedIds)
        ->orderBy('id', 'asc')
        ->get();
      foreach ($statisticRefs as $index => $statisticRef) {
        $newStatRefId = $newStatisticRefs[$index]->id ?? null;
        // $newStatRefId = $insertedIds[$index] ?? null;

        if (!$newStatRefId)
          continue;

        foreach ($statisticRef->statistics as $statistic) {
          $newQuestionId = $questionMappings[$statistic->question_id] ?? 0;
          $statisticData = [
            'statistic_ref_id' => $newStatRefId,
            'question_id' => $newQuestionId,
            'correct_count' => $statistic->correct_count,
            'incorrect_count' => $statistic->incorrect_count,
            'hint_count' => $statistic->hint_count,
            'solved_count' => $statistic->solved_count,
            'points' => $statistic->points,
            'negative_points' => 0,
            'question_time' => $statistic->question_time,
            'answer_data' => $statistic->answer_data ?? null,
            'attempted_at' => null,
            'is_evaluated' => true,
            'evaluated_by' => null,
            'evaluated_id' => null,
            'evaluation_remark' => null
          ];
          acadlix()->model()->statistic()->create($statisticData);
        }

        $syncData[] = [
          'type' => 'statistic_ref',
          'old_id' => $statisticRef->statistic_ref_id ?? 0,
          'new_id' => $newStatRefId,
          'from' => ImporterSync::FROM_WP_PRO_QUIZ,
        ];
      }

      // Bulk insert into acadlix_statistics and importer sync tables
      ImporterSync::insert($syncData);
    }

    if ($statisticRef === null || $statisticRef->count() < $pageSize) {
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_statistic_ref_completed", "yes");

      $res = [
        'completed' => true,
        'completedSize' => $completedSize + ($statisticRef === null ? 0 : $statisticRef->count())
      ];
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_statistic_ref_completed_size", $res['completedSize']);
      return rest_ensure_response($res);
    }

    Helper::instance()->acadlix_importer_update_option("acadlix_importer_statistic_ref_completed", "no");
    $res = [
      'completed' => false,
      'completedSize' => $pageSize + $completedSize
    ];
    Helper::instance()->acadlix_importer_update_option("acadlix_importer_statistic_ref_completed_size", $res['completedSize']);
    return rest_ensure_response($res);
  }

  public function post_import_statistic($request)
  {

  }

  public function post_import_toplist($request)
  {
    $res = [];
    $pageSize = $request->get_param('pageSize');
    $completedSize = $request->get_param('completedSize');

    $toplist_count = WpProQuizToplist::count();
    $importer_sync_toplist_count = ImporterSync::ofToplist()->ofWpProQuiz()->count();
    Helper::instance()->acadlix_importer_update_option("acadlix_importer_toplist_show", "yes");

    // check if toplist already imported
    if ($toplist_count == $importer_sync_toplist_count) {
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_toplist_completed", "yes");
      $res = [
        'completed' => true,
        'completedSize' => $importer_sync_toplist_count
      ];
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_toplist_completed_size", $res['completedSize']);
      return rest_ensure_response($res);
    }
    // if not, import toplist
    $quizMappings = ImporterSync::ofMaster()->ofWpProQuiz()->pluck('new_id', 'old_id');
    $existingOldIds = ImporterSync::ofToplist()->ofWpProQuiz()->pluck('old_id')->toArray();

    $toplists = WpProQuizToplist::skip($completedSize)->take($pageSize)->get();

    $toplists = $toplists->reject(function ($toplist) use ($existingOldIds) {
      return in_array($toplist->toplist_id, $existingOldIds);
    });
    if ($toplists->isNotEmpty()) {
      $toplistData = [];
      $syncData = [];
      foreach ($toplists as $toplist) {
        $newQuizId = $quizMappings[$toplist->quiz_id] ?? null;
        if (!$newQuizId)
          continue;

        $toplistData[] = [
          "quiz_id" => $newQuizId,
          "user_id" => $toplist->user_id ?? 0,
          "name" => $toplist->name ?? '',
          "email" => $toplist->email ?? '',
          "points" => (float) ($toplist->points ?? 0),
          "result" => (float) ($toplist->result ?? 0),
          "ip" => $toplist->ip ?? '',
          "quiz_time" => 0,
          "accuracy" => null,
          "status" => null
        ];

      }

      acadlix()->model()->toplist()->insert($toplistData);

      $insertedIds = acadlix()->model()->toplist()->latest('id')
        ->limit(count($toplistData))
        ->pluck('id')->toArray();
      $newToplists = acadlix()->model()->toplist()->whereIn('id', $insertedIds)
        ->orderBy('id', 'asc')
        ->get();

      foreach ($toplists as $index => $toplist) {
        $newToplistId = $newToplists[$index]->id ?? null;
        if (!$newToplistId)
          continue;

        $syncData[] = [
          'type' => 'toplist',
          'old_id' => $toplist->toplist_id ?? 0,
          'new_id' => $newToplistId,
          'from' => ImporterSync::FROM_WP_PRO_QUIZ,
        ];
      }

      ImporterSync::insert($syncData);
    }

    if ($toplists->count() < $pageSize) {
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_toplist_completed", "yes");
      $res = [
        'completed' => true,
        'completedSize' => $completedSize + $toplists->count()
      ];
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_toplist_completed_size", $res['completedSize']);
      return rest_ensure_response($res);
    }

    Helper::instance()->acadlix_importer_update_option("acadlix_importer_toplist_completed", "no");
    $res = [
      'completed' => false,
      'completedSize' => $pageSize + $completedSize
    ];
    Helper::instance()->acadlix_importer_update_option("acadlix_importer_toplist_completed_size", $res['completedSize']);
    return rest_ensure_response($res);
  }

  public function post_import_post($request)
  {
    $res = [];
    $pageSize = $request->get_param('pageSize');
    $completedSize = $request->get_param('completedSize');

    Helper::instance()->acadlix_importer_update_option("acadlix_importer_post_show", "yes");

    // if not, import post
    $posts = acadlix()->model()->wpPosts()->whereIn('post_type', ["post", "page"])->skip($completedSize)->take($pageSize)->get();
    if ($posts->count() > 0) {
      foreach ($posts as $post) {
        $importer_sync = ImporterSync::ofPost()->ofWpProQuiz()->where('old_id', $post->ID)->first();
        if (!$importer_sync) {
          $pattern = '/\[WpProQuiz (\d+)\]/';
          if (preg_match_all($pattern, $post->post_content, $matches)) {
            $matches = $matches[1];
            $post_content = $post->post_content;
            $post_excerpt = $post->post_excerpt;
            foreach ($matches as $match) {
              $quiz_id = $match;
              $new_quiz_id = ImporterSync::ofMaster()->ofWpProQuiz()->where("old_id", $quiz_id)->first()->new_id;
              $new_shortcode_id = acadlix()->model()->quizShortcode()->where('quiz_id', $new_quiz_id)->first()->id;
              $old_shortcode = "[WpProQuiz {$quiz_id}]";
              $new_shortcode = "[Acadlix_Quiz {$new_shortcode_id}]";

              // Replace the shortcode with the new one
              $post_content = str_replace($old_shortcode, $new_shortcode, $post_content);
              $post_excerpt = str_replace($old_shortcode, $new_shortcode, $post_excerpt);
            }
            $my_post = array(
              'ID' => $post->ID,
              'post_content' => $post_content,
              'post_excerpt' => $post_excerpt,
            );

            // Update the post into the database
            wp_update_post($my_post);
            // check post meta
            $meta_data = get_post_meta($post->ID);

            foreach ($meta_data as $meta_key => $meta_values) {
              foreach ($meta_values as $meta_value) {
                // Check if meta_value contains the old shortcode
                if (preg_match_all($pattern, $meta_value, $matches)) {
                  $matches = $matches[1];
                  $new_meta_value = $meta_value;
                  foreach ($matches as $match) {
                    $quiz_id = $match;
                    $new_quiz_id = ImporterSync::ofMaster()->ofWpProQuiz()->where("old_id", $quiz_id)->first()->new_id;
                    $new_shortcode_id = acadlix()->model()->quizShortcode()->where('quiz_id', $new_quiz_id)->first()->id;
                    $old_shortcode = "[WpProQuiz {$quiz_id}]";
                    $new_shortcode = "[Acadlix_Quiz {$new_shortcode_id}]";
                    $new_meta_value = str_replace($old_shortcode, $new_shortcode, $meta_value);
                  }
                  // Update meta value
                  update_post_meta($post->ID, $meta_key, $new_meta_value);
                }
              }
            }
            // create sync
            ImporterSync::create([
              'type' => 'post',
              'old_id' => $post->ID,
              'new_id' => $quiz_id,
              // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
              'meta_key' => "shortcode_type",
              // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
              'meta_value' => "quiz",
              'from' => ImporterSync::FROM_WP_PRO_QUIZ,
            ]);
          }
        }
      }
    }

    if ($posts->count() < $pageSize) {
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_post_completed", "yes");
      $res = [
        'completed' => true,
        'completedSize' => $completedSize + $posts->count()
      ];
      Helper::instance()->acadlix_importer_update_option("acadlix_importer_post_completed_size", $res['completedSize']);
      return rest_ensure_response($res);
    }

    Helper::instance()->acadlix_importer_update_option("acadlix_importer_post_completed", "no");
    $res = [
      'completed' => false,
      'completedSize' => $pageSize + $completedSize
    ];
    Helper::instance()->acadlix_importer_update_option("acadlix_importer_post_completed_size", $res['completedSize']);
    return rest_ensure_response($res);
  }

  public function post_import_reset($request)
  {
    $res = [];
    $pageSize = $request->get_param('pageSize');
    $completedSize = $request->get_param('completedSize');

    // ImporterSync::ofStatisticRef()->delete();

    // $statistic_refs = acadlix()->model()->statisticRef()->get()->each->delete();
    // Helper::instance()->acadlix_importer_update_option("acadlix_importer_statistic_ref_completed", "no");
    // $res = [
    //     'completed' => true,
    //     'completedSize' => $pageSize + $completedSize
    // ];
    // Helper::instance()->acadlix_importer_update_option("acadlix_importer_statistic_ref_completed_size", 0);
    // return rest_ensure_response($res);

    $importer_sync = ImporterSync::ofWpProQuiz()->skip($completedSize)->take($pageSize)->get();
    if ($importer_sync->count() > 0) {
      foreach ($importer_sync as $sync) {
        switch ($sync->type) {
          case "category":
            if ($sync->meta_key == "category_type" && $sync->meta_value == "quiz") {
              $category = acadlix()->model()->category()->find($sync->new_id);
              if ($category) {
                acadlix()->model()->category()->delete($sync->new_id);
              }
            }
            if ($sync->meta_key == "category_type" && $sync->meta_value == "question") {
              $subject = acadlix()->model()->subject()->find($sync->new_id);
              if ($subject) {
                $subject->delete();
              }
            }
            break;
          case "master":
            $quiz = acadlix()->model()->quiz()->ofQuiz()->find($sync->new_id);
            if ($quiz) {
              acadlix()->model()->quiz()->deleteQuiz($sync->new_id);
            }
            break;
          case "question":
            $question = acadlix()->model()->question()->find($sync->new_id);
            if ($question) {
              $question->delete();
            }
            break;
          case "prerequisite":
            $prerequisite = acadlix()->model()->prerequisite()->ofTypeQuiz()->find($sync->new_id);
            if ($prerequisite) {
              $prerequisite->delete();
            }
            break;
          case "statistic_ref":
            $statistic_ref = acadlix()->model()->statisticRef()->find($sync->new_id);
            if ($statistic_ref) {
              $statistic_ref->delete();
            }
            break;
          case "toplist":
            $toplist = acadlix()->model()->toplist()->find($sync->new_id);
            if ($toplist) {
              $toplist->delete();
            }
            break;
          case "post":
            // handle shortcode
            $post = acadlix()->model()->wpPosts()->find($sync->old_id);
            if ($post) {
              $importer_sync = ImporterSync::ofMaster()->ofWpProQuiz()->where("old_id", $sync->new_id)->first();
              if (!$importer_sync)
                continue 2;
              $new_shortcode_id = acadlix()->model()->quizShortcode()->where('quiz_id', $importer_sync->new_id)->first()->id;
              $shortcode = "[Acadlix_Quiz {$new_shortcode_id}]";
              $new_shortcode = "[WpProQuiz {$sync->new_id}]";

              // Replace the shortcode with the new one
              $post_content = str_replace($shortcode, $new_shortcode, $post->post_content);
              $post_excerpt = str_replace($shortcode, $new_shortcode, $post->post_excerpt);
              $my_post = array(
                'ID' => $post->ID,
                'post_content' => $post_content,
                'post_excerpt' => $post_excerpt,
              );

              // Update the post into the database
              wp_update_post($my_post);
              // check post meta
              $meta_data = get_post_meta($post->ID);

              foreach ($meta_data as $meta_key => $meta_values) {
                foreach ($meta_values as $meta_value) {
                  // Check if meta_value contains the old shortcode
                  if (strpos($meta_value, $shortcode) !== false) {
                    // Replace shortcode
                    $new_meta_value = str_replace($shortcode, $new_shortcode, $meta_value);

                    // Update meta value
                    update_post_meta($post->ID, $meta_key, $new_meta_value);
                  }
                }
              }
            }
            break;
          default:
            break;
        }
      }
    }

    if ($importer_sync->count() < $pageSize) {
      ImporterSync::ofWpProQuiz()->delete();

      $options = Helper::instance()->acadlix_importer_options();
      if (count($options) > 0) {
        foreach ($options as $key => $option) {
          Helper::instance()->acadlix_importer_update_option($key, $option);
        }
      }
      $res = [
        'completed' => true,
        'completedSize' => $completedSize + $importer_sync->count()
      ];
      return rest_ensure_response($res);
    }

    $res = [
      'completed' => false,
      'completedSize' => $pageSize + $completedSize
    ];

    return rest_ensure_response($res);
  }


  public function check_permission()
  {
    return true;
  }
}