<?php
if (!defined('ABSPATH')) {
  exit;
}

/**
 * Local review lifecycle and permanent Doctor feedback panel.
 *
 * Content is bundled with CAS. Optional CTA analytics use the existing CAS RM
 * event endpoint only when the separate analytics preference is enabled.
 */

if (!function_exists('custausu_community_feedback_is_it')) {
  function custausu_community_feedback_is_it(): bool {
    $locale = function_exists('get_user_locale')
      ? (string) get_user_locale()
      : (string) get_locale();

    return strpos(strtolower($locale), 'it') === 0;
  }
}

if (!function_exists('custausu_community_feedback_t')) {
  function custausu_community_feedback_t(string $en, string $it): string {
    return custausu_community_feedback_is_it() ? $it : $en;
  }
}

if (!function_exists('custausu_wporg_plugin_slug')) {
  function custausu_wporg_plugin_slug(): string {
    return 'custom-auth-suite';
  }
}

if (!function_exists('custausu_wporg_plugin_url')) {
  function custausu_wporg_plugin_url(): string {
    return 'https://wordpress.org/plugins/' . rawurlencode(custausu_wporg_plugin_slug()) . '/';
  }
}

if (!function_exists('custausu_wporg_support_url')) {
  function custausu_wporg_support_url(): string {
    return 'https://wordpress.org/support/plugin/' . rawurlencode(custausu_wporg_plugin_slug()) . '/';
  }
}

if (!function_exists('custausu_wporg_reviews_url')) {
  function custausu_wporg_reviews_url(): string {
    return 'https://wordpress.org/support/plugin/' . rawurlencode(custausu_wporg_plugin_slug()) . '/reviews/#new-post';
  }
}

if (!function_exists('custausu_community_feedback_allowed_redirect_hosts')) {
  function custausu_community_feedback_allowed_redirect_hosts(
    array $hosts,
    string $host
  ): array {
    if (
      $host === 'wordpress.org'
      && !in_array('wordpress.org', $hosts, true)
    ) {
      $hosts[] = 'wordpress.org';
    }

    return $hosts;
  }
}

if (!function_exists('custausu_community_feedback_redirect_to_wordpress_org')) {
  function custausu_community_feedback_redirect_to_wordpress_org(
    string $url
  ): void {
    add_filter(
      'allowed_redirect_hosts',
      'custausu_community_feedback_allowed_redirect_hosts',
      10,
      2
    );

    wp_safe_redirect($url);

    remove_filter(
      'allowed_redirect_hosts',
      'custausu_community_feedback_allowed_redirect_hosts',
      10
    );

    exit;
  }
}

if (!function_exists('custausu_community_feedback_plan')) {
  function custausu_community_feedback_plan(): string {
    $plan = defined('CUSTAUSU_BUILD_PACKAGE_PLAN')
      ? sanitize_key((string) CUSTAUSU_BUILD_PACKAGE_PLAN)
      : 'freemium';

    return in_array($plan, ['freemium', 'advanced', 'premium'], true)
      ? $plan
      : 'freemium';
  }
}

if (!function_exists('custausu_community_feedback_is_free')) {
  function custausu_community_feedback_is_free(): bool {
    return custausu_community_feedback_plan() === 'freemium';
  }
}

if (!function_exists('custausu_community_feedback_feature_url')) {
  function custausu_community_feedback_feature_url(string $lang = ''): string {
    $lang = sanitize_key($lang);

    if ($lang === '') {
      $lang = custausu_community_feedback_is_it() ? 'it' : 'en';
    }

    $base = $lang === 'it'
      ? 'https://customauthsuite.com/it/il-plugin/proponi-funzionalita/'
      : 'https://customauthsuite.com/plugin/feature-request/';

    return esc_url_raw(add_query_arg([
      'source' => 'custausu_doctor',
      'edition' => custausu_community_feedback_plan(),
      'lang' => $lang,
    ], $base));
  }
}

