#!/usr/bin/perl
##############################################################################
# COFC new customer login request screen
##############################################################################

use strict;
use warnings;

use CGI;
use Data::Dumper;
use HTML::Entities;
use Template;
use URI::Escape;
$Data::Dumper::Sortkeys = 1;

use lib '/home/httpd/cofhol/cgi-binBENSUT/mod';
use COFC;

eval { COFC::init(); };
if ( $@ ) {
    die $@;
}

my $q = $COFC::CGI;

my %cgi_args = $q->Vars;

my $tt = Template->new( ABSOLUTE => 1 );
my $tt_data = { };

if ( 0 && keys %cgi_args ) {
    COFC::eject(\%cgi_args, \%ENV);
    print "Content-Type: text/plain\n\n";
    print Dumper({ _0_q_Vars => \%cgi_args, _1_ENV => \%ENV });
    exit 0;
}

my %gtg_all = (
    request_logo => ($ENV{'GTG_SMALL_LOGO'} || ''),
    company      => ($ENV{'GTG_COMPANY'} || ''),
);

my @errors = ();
$$tt_data{'focus_id'} = 'email';

my $mode = '';
my $suffix = '';

my $tmpl_data = {
    request_logo => $gtg_all{'request_logo'},
    company => $gtg_all{'company'},
    mode => $mode,
    suffix => $suffix,
    current_year => (localtime())[5] + 1900,
};

if ( $cgi_args{'confirm'} ) {
    my $result = COFC::confirm_login_request($cgi_args{'confirm'});
    if ( $$result{'success'} ) {
        $$tmpl_data{'token_confirmed'} = 1;
    }
    else {
        $$tmpl_data{'token_error'} = 1;
        if ( $$result{'message'} ) {
            push @errors, $$result{'message'};
        }
        else {
            push @errors, qq(Could not confirm request);
        }
    }
}
elsif ( $cgi_args{'form_submitted'} && validate_args(\%cgi_args, $tt_data, \@errors) ) {
    # args look good, insert login request

#    COFC::eject("looks good:", \%cgi_args);

    my $insert_args = {
        email => $cgi_args{'email'},
        name => $cgi_args{'first_name'} . ' ' . $cgi_args{'last_name'},
        vendorid => $cgi_args{'vendorid'},
        company => $cgi_args{'cust_name'},
        office_loc => $cgi_args{'office_loc'},
        phone => $cgi_args{'telephone'},
        also_notify_email => $cgi_args{'also_notify'},
        after_hours_phone => $cgi_args{'ah_phone'},
        after_hours_email => $cgi_args{'ah_email'},
        request_ip => $ENV{'REMOTE_ADDR'} || '',
    };

    my $result = COFC::add_login_request($insert_args);

    if ( $$result{'success'} ) {
        $$tmpl_data{'confirmation_sent'} = 1;
    }
    else {
        push @errors, qq(Your login request could not be processed. Please try again later.);
    }
}

my $title = "COFC Customer Login Request";
print $q->header,
$q->start_html(-title => $title);

$$tmpl_data{'errors'} = \@errors if @errors;

%$tmpl_data = (%$tt_data, %$tmpl_data);

my $out;
(my $template_dir = $0) =~ s#^(.+)/[^/]+$#$1#;
$tt->process( $template_dir . '/request.tt', $tmpl_data, \$out ) || die $tt->error(), "\n ";

print $out;

exit 0;

##############################################################################
# validate_args - process incoming CGI args to make sure required fields are
#                 present and any filled-out fields are valid to the extent
#                 we can tell right now; also normalize values as needed
##############################################################################

