package Koha::Plugin::Pt::KEEPS::ResendFailedEmails;

use Modern::Perl;

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

our $VERSION = '1.0';

our $metadata = {
    name   => 'KEEP - Resend Failed Emails',
    author => 'Keep Solutions - joliveira@keep.pt',
    description => 'This plugin will attempt to resend emails that failed for some reason',
    date_authored   => '2023-09-19',
    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;
}


sub startup {
    my $path = "/KEEPS/koha/var/lib/koha/plugins/Koha/Plugin/Pt/KEEPS/ResendFailedEmails";

    my $DIR = "/KEEPS/koha";
    my $CRONJOBS = $DIR . "/bin/cronjobs";

    system("mkdir -p $CRONJOBS/resend-failed-emails");
    system("cp $path/resend-failed-emails_plugin.pl $CRONJOBS/resend-failed-emails/resend-failed-emails_plugin.pl");
}

sub cronjob {
    my $PERL= "/usr/bin/perl";
    my $PERL5LIB= "/KEEPS/koha/lib/";
    my $KOHA_CRON_PATH= "/KEEPS/koha/bin/cronjobs";

    system("$PERL -I $PERL5LIB $KOHA_CRON_PATH/resend-failed-emails/resend-failed-emails_plugin.pl");
}


# Mandatory even if does nothing
sub install {
    my ( $self, $args ) = @_;
    startup();
    $self->store_data(
    {
        interval_hours => '49',
        last_configured_by => C4::Context->userenv->{'number'},
    }
    );
    return 1;
}

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

    return 1;
}

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

    my $DIR = "/KEEPS/koha";
    my $CRONJOBS = $DIR . "/bin/cronjobs";

    system("rm $CRONJOBS/resend-failed-emails/resend-failed-emails_plugin.pl");

    return 1;
}



sub configure {
    my ($self, $args) = @_;
    my $cgi = $self->{'cgi'};

    unless ($cgi->param('save')) {
        my $lang_dialect = C4::Languages::getlanguage($cgi);

        my $template = $self->get_template({ file => 'configure.tt' });

        $template->param(
            lang_dialect => $lang_dialect,
            interval_hours => $self->retrieve_data('interval_hours'),
            last_upgraded   => $self->retrieve_data('last_upgraded'),
        );

        $self->output_html( $template->output() );
    } else {
        $self->store_data(
            {
            interval_hours => $cgi->param('interval_hours'),
            last_configured_by => C4::Context->userenv->{'number'},
            }
        );
        $self->go_home();
    }
}



1;