package Koha::Plugin::Pt::KEEPS::OpacTexts;

use utf8;

use Modern::Perl;
use URI::Escape;

use Data::Dumper;

use C4::Languages;
use C4::Context;

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

our $VERSION = '1.0';

our $metadata = {
    name   => 'KEEPS - OPAC Texts',
    author => 'Pedro Moura - pmoura@keep.pt',
    description => 'Plugin for adding new pages to OPAC',
    date_authored   => '2022-01-25',
    date_updated    => undef,
    minimum_version => '21.05',
    maximum_version => undef,
    version         => $VERSION
};


my $LANG_LIST = [ "pt-PT", "en" ];

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 ) = @_;

    # Create Table in database
    my $dbh = C4::Context->dbh();
    $dbh->do("CREATE TABLE IF NOT EXISTS `opac_texts` (
                `id` INT NOT NULL AUTO_INCREMENT,
                `name` VARCHAR(255) NOT NULL,
                `language` VARCHAR(10) NOT NULL,
                `description` VARCHAR(255),
                `content` MEDIUMTEXT,
                `active` BOOLEAN NOT NULL,
                PRIMARY KEY (id)
              );");
    
    return 1;
}

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

    return 1;
}

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

    # Delete table from database
    my $dbh = C4::Context->dbh();
    $dbh->do("DROP TABLE `opac_texts`;");

    return 1;
}


sub configure {
    my ($self, $args) = @_;
    my $cgi = $self->{'cgi'};
    my $lang_dialect = C4::Languages::getlanguage($cgi);


    if ($cgi->param('create')) {
        handle_create($self, {
            name => $cgi->param('name'),
            language => $cgi->param('language'),
            description => $cgi->param('description'),
            content => $cgi->param('content')
        });
    }
    elsif ($cgi->param('edit')) {
        handle_edit($self, {
            id => $cgi->param('id'),
            name => $cgi->param('name'),
            language => $cgi->param('language'),
            description => $cgi->param('description'),
            content => $cgi->param('content')
        });
    }
    elsif ($cgi->param('delete')) {
        handle_delete($self);
    }
    elsif ($cgi->param('enable')) {
        handle_enable($self);
    }
    elsif ($cgi->param('disable')) {
        handle_disable($self);
    }
    elsif ($cgi->param('create_page')) {
        handle_create_page($self, {
            lang_dialect => $lang_dialect,
            error_message => $cgi->param('error') // 0
        });
    } 
    elsif ($cgi->param('edit_page')) {
        handle_edit_page($self, {
            id => $cgi->param('id'),
            lang_dialect => $lang_dialect,
            error_message => $cgi->param('error') // 0
        });
    }
    else {
        handle_configure_page($self, {
            lang_dialect => $lang_dialect
        });
    }


}


sub handle_create {
    my ($self, $info) = @_;

    eval {
        my $dbh = C4::Context->dbh();
        my $sth = $dbh->prepare("SELECT count(*)
                                FROM opac_texts
                                WHERE name = '$info->{name}' AND language = '$info->{language}';");
        $sth->execute();
        if ($sth->err) {
            die { message => "SELECTING_RECORD_ERROR" };
        }

        my ($count) = $sth->fetchrow_array;
        if ($count) {
            die { message => "DUPLICATE_RECORD_ERROR" };
        }

        $dbh->do("INSERT INTO opac_texts
                (name, language, description, content, active)
                VALUES
                ('$info->{name}', '$info->{language}', '$info->{description}', '$info->{content}', 1);")
                or die { message => "INSERTING_RECORD_ERROR"};   
    };

    if ($@) {
        my $class = $self->{cgi}->param('class');
        my $method = $self->{cgi}->param('method');

        print $self->{cgi}->redirect(
            -uri => "?class=$class&method=$method&create_page=1&error=$@->{message}"
        );
    } else {
        go_configure_page($self); 
    }
}


sub handle_edit {
    my ($self, $info) = @_;

    eval {
        my $dbh = C4::Context->dbh();

        my $sth = $dbh->prepare("SELECT *
                                 FROM opac_texts
                                 WHERE name = '$info->{name}' AND language = '$info->{language}';");
        $sth->execute();
        if ($sth->err) {
            die { message => "SELECTING_RECORD_ERROR" };
        }

        my $row = $sth->fetchrow_hashref;
        warn Dumper $row;
        if ($row && $info->{id} != $row->{id}) {
            die { message => "DUPLICATE_RECORD_ERROR" };
        }

        $dbh->do("
            UPDATE opac_texts
            SET
                name = '$info->{name}',
                language = '$info->{language}',
                description = '$info->{description}',
                content = '$info->{content}'
            WHERE
                id = $info->{id};
        ") 
        or die { message => "UPDATING_RECORD_ERROR" };
    };

    if ($@) {
        my $class = $self->{cgi}->param('class');
        my $method = $self->{cgi}->param('method');

        print $self->{cgi}->redirect(
            -uri => "?class=$class&method=$method&edit_page=1&id=$info->{id}&error=$@->{message}"
        );
    } else {
        go_configure_page($self); 
    }
}


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

    my $id = $self->{cgi}->param('id');

    my $dbh = C4::Context->dbh();
    $dbh->do("DELETE FROM opac_texts WHERE id = $id;");

    go_configure_page($self);
}


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

    my $id = $self->{cgi}->param('id');

    my $dbh = C4::Context->dbh();
    $dbh->do("UPDATE opac_texts SET active = 1 WHERE id = $id;");

    go_configure_page($self);
}


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

    my $id = $self->{cgi}->param('id');

    my $dbh = C4::Context->dbh();
    $dbh->do("UPDATE opac_texts SET active = 0 WHERE id = $id;");

    go_configure_page($self);
}


sub handle_create_page {
    my ($self, $params) = @_;

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

    $template->param(
        lang_dialect => $params->{'lang_dialect'},
        lang_list => $LANG_LIST,
        op => 'create',
        error_message => $params->{'error_message'}
    );

    $self->output_html($template->output());
}


sub handle_edit_page {
    my ($self, $params) = @_;

    my $id = $self->{cgi}->param('id');

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

    my $dbh = C4::Context->dbh();
    my $sth = $dbh->prepare("SELECT * FROM opac_texts WHERE id = $id;");
    $sth->execute();

    my $opac_text = $sth->fetchrow_hashref;

    $template->param(
        id => $params->{'id'},
        lang_dialect => $params->{'lang_dialect'},
        lang_list => $LANG_LIST,
        op => 'edit',
        placeholder_info => {
            name => $opac_text->{'name'},
            language => $opac_text->{'language'},
            description => $opac_text->{'description'},
            content => $opac_text->{'content'}
        },
        error_message => $params->{'error_message'}
    );

    $self->output_html($template->output());
}


sub handle_configure_page {
    my ($self, $params) = @_;

    my $template = $self->get_template({ file => 'configure.tt' });
    
    my $dbh = C4::Context->dbh();
    my $sth = $dbh->prepare("SELECT * FROM opac_texts;");
    $sth->execute();

    my @opac_texts;
    while (my $hash_ref = $sth->fetchrow_hashref) {
        push @opac_texts, $hash_ref;
    }

    $template->param(
        lang_dialect => $params->{'lang_dialect'},
        opac_texts_entries => \@opac_texts
    );

    $self->output_html($template->output());
}


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

    my $class = $self->{cgi}->param('class');
    my $method = $self->{cgi}->param('method');

    print $self->{cgi}->redirect(
        -uri => "?class=$class&method=$method"
    );
}


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

    return qq%
<script>
    console.log('Hello World!');
</script>
%;
}



1;