if (!function_exists('custausu_review_notice_state_meta_key')) {
  function custausu_review_notice_state_meta_key(): string {
    return 'custausu_review_notice_state';
  }
}

if (!function_exists('custausu_review_notice_started_option_name')) {
  function custausu_review_notice_started_option_name(): string {
    return 'custausu_review_notice_started_at';
  }
}

if (!function_exists('custausu_review_notice_campaign_key')) {
  function custausu_review_notice_campaign_key(string $version = ''): string {
    $version = trim($version !== '' ? $version : (defined('CUSTAUSU_VERSION') ? (string) CUSTAUSU_VERSION : ''));

    if ($version === '') {
      return '';
    }

    if (preg_match('/(?:^|[-._])(alpha|beta|rc|dev)(?:[-._0-9]|$)/i', $version)) {
      return '';
    }

    $numeric = preg_replace('/[^0-9.].*$/', '', $version);
    $numeric = is_string($numeric) ? trim($numeric, '.') : '';

    if ($numeric === '' || !preg_match('/^(\d+)\.(\d+)/', $numeric, $matches)) {
      return '';
    }

    if (version_compare($numeric, '1.0.0', '<')) {
      return 'pre-1.0';
    }

    return absint($matches[1]) . '.' . absint($matches[2]);
  }
}

if (!function_exists('custausu_review_notice_normalize_campaign_key')) {
  function custausu_review_notice_normalize_campaign_key(string $key): string {
    $key = strtolower(trim($key));

    return preg_match('/^(?:pre-1\.0|\d+\.\d+)$/', $key)
      ? $key
      : '';
  }
}

if (!function_exists('custausu_review_notice_normalize_state')) {
  function custausu_review_notice_normalize_state($state): array {
    $state = is_array($state) ? $state : [];

    $campaigns = [];
    foreach ((array) ($state['campaigns'] ?? []) as $key => $campaign) {
      $key = custausu_review_notice_normalize_campaign_key((string) $key);
      $campaign = is_array($campaign) ? $campaign : [];
      $status = sanitize_key((string) ($campaign['status'] ?? ''));

      if ($key === '' || !in_array($status, ['declined', 'review_clicked'], true)) {
        continue;
      }

      $campaigns[$key] = [
        'status' => $status,
        'updated_at' => absint($campaign['updated_at'] ?? 0),
      ];
    }

    return [
      'snoozed_until' => absint($state['snoozed_until'] ?? 0),
      'global_opt_out' => !empty($state['global_opt_out']),
      'campaigns' => $campaigns,
    ];
  }
}

if (!function_exists('custausu_review_notice_state')) {
  function custausu_review_notice_state(int $user_id = 0): array {
    $user_id = $user_id > 0 ? $user_id : get_current_user_id();

    if ($user_id <= 0) {
      return custausu_review_notice_normalize_state([]);
    }

    return custausu_review_notice_normalize_state(
      get_user_meta($user_id, custausu_review_notice_state_meta_key(), true)
    );
  }
}

if (!function_exists('custausu_review_notice_update_state')) {
  function custausu_review_notice_update_state(array $state, int $user_id = 0): bool {
    $user_id = $user_id > 0 ? $user_id : get_current_user_id();

    if ($user_id <= 0) {
      return false;
    }

    return (bool) update_user_meta(
      $user_id,
      custausu_review_notice_state_meta_key(),
      custausu_review_notice_normalize_state($state)
    );
  }
}

if (!function_exists('custausu_review_notice_seed_started_at')) {
  function custausu_review_notice_seed_started_at(): void {
    if (get_option(custausu_review_notice_started_option_name(), null) !== null) {
      return;
    }

    $configured = (bool) get_option('custausu_setup_completed', false)
      || (bool) get_option('custausu_wizard_completed', false);

    $started_at = $configured
      ? time() - (14 * DAY_IN_SECONDS)
      : time();

    add_option(custausu_review_notice_started_option_name(), $started_at, '', false);
  }
}

