package Koha::Plugin::Pt::KEEPS::CatalogueAdvancedSearch;

use Modern::Perl;

use base qw(Koha::Plugins::Base);

our $VERSION = '1.0';

our $metadata = {
    name   => 'KEEPS - Catalogue Advanced Search',
    author => 'Keep Solutions',
    description => 'New advanced search fields',
    date_authored   => '2022-01-26',
    date_updated    => undef,
    minimum_version => '21.05',
    maximum_version => undef,
    version         => $VERSION,
};

sub new {
    my ( $class, $args ) = @_;

    $args->{'metadata'} = $metadata;
    $args->{'metadata'}->{'class'} = $class;

    my $self = $class->SUPER::new($args);

    return $self;
}

# Mandatory even if does nothing
sub install {
    my ( $self, $args ) = @_;

    return 1;
}

# Mandatory even if does nothing
sub upgrade {
    my ( $self, $args ) = @_;

    return 1;
}

# Mandatory even if does nothing
sub uninstall {
    my ( $self, $args ) = @_;

    return 1;
}

sub intranet_js {
    my ( $self ) = @_;

    my $path = $self->get_plugin_http_path();

    return qq%
<script>
    var pathname = window.location.pathname;
    var adv_search_plugin_path = "$path";

    var lang = \$('html').attr('lang');
    if (lang == null) {
        lang = \$('html').attr('xml:lang');
    }

    // Set the global configs to synchronous 
    \$.ajaxSetup({
        async: false
    });

    var TOKENS = {};
    \$.getJSON(adv_search_plugin_path + `/i18n/\${lang}.json`, function (data) {
        TOKENS = data;
    }).fail(function() { 
        \$.getJSON(adv_search_plugin_path + `/i18n/default.json`, function (data) {
            TOKENS = data;
        }); 
    });

    \$.ajaxSetup({
        async: true
    });

    if (pathname.match("/cgi-bin/koha/catalogue/search.pl") && \$("body#catalog_advsearch").length) {
        \$(".advsearch option[value='acqdate,st-date-normalized']").each(function () {
            \$(this).text(TOKENS.item_acq_date_label);
            \$(this).val("acqdate,wrdl");
        });

        \$("#searchterms .advsearch").append('<option value="date-entered-on-file,wrdl">' + TOKENS.record_acq_date_label +'</option>');
 
        \$('#searchterms option[value="ns"]').after('<option value="cdd">&nbsp;&nbsp;&nbsp;&nbsp; CDD</option>');
        \$('#searchterms option[value="ns"]').after('<option value="cdu">&nbsp;&nbsp;&nbsp;&nbsp; CDU</option>');

        //--- Remove unwanted search terms ---//
        \$('#searchterms option[value="su-br"]').hide();
        \$('#searchterms option[value="su-na"]').hide();
        \$('#searchterms option[value="su-rl"]').hide();

        //--- Remove unwanted labels ---//
        \$('label[for="scan"],#scan').remove();

        //--- Add an extra advance search option ---//
        \$('<option value="control-number">' + TOKENS.control_number_label + '</option>').appendTo('#searchterms .advsearch');
    }
</script>
%;
}

1;