package LIMS::Controller::PhoneLog;

use parent 'LIMS::Base';

use Moose;
	with 'LIMS::Controller::Roles::User';
__PACKAGE__->meta->make_immutable(inline_constructor => 0);
	
# ------------------------------------------------------------------------------
# default() should never be called direct - redirect to start page:
sub default : StartRunmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);

    return $self->redirect( $self->query->url );
}

# ------------------------------------------------------------------------------
sub load : Runmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);
    my $errs = shift;
	
    return $self->forbidden() unless $self->user_can('phone_log');
    
    my $request_id = $self->param('id')
    || return $self->error('no id passed to ' . $self->get_current_runmode);

    my $data        = $self->model('PhoneLog')->get_phonelog_data($request_id);
    my $request     = $self->model('Request')->get_single_request($request_id);
	my $log_options = $self->model('PhoneLog')->get_phonelog_options;	
	my $lab_staff   = $self->get_lab_staff_users;
	
    $self->tt_params( 
        data       => $data,
        users      => $lab_staff,
        request    => $request,
		options    => $log_options,
	);

	$self->js_validation_profile('phonelog');

    return $self->tt_process('phonelog/default.tt', $errs);
}

#-------------------------------------------------------------------------------
sub update : Runmode {
    my $self = shift; $self->_debug_path($self->get_current_runmode);
    
    my $request_id = $self->param('id')
    || return $self->error('no id passed to ' . $self->get_current_runmode);

    my $dfv = $self->check_rm('load', $self->validate('phonelog') )
	|| return $self->dfv_error_page;

    my $data = $dfv->valid(); # $self->debug($data);

    # put request_id into $data:
    $data->{request_id} = $request_id;
	
	# create 'details' param from optional 'comments' & 'summary' fields:
	$data->{details} = join '; ',
		map { $data->{$_} } grep $data->{$_}, qw(summary comments);
   
    my $rtn = $self->model('PhoneLog')->update_phonelog($data);
 
    if ($rtn) {
        $self->error($rtn);
	}
	else {
		$self->flash( info => $self->messages('action')->{create_success} );
		$self->redirect( $self->query->url . '/phone-log/=/' . $request_id );
	}
}

1;