add_action('admin_init', 'custausu_review_notice_seed_started_at', 2);

if (!function_exists('custausu_review_notice_screen_allowed')) {
  function custausu_review_notice_screen_allowed(): bool {
    if (!is_admin() || !current_user_can('manage_options')) {
      return false;
    }

    $screen = function_exists('get_current_screen') ? get_current_screen() : null;
    $screen_id = $screen && isset($screen->id)
      ? sanitize_key((string) $screen->id)
      : '';

    return in_array($screen_id, ['dashboard', 'plugins', 'plugins-network'], true);
  }
}

if (!function_exists('custausu_review_notice_is_eligible')) {
  function custausu_review_notice_is_eligible(): bool {
    if (!custausu_review_notice_screen_allowed()) {
      return false;
    }

    if (
      !(bool) get_option('custausu_setup_completed', false)
      && !(bool) get_option('custausu_wizard_completed', false)
    ) {
      return false;
    }

    $campaign = custausu_review_notice_campaign_key();

    if ($campaign === '') {
      return false;
    }

    $started_at = absint(get_option(custausu_review_notice_started_option_name(), 0));

    if ($started_at <= 0 || time() < ($started_at + (14 * DAY_IN_SECONDS))) {
      return false;
    }

    $state = custausu_review_notice_state();

    if (!empty($state['global_opt_out'])) {
      return false;
    }

    if (absint($state['snoozed_until'] ?? 0) > time()) {
      return false;
    }

    $status = sanitize_key((string) ($state['campaigns'][$campaign]['status'] ?? ''));

    return !in_array($status, ['declined', 'review_clicked'], true);
  }
}

if (!function_exists('custausu_community_feedback_event_card_attrs')) {
  function custausu_community_feedback_event_card_attrs(
    string $message_id,
    string $placement,
    string $title,
    string $subtitle = ''
  ): array {
    return [
      'data-custausu-rm-event-card' => '1',
      'data-custausu-rm-track-impression' => '0',
      'data-custausu-rm-message-id' => sanitize_key($message_id),
      'data-custausu-rm-placement' => sanitize_key($placement),
      'data-custausu-rm-category' => 'community',
      'data-custausu-rm-message-role' => 'community_feedback',
      'data-custausu-rm-delivery-group' => 'local_community_feedback',
      'data-custausu-rm-dismiss-hash' => '',
      'data-custausu-rm-title' => $title,
      'data-custausu-rm-subtitle' => $subtitle,
      'data-custausu-rm-cta-label' => '',
    ];
  }
}

if (!function_exists('custausu_community_feedback_event_cta_attrs')) {
  function custausu_community_feedback_event_cta_attrs(
    string $action_id
  ): array {
    return [
      'data-custausu-rm-event-cta' => '1',
      'data-custausu-rm-action-id' => sanitize_key($action_id),
    ];
  }
}

if (!function_exists('custausu_community_feedback_print_attrs')) {
  function custausu_community_feedback_print_attrs(array $attrs): void {
    foreach ($attrs as $name => $value) {
      printf(
        ' %1$s="%2$s"',
        esc_attr((string) $name),
        esc_attr((string) $value)
      );
    }
  }
}

if (!function_exists('custausu_review_notice_action_url')) {
  function custausu_review_notice_action_url(string $review_action): string {
    return wp_nonce_url(
      add_query_arg([
        'action' => 'custausu_review_notice_action',
        'review_action' => sanitize_key($review_action),
      ], admin_url('admin-post.php')),
      'custausu_review_notice_action'
    );
  }
}

