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

if (!function_exists('custausu_admin_backend_t')) {
  function custausu_admin_backend_t(string $en, string $it): string {
    $loc = function_exists('get_user_locale') ? (string) get_user_locale() : (string) get_locale();
    $is_it = (stripos($loc, 'it_') === 0);
    return $is_it ? $it : $en;
  }
}

if (!function_exists('custausu_admin_tiny_mce_align_buttons_filter')) {
  function custausu_admin_tiny_mce_align_buttons_filter($init) {
    $tb1 = isset($init['toolbar1']) ? (string) $init['toolbar1'] : '';
    if ($tb1 === '') return $init;

    foreach (['alignleft', 'aligncenter', 'alignright', 'alignjustify'] as $btn) {
      if (strpos($tb1, $btn) === false) {
        $tb1 .= ',' . $btn;
      }
    }

    $init['toolbar1'] = $tb1;
    return $init;
  }
}

if (!function_exists('custausu_admin_enqueue_assets')) {
  function custausu_admin_enqueue_assets(string $hook): void {
    if ($hook !== 'toplevel_page_custausu-settings') return;

    $T = 'custausu_admin_backend_t';

    wp_enqueue_style('wp-color-picker');
    wp_enqueue_script('wp-color-picker');

    if (!has_filter('tiny_mce_before_init', 'custausu_admin_tiny_mce_align_buttons_filter')) {
      add_filter('tiny_mce_before_init', 'custausu_admin_tiny_mce_align_buttons_filter', 20);
    }

    wp_enqueue_editor();

    $custausu_admin_css = CUSTAUSU_PLUGIN_DIR . 'inc/css/custausu-admin.css';

    wp_enqueue_style(
      'custausu-admin-ui',
      CUSTAUSU_PLUGIN_URL . 'inc/css/custausu-admin.css',
      [],
      file_exists($custausu_admin_css) ? (string) filemtime($custausu_admin_css) : CUSTAUSU_VERSION
    );

    wp_enqueue_script(
      'custausu-admin-top-panel',
      CUSTAUSU_PLUGIN_URL . 'inc/assets/js/custausu-admin-top-panel.js',
      [],
      '1.1.4',
      true
    );

    wp_enqueue_script(
      'custausu-doctor-launcher',
      CUSTAUSU_PLUGIN_URL . 'inc/assets/js/custausu-doctor-launcher.js',
      ['custausu-admin-top-panel'],
      '1.2.0',
      true
    );

    $custausu_doctor_preview_js = CUSTAUSU_PLUGIN_DIR . 'inc/assets/js/custausu-doctor-support-preview.js';
    wp_enqueue_script(
      'custausu-doctor-support-preview',
      CUSTAUSU_PLUGIN_URL . 'inc/assets/js/custausu-doctor-support-preview.js',
      [],
      is_readable($custausu_doctor_preview_js) ? (string) filemtime($custausu_doctor_preview_js) : CUSTAUSU_VERSION,
      true
    );

    wp_localize_script('custausu-admin-top-panel', 'CUSTAUSU_ADMIN_TOP_PANEL', [
      'ajax_url'            => admin_url('admin-ajax.php'),
      'nonce'               => wp_create_nonce('custausu_health_check'),

      'run_label'           => $T('Run check', 'Esegui controllo'),
      'running_label'       => $T('Checking...', 'Controllo in corso...'),
      'error_label'         => $T('Health check failed', 'Controllo stato fallito'),
      'network_error_label' => $T('Network error', 'Errore di rete'),


      'export_report_loading_label' => $T('Preparing report...', 'Preparazione report...'),
      'export_report_done_label'    => $T('Report downloaded.', 'Report scaricato.'),
      'export_report_error_label'   => $T('Export failed. Please try again.', 'Export non riuscito. Riprova.'),
    ]);

    wp_enqueue_script(
      'custausu-admin-email-customizer',
      CUSTAUSU_PLUGIN_URL . 'inc/assets/js/custausu-admin-email-customizer.js',
      ['jquery', 'wp-color-picker'],
      '1.0.0',
      true
    );

    wp_localize_script('custausu-admin-email-customizer', 'CUSTAUSU_ADMIN_EMAIL', [
      'ajax_url'              => admin_url('admin-ajax.php'),
      'nonce'                 => wp_create_nonce('custausu_send_test_email'),
      'site_name'             => get_bloginfo('name'),
      'home_url'              => home_url('/'),
      'profile_url'           => custausu_profile_login_url(),
      'msg_insert_test_email' => $T('Insert a test email', 'Inserisci una email di test'),
      'msg_sending'           => $T('Sending...', 'Invio...'),
      'msg_sent'              => $T('✅ Test email sent!', '✅ Test email inviata!'),
      'msg_error_prefix'      => $T('❌ Error: ', '❌ Errore: '),
      'msg_network_error'     => $T('❌ Network error', '❌ Errore di rete'),
      'msg_send_test'         => $T('Send test', 'Invia test'),
    ]);

    wp_enqueue_script(
      'custausu-admin-copy-buttons',
      CUSTAUSU_PLUGIN_URL . 'inc/assets/js/custausu-admin-copy-buttons.js',
      [],
      '1.0.0',
      true
    );

    wp_enqueue_script(
      'custausu-admin-reset',
      CUSTAUSU_PLUGIN_URL . 'inc/assets/js/custausu-admin-reset.js',
      [],
      '1.0.0',
      true
    );

    wp_localize_script('custausu-admin-reset', 'CUSTAUSU_ADMIN_RESET', [
      'confirm_text' => $T(
        'Warning: this will delete all CAS settings currently saved in custausu_global_settings. Do you want to continue?',
        'Attenzione: questa azione eliminerà tutte le impostazioni CAS attualmente salvate in custausu_global_settings. Vuoi continuare?'
      ),
    ]);

    wp_enqueue_script(
      'custausu-admin-save-state',
      CUSTAUSU_PLUGIN_URL . 'inc/assets/js/custausu-admin-save-state.js',
      [],
      '1.0.0',
      true
    );

    wp_localize_script('custausu-admin-save-state', 'CUSTAUSU_ADMIN_SAVE_STATE', [
      'clean_label' => $T('Save settings','Salva impostazioni'),
      'dirty_label' => $T('Save changes','Salva modifiche'),
    ]);

    wp_enqueue_script(
      'custausu-admin-clean-referer',
      CUSTAUSU_PLUGIN_URL . 'inc/assets/js/custausu-admin-clean-referer.js',
      [],
      '1.0.0',
      true
    );

    wp_localize_script('custausu-admin-clean-referer', 'CUSTAUSU_ADMIN_CLEAN_REFERER', [
      'clean_url' => admin_url('admin.php?page=custausu-settings'),
    ]);

    wp_enqueue_script(
      'custausu-admin-routes-accordion',
      CUSTAUSU_PLUGIN_URL . 'inc/assets/js/custausu-admin-routes-accordion.js',
      [],
      '1.0.0',
      true
    );

    $custausu_doctor_warning_ack_js = CUSTAUSU_PLUGIN_DIR . 'inc/assets/js/custausu-doctor-warning-ack.js';
    wp_enqueue_script(
      'custausu-doctor-warning-ack',
      CUSTAUSU_PLUGIN_URL . 'inc/assets/js/custausu-doctor-warning-ack.js',
      [],
      is_readable($custausu_doctor_warning_ack_js) ? (string)filemtime($custausu_doctor_warning_ack_js) : CUSTAUSU_VERSION,
      true
    );

    wp_localize_script('custausu-doctor-warning-ack', 'CUSTAUSU_DOCTOR_WARNING_ACK', [
      'confirm_text' => $T(
        'Confirm only after you reviewed the plugin warning and applied the recommended compatibility measures. Continue?',
        'Conferma solo dopo aver verificato il warning del plugin e applicato le misure di compatibilità raccomandate. Continuare?'
      ),
    ]);

    $custausu_mobile_field_popup_js = CUSTAUSU_PLUGIN_DIR . 'inc/assets/js/custausu-admin-mobile-field-popup.js';
    wp_enqueue_script(
      'custausu-admin-mobile-field-popup',
      CUSTAUSU_PLUGIN_URL . 'inc/assets/js/custausu-admin-mobile-field-popup.js',
      [],
      file_exists($custausu_mobile_field_popup_js) ? (string) filemtime($custausu_mobile_field_popup_js) : CUSTAUSU_VERSION,
      true
    );

  }
}