sub validate_args {
    my $args = shift;
    my $tt_data = shift;
    my $errors = shift;
    my $success = 1;
    my $focus_id = '';

    ##########################################################################
    # primary email address

    if ( !$$args{'email'} ) {
        push @$errors, "E-mail is required";
        $focus_id = 'email' unless $focus_id;
        $success = 0;
    }
    elsif ( !COFC::validate_email($$args{'email'}) ) {
        push @$errors, "E-mail address does not appear to be valid";
        $focus_id = 'email' unless $focus_id;
        $success = 0;
    }
    else {
        $$args{'email'} = COFC::validate_email($$args{'email'});
    }

    ##########################################################################
    # first & last names

    if ( !$$args{'first_name'} ) {
        push @$errors, "First name is required";
        $focus_id = 'first_name' unless $focus_id;
        $success = 0;
    }

    if ( !$$args{'last_name'} ) {
        push @$errors, "Last name is required";
        $focus_id = 'last_name' unless $focus_id;
        $success = 0;
    }

    ##########################################################################
    # customer number & name

    if ( !$$args{'vendorid'} ) {
        push @$errors, "Customer No. is required";
        $focus_id = 'vendorid' unless $focus_id;
        $success = 0;
    }

    if ( !$$args{'cust_name'} ) {
        push @$errors, "Company name is required";
        $focus_id = 'cust_name' unless $focus_id;
        $success = 0;
    }

    ##########################################################################
    # office location

    if ( !$$args{'office_loc'} ) {
        push @$errors, "Office City/State is required";
        $focus_id = 'office_loc' unless $focus_id;
        $success = 0;
    }

    ##########################################################################
    # telephone

    if ( !$$args{'telephone'} ) {
        push @$errors, "Telephone is required";
        $focus_id = 'telephone' unless $focus_id;
        $success = 0;
    }
    elsif ( !COFC::validate_phone($$args{'telephone'}) ) {
        push @$errors, "Invalid telephone";
        $focus_id = 'telephone' unless $focus_id;
        $success = 0;
    }
    $$args{'telephone'} = COFC::format_phone($$args{'telephone'});

    ##########################################################################
    # also notify email address

    if ( !$$args{'also_notify'} ) {
        push @$errors, "Also Notify E-mail is required";
        $focus_id = 'also_notify' unless $focus_id;
        $success = 0;
    }
    elsif ( !COFC::validate_email($$args{'also_notify'}) ) {
        push @$errors, "Also Notify E-mail address does not appear to be valid";
        $focus_id = 'also_notify' unless $focus_id;
        $success = 0;
    }
    else {
        $$args{'also_notify'} = COFC::validate_email($$args{'also_notify'});
    }

    if ( $$args{'also_notify'} && $$args{'also_notify'} eq $$args{'email'} ) {
        push @$errors, "Also Notify E-mail address is the same as primary email";
        $focus_id = 'also_notify' unless $focus_id;
        $success = 0;
    }

    ##########################################################################
    # after hours telephone

    if ( $$args{'ah_phone'} && !COFC::validate_phone($$args{'ah_phone'}) ) {
        push @$errors, "Invalid after hours telephone";
        $focus_id = 'ah_phone' unless $focus_id;
        $success = 0;
    }
    $$args{'ah_phone'} = COFC::format_phone($$args{'ah_phone'});

    ##########################################################################
    # after hours email

    if ( $$args{'ah_email'} && !COFC::validate_email($$args{'ah_email'}) ) {
        push @$errors, "After hours E-mail address does not appear to be valid";
        $focus_id = 'ah_email' unless $focus_id;
        $success = 0;
    }
    else {
        $$args{'ah_email'} = COFC::validate_email($$args{'ah_email'});
    }

    if ( $$args{'ah_email'} && $$args{'ah_email'} eq $$args{'email'} ) {
        push @$errors, "After hours E-mail address is the same as primary email";
        $focus_id = 'ah_email' unless $focus_id;
        $success = 0;
    }

    if ( $$args{'ah_email'} && $$args{'ah_email'} eq $$args{'also_notify'} ) {
        push @$errors, "After hours E-mail address is the same as also-notify email";
        $focus_id = 'ah_email' unless $focus_id;
        $success = 0;
    }

    ##########################################################################
    # copy validated, normalized, and encoded args to the template hash, so
    # they can be displayed if there is an error

    for my $key ( qw(email first_name last_name vendorid cust_name office_loc telephone also_notify ah_phone ah_email) ) {
        $$args{$key} = '' unless defined $$args{$key};
        $$args{$key} =~ s/^ +//;
        $$args{$key} =~ s/ +$//;
        $$tt_data{$key} = HTML::Entities::encode($$args{$key});
    }

    $$tt_data{'focus_id'} = $focus_id;
    return $success;
}