if (!function_exists('custausu_review_notice_apply_action')) {
  function custausu_review_notice_apply_action(string $review_action): void {
    $review_action = sanitize_key($review_action);
    $state = custausu_review_notice_state();
    $campaign = custausu_review_notice_campaign_key();
    $now = time();

    if (in_array($review_action, ['snooze', 'later'], true)) {
      $state['snoozed_until'] = $now + (3 * DAY_IN_SECONDS);
    } elseif ($review_action === 'forum') {
      $state['snoozed_until'] = $now + (14 * DAY_IN_SECONDS);
    } elseif ($review_action === 'already_reviewed') {
      $state['global_opt_out'] = true;
      $state['snoozed_until'] = 0;
    } elseif ($campaign !== '' && in_array($review_action, ['decline', 'review'], true)) {
      $state['campaigns'][$campaign] = [
        'status' => $review_action === 'review' ? 'review_clicked' : 'declined',
        'updated_at' => $now,
      ];
      $state['snoozed_until'] = 0;
    }

    custausu_review_notice_update_state($state);
  }
}

if (!function_exists('custausu_review_notice_handle_action')) {
  function custausu_review_notice_handle_action(): void {
    if (!current_user_can('manage_options')) {
      wp_die(esc_html__('You do not have permission to perform this action.', 'custom-auth-suite'));
    }

    check_admin_referer('custausu_review_notice_action');

    $review_action = isset($_REQUEST['review_action'])
      ? sanitize_key((string) wp_unslash($_REQUEST['review_action']))
      : '';

    $allowed = ['snooze', 'later', 'forum', 'already_reviewed', 'decline', 'review'];

    if (!in_array($review_action, $allowed, true)) {
      wp_die(esc_html__('Invalid review notice action.', 'custom-auth-suite'));
    }

    custausu_review_notice_apply_action($review_action);

    if (!empty($_POST['custausu_review_ajax'])) {
      wp_send_json_success(['action' => $review_action]);
    }

    if ($review_action === 'review') {
      custausu_community_feedback_redirect_to_wordpress_org(
        custausu_wporg_reviews_url()
      );
    }

    if ($review_action === 'forum' && custausu_community_feedback_is_free()) {
      custausu_community_feedback_redirect_to_wordpress_org(
        custausu_wporg_support_url()
      );
    }

    wp_safe_redirect(wp_get_referer() ?: admin_url());
    exit;
  }
}

add_action('admin_post_custausu_review_notice_action', 'custausu_review_notice_handle_action');

if (!function_exists('custausu_review_notice_enqueue_assets')) {
  function custausu_review_notice_enqueue_assets(string $hook): void {
    if (
      !current_user_can('manage_options')
      || !in_array($hook, ['index.php', 'plugins.php', 'plugins-network.php'], true)
    ) {
      return;
    }

    $css = CUSTAUSU_PLUGIN_DIR . 'inc/css/custausu-review-notice.css';
    $js = CUSTAUSU_PLUGIN_DIR . 'inc/assets/js/custausu-review-notice.js';

    wp_enqueue_style(
      'custausu-review-notice',
      CUSTAUSU_PLUGIN_URL . 'inc/css/custausu-review-notice.css',
      [],
      is_file($css) ? (string) filemtime($css) : CUSTAUSU_VERSION
    );

    wp_enqueue_script(
      'custausu-review-notice',
      CUSTAUSU_PLUGIN_URL . 'inc/assets/js/custausu-review-notice.js',
      [],
      is_file($js) ? (string) filemtime($js) : CUSTAUSU_VERSION,
      true
    );
  }
}

add_action('admin_enqueue_scripts', 'custausu_review_notice_enqueue_assets', 20);

