package LIMS::Controller::Admin::Lab::Test::Accreditation;

use Data::Dumper;
use LIMS::Local::Sugar;

use Moose;
BEGIN { extends 'LIMS::Base'; }
with 'LIMS::Controller::Roles::Misc';
__PACKAGE__->meta->make_immutable(inline_constructor => 0);

__PACKAGE__->authz->authz_runmodes(	':all' => 'do_admin' );

# ------------------------------------------------------------------------------
startmode default ($errs) { # not using $errs
    $self->_debug_path($self->get_current_runmode);

    my $lab_sections = $self->model('LabSection')->get_lab_sections;
    $self->tt_params( lab_sections => $lab_sections );

    if ( my $lab_section_id = $self->query->param('lab_section_id') ) {
        my @tests = do {
            my %args = (
                lab_section_id => $lab_section_id,
                is_active   => 'yes',
            );
            my $o = $self->model('LabTest')->get_section_lab_tests(\%args);
            # sort by field label lc:
            sort { lc $a->field_label cmp lc $b->field_label } @$o;
        }; # warn Dumper \@tests;
        $self->tt_params( lab_tests => \@tests );

        { # get existing data:
            my $data = $self->lab_test_accreditation_map; # warn Dumper $data;
            $self->tt_params( data => $data );
        }
    }
    return $self->tt_process('admin/lab/test/accreditation/default.tt');
}

# -------------------------------------------------------------------------------------
runmode edit ($id) {
	$self->_debug_path($self->get_current_runmode); # $self->stash( errs => $errs);

    $id || return $self->error('no id passed to '.$self->get_current_runmode);
    {
		my $data = $self->model('LabTest')->get_lab_test_accreditation($id);
		$self->tt_params( data => $data	);
	}
    return $self->tt_process(); # not using errs - only date var handled by form
}

# -------------------------------------------------------------------------------------
runmode update ($id) {
    $self->_debug_path($self->get_current_runmode);

    my $accreditation_uri  = '/admin/lab_test_accreditation';
    my $accreditation_date = $self->query->param('accreditation_date');
    my $lab_section_id     = $self->query->param('lab_section_id'); # hidden field

    # incorrect date format unlikely if date picker used:
    if ($accreditation_date && $accreditation_date !~ /^\d{4}-\d{2}-\d{2}$/) {
        $self->flash( error => qq!incorrect date format "$accreditation_date"!);
        my $url = $self->query->url . $accreditation_uri . '/edit/' . $id;
        return $self->redirect( $url );
    }
    my %data = (
        lab_test_id        => $id,
        accreditation_date => $accreditation_date,
    );
    my $url = $accreditation_uri . '?lab_section_id=' . $lab_section_id;

    my $rtn = $self->model('LabTest')->update_accreditation_date(\%data);
    return $rtn
        ? $self->error($rtn)
        : $self->redirect_after_edit_success($url);
}

1;