if (!function_exists('custausu_review_notice_render')) {
  function custausu_review_notice_render(): void {
    if (!custausu_review_notice_is_eligible()) {
      return;
    }

    $it = custausu_community_feedback_is_it();
    $campaign = custausu_review_notice_campaign_key();
    $title = $it
      ? 'Cosa ne pensi di Custom Auth Suite™?'
      : 'What do you think about Custom Auth Suite™?';
    $subtitle = $it
      ? 'Una recensione onesta aiuta altri utenti e sostiene lo sviluppo del progetto.'
      : 'An honest review helps other users and supports continued development.';

    $ajax_url = admin_url('admin-post.php');
    $nonce = wp_create_nonce('custausu_review_notice_action');

    echo '<div class="notice notice-info is-dismissible custausu-review-notice"'
      . ' data-custausu-review-notice="1"'
      . ' data-custausu-review-action-url="' . esc_url($ajax_url) . '"'
      . ' data-custausu-review-nonce="' . esc_attr($nonce) . '"';

    custausu_community_feedback_print_attrs(
      custausu_community_feedback_event_card_attrs(
        'custausu_review_request_' . $campaign,
        'review_notice',
        $title,
        $subtitle
      )
    );

    echo '>';

    echo '<div class="custausu-review-notice__content">';
    echo '<h3>' . esc_html($title) . '</h3>';
    echo '<p>' . esc_html($subtitle) . '</p>';

    echo '<div class="custausu-review-notice__actions">';
    echo '<a class="button button-primary" href="' . esc_url(custausu_review_notice_action_url('review')) . '" target="_blank" rel="noopener noreferrer"';

    custausu_community_feedback_print_attrs(
      custausu_community_feedback_event_cta_attrs('review')
    );

    echo '>'
      . esc_html($it ? 'Lascia una recensione' : 'Leave a review')
      . '</a>';

    echo '<a class="button" href="' . esc_url(custausu_review_notice_action_url('later')) . '">'
      . esc_html($it ? 'Più tardi' : 'Maybe later')
      . '</a>';
    echo '</div>';

    if (custausu_community_feedback_is_free()) {
      echo '<div class="custausu-review-notice__support">';
      echo '<p><strong>' . esc_html($it ? 'Hai una domanda o un problema tecnico?' : 'Have a question or a technical problem?') . '</strong> '
        . esc_html($it
          ? 'Apri un topic nel forum di supporto e descrivi cosa è successo.'
          : 'Open a support topic and describe what happened.')
        . '</p>';

      echo '<a class="button button-secondary" href="' . esc_url(custausu_review_notice_action_url('forum')) . '" target="_blank" rel="noopener noreferrer"';

      custausu_community_feedback_print_attrs(
        custausu_community_feedback_event_cta_attrs('forum')
      );

      echo '>'
        . esc_html($it ? 'Scrivi nel forum' : 'Write in the forum')
        . '</a>';
      echo '</div>';
    }

    echo '<p class="custausu-review-notice__secondary">';
    echo '<a href="' . esc_url(custausu_review_notice_action_url('decline')) . '">'
      . esc_html($it ? 'No, grazie per questa release' : 'No thanks for this release')
      . '</a>';
    echo '<span aria-hidden="true"> · </span>';
    echo '<a href="' . esc_url(custausu_review_notice_action_url('already_reviewed')) . '">'
      . esc_html($it ? 'Ho già lasciato una recensione' : 'I’ve already reviewed')
      . '</a>';
    echo '</p>';
    echo '</div>';
    echo '</div>';
  }
}

add_action('admin_notices', 'custausu_review_notice_render', 30);

if (!function_exists('custausu_admin_render_community_feedback_panel')) {
  function custausu_admin_render_community_feedback_panel(
    callable $T,
    string $support_url = '',
    bool $assisted_support_enabled = false
  ): void {
    $title = $T('Doctor always listens to you!', 'Doctor ti ascolta sempre!');
    $subtitle = $T('Help shape Custom Auth Suite™', 'Aiuta a dare forma a Custom Auth Suite™');
    $review_url = custausu_wporg_reviews_url();
    $feature_url = custausu_community_feedback_feature_url(custausu_community_feedback_is_it() ? 'it' : 'en');

    echo '<section class="custausu-doctor-feedback"';

    custausu_community_feedback_print_attrs(
      custausu_community_feedback_event_card_attrs(
        'custausu_doctor_community_feedback',
        'doctor_feedback',
        $title,
        $subtitle
      )
    );

    echo '>';

    echo '<div class="custausu-doctor-feedback__head">';
    echo '<span class="dashicons dashicons-megaphone" aria-hidden="true"></span>';
    echo '<div>';
    echo '<h3>' . esc_html($title) . '</h3>';
    echo '<p>' . esc_html($subtitle) . '</p>';
    echo '</div>';
    echo '</div>';

    echo '<div class="custausu-doctor-feedback__grid">';

    echo '<article class="custausu-doctor-feedback__item">';
    echo '<h4>' . esc_html($T('Leave a review', 'Lascia una recensione')) . '</h4>';
    echo '<p>' . esc_html($T(
      'An honest review helps other users discover CAS and supports its continued development.',
      'Una recensione onesta aiuta altri utenti a conoscere CAS e sostiene lo sviluppo del progetto.'
    )) . '</p>';
    echo '<a class="button button-primary" href="' . esc_url($review_url) . '" target="_blank" rel="noopener noreferrer"';

    custausu_community_feedback_print_attrs(
      custausu_community_feedback_event_cta_attrs('review')
    );

    echo '>'
      . esc_html($T('Leave a review', 'Lascia una recensione'))
      . '</a>';
    echo '</article>';

    if (custausu_community_feedback_is_free()) {
      echo '<article class="custausu-doctor-feedback__item">';
      echo '<h4>' . esc_html($T('Write in the support forum', 'Scrivi nel forum di supporto')) . '</h4>';
      echo '<p>' . esc_html($T(
        'Ask a question or report a Free-edition problem with the details needed to investigate it.',
        'Fai una domanda o segnala un problema della versione Free con i dettagli utili a verificarlo.'
      )) . '</p>';
      echo '<a class="button" href="' . esc_url(custausu_wporg_support_url()) . '" target="_blank" rel="noopener noreferrer"';

      custausu_community_feedback_print_attrs(
        custausu_community_feedback_event_cta_attrs('forum')
      );

      echo '>'
        . esc_html($T('Write in the forum', 'Scrivi nel forum'))
        . '</a>';
      echo '</article>';
    }

    echo '<article class="custausu-doctor-feedback__item">';
    echo '<h4>' . esc_html($T('Propose a feature', 'Proponi una funzionalità')) . '</h4>';
    echo '<p>' . esc_html($T(
      'Share a quick idea that could make Custom Auth Suite™ more useful.',
      'Condividi rapidamente un’idea che potrebbe rendere Custom Auth Suite™ ancora più utile.'
    )) . '</p>';
    echo '<a class="button" href="' . esc_url($feature_url) . '" target="_blank" rel="noopener noreferrer"';

    custausu_community_feedback_print_attrs(
      custausu_community_feedback_event_cta_attrs('feature_request')
    );

    echo '>'
      . esc_html($T('Propose a feature', 'Proponi una funzionalità'))
      . '</a>';
    echo '</article>';

    if (
      !custausu_community_feedback_is_free()
      && $assisted_support_enabled
      && trim($support_url) !== ''
    ) {
      echo '<article class="custausu-doctor-feedback__item">';
      echo '<h4>' . esc_html($T('Open CAS Support Desk', 'Apri CAS Support Desk')) . '</h4>';
      echo '<p>' . esc_html($T(
        'Open the assisted support flow with the same consent and safe handoff used by Doctor.',
        'Apri il flusso di supporto assistito con lo stesso consenso e handoff sicuro usato dal Doctor.'
      )) . '</p>';
      echo '<a class="button" href="' . esc_url($support_url) . '" target="_blank" rel="noopener noreferrer"';

      custausu_community_feedback_print_attrs(
        custausu_community_feedback_event_cta_attrs('support')
      );

      echo '>'
        . esc_html($T('Open CAS Support Desk', 'Apri CAS Support Desk'))
        . '</a>';
      echo '</article>';
    }

    echo '</div>';
    echo '</section>';
  }
}
