#!/usr/bin/perl

BEGIN { use lib '/usr/home/cfg' ; require push_inc ; }
    
require cfg ;
# unless ($username eq 'handre') { print "<<<<<<<<<<<< MAINTENANCE IN PROGRESS >>>>>>>>>" ; exit ; }
#---------------------------------------------------------------------------------------------------------------------------------------------------------------------

use CGI::Carp qw(fatalsToBrowser);
use CGI;

&today;

#---------------------------------------------------------------------------------------------------------------------------------------------------------------------

@ARGV   = split(/\\*\&/, $ENV{'QUERY_STRING'});
$action = $ARGV[0] ;

our ($q)                 = CGI -> new() ;
our $iaction             = $q -> param('iaction')                || $action ;
our $isaved              = $q -> param('isaved')                 || '' ;
# our $debug = 1 ;
# our $testing = 1 ;

our $double_box_layout = 1 ;

# our $open_new_tab = qq~target="_blank"~ ; # opens booking page in a new tab

#-------- page opts --------------------------------------------------------------------------------------------------------------------------------------------------

&page_opts ; 

#---------------------------------------------------------------------------------------------------------------------------------------------------------------------

# unless ($useropts{it}{$username}) {
unless ($glod_user_level >= 5) {
	print "Development in Progress!!!" ;
	exit ;
}

print "Content-type: text/html\n\n";

if ($iaction eq 'update') {  
	&common_min_load_params ;
	&validate ;
	&update ;
    &common_min_screen2 ; 
	exit ;
}

&common_min_action ;

exit ;

#------------------------------------------------------------------------------------------

sub validate {

	my $exists = '' ;
	&db_min_ro($table,'*','','','') ;

	foreach my $id (keys %{$db{$table}}) {
		next if $i{id} && $i{id} eq $id ;
		if ($db{$table}{$id}{credit_type} eq $i{credit_type} && $db{$table}{$id}{client_id} eq $i{client_id} && ($db{$table}{$id}{sport_type_id} eq 'all' || $db{$table}{$id}{sport_type_id} eq $i{sport_type_id} || $i{sport_type_id} eq 'all')) {
			$exists = 1 ; 
		}
	}
	
	my $credits_out_of_range = (length $i{credits} > 10) ? 1 : 0 ;
	
	if ($credits_out_of_range) {
		$i{id} = $i{orig_id} if $i{orig_id} ;
		$alert = &common_min_alert('warning',"THE CREDITS NUMBER CONTAIN TOO MANY CHARACTERS!",'ok') ;
		%col_name = ();
		&common_min_error_screen;
		&common_min_screen1;
		exit ;
	}
	
	if ($exists) {
		$i{id} = $i{orig_id} if $i{orig_id} ;
		$alert = &common_min_alert('warning',"CREDITS ALREADY EXIST FOR THIS CLIENT, SPORT AND CREDIT TYPE!",'ok') ;
		%col_name = ();
		&common_min_error_screen;
		# $i{id} = $i{orig_id} if $i{orig_id} ;
		&common_min_screen1;
		exit ;
	}
	
} #------------------------------------------------------------------------------------------

sub insert {

	&add_db_fields ;

	$i{id} = &db_min_get_max($table,'id') ; 
	
	&db_min_insert($table) ;
	
	# exit ;

} #------------------------------------------------------------------------------------------

sub update {

	unless ($i{id}) { 
		$error = qq(NO ID) ; 
		return ; 
	}

	&edit_db_fields ;
	
	$ignore{id} = 1 ;
	
	&db_min_upd($table,"id='$i{id}'") ;

} #------------------------------------------------------------------------------------------

sub build_rates_fields {
	
	my ($field_name,$row_cnt) = @_ ; 
	
	# $ii{$field_name}	= qq~$db{$table}{1}{$field_name}~ ;
	$ii{$field_name}	.= ';' if $ii{$field_name} ;
	$ii{$field_name}	.= qq~$i{"$field_name\_$row_cnt"}~ ;
	$i{$field_name}		= $ii{$field_name} ; 
	
} #------------------------------------------------------------------------------------------

sub list_screen {
	
	&db_min_ro('sport_types','*','','','') ;
	
	&db_min_ro('customers','id,name','','','') ;
	
	&db_min_ro($table,'*','','id','') ;
	
	my $excl = "" ;
	
	our @sql_col_display = ("id","client","sport","credit_type","credits","") ; 
	
	my %credit_types = (1 => "Standard", 2 => "Premium", 3 => "Individual") ; 
	
	my $row_cnt = 0 ;
	
	foreach my $id (sort { $db{customers}{$db{$table}{$a}{client_id}}{name} cmp $db{customers}{$db{$table}{$b}{client_id}}{name} || $db{sport_types}{$db{$table}{$a}{sport_type_id}}{name} cmp $db{sport_types}{$db{$table}{$b}{sport_type_id}}{name} || $db{$table}{$a}{credit_type} <=> $db{$table}{$b}{credit_type} } keys %{$db{$table}}) {
		
		$print_tbody .= qq~<tr id="$id">~ ;
		
		$row_cnt++ ;
		
		foreach my $col (@sql_col_display) {
			
			$val = $db{$table}{$id}{$col} ;
			my $nowrap = "" ;
			my $align = qq~ class="dt-center"~ ;
			
			if ($col eq "id") {
				
				my $row_val = sprintf("%09d",$row_cnt) ; 
				$val = qq~<span style='display:none'>$row_val</span>$id~ ; 
				$align = qq~ class="dt-left"~ ; 
			} elsif ($col eq "client") {
				$val = $db{customers}{$db{$table}{$id}{client_id}}{name} ;
			} elsif ($col eq "sport") {
				$val = $db{sport_types}{$db{$table}{$id}{sport_type_id}}{name} ;
				$val = "All" if $db{$table}{$id}{sport_type_id} eq 'all' ;
			} elsif ($col eq "credit_type") {
				$val = $credit_types{$db{$table}{$id}{credit_type}} ;
			} elsif ($col eq "credits") {
				$val = &common_commify($val);
			} elsif ($col eq '') {
				$align = qq~ class="dt-left"~ ; 
				my $edit_butt = '' ; 
				my $del_butt  = '' ;	
				# if ($useropts{super}{$username}) { 
					# $edit_butt = qq~&nbsp;<a class="btn btn-info btn-xs" href="javascript:editMinItem('$db{$table}{$id}{id}');"><i class="glyphicon glyphicon-edit icon-white"></i></a>~ ; 
				# }
				# if ($useropts{boss}{$username} or $useropts{super}{$username}) { 
					# $del_butt  = qq~&nbsp;<a class="btn btn-danger btn-xs" href="javascript:deleteMinItem('$db{$table}{$id}{name}','$db{$table}{$id}{id}')"><i class="glyphicon glyphicon-trash icon-white"></i></a>~ if not $seen_event_item_costing{$id}; 
					# $del_butt  = qq~&nbsp;<a class="btn btn-default btn-xs" href="#" title data-toggle="tooltip" data-original-title="In system use!"><i class="glyphicon glyphicon-trash icon-white"></i></a>~ if $seen_event_item_costing{$id}; 
				# }
				$edit_butt = qq~&nbsp;<a class="btn btn-info btn-xs" href="javascript:editMinItem('$db{$table}{$id}{id}');" title="Edit" data-toggle="tooltip"><i class="glyphicon glyphicon-edit icon-white"></i></a>~ ;
				$del_butt  = qq~&nbsp;<a class="btn btn-danger btn-xs" href="javascript:deleteMinItem('$db{$table}{$id}{name}','$db{$table}{$id}{id}')" title="Delete" data-toggle="tooltip"><i class="glyphicon glyphicon-trash icon-white"></i></a>~ ;		
				
				$val = qq~$edit_butt$del_butt~ ;
			}
			$print_tbody .= qq~<td $nowrap $align>$val</td>~ ;	
		}
		$print_tbody .= qq~</tr>~ ;
	}

} #------------------------------------------------------------------------------------------

sub add_db_fields {
		
	# &sort_fields;
	&hidden_db_fields;
	# $ignore{id} = 1 ;

} #------------------------------------------------------------------------------------------

sub edit_db_fields {
		
	# &sort_fields;	
	&hidden_db_fields;
	$hidden{id} = 1 ; # 1 = bypass for db update

} #------------------------------------------------------------------------------------------

sub hidden_db_fields {
	
	$ignore{selected_add_credit_types} = 1 ;
	$ignore{iaction}               = 1 ;
	$ignore{orig_id}               = 1 ;
	
	&sort_fields ;
		
} #------------------------------------------------------------------------------------------

sub sort_fields {
	
} #-------------------------------------------------------------------------------

sub add_screen {

	&sort_fields ;

	&select_opts ;
	
	&build_boxes ;
	
} #------------------------------------------------------------------------------------------

sub edit_screen {
	
	&select_opts ;

	&build_boxes ;
	
} #------------------------------------------------------------------------------------------

sub build_boxes {
	
	our ($lcol,$fcol) = &common_min_columns() ;

	$add_form_fields = '' ;
	
	$print_box_content_rows .= &common_min_forms_start($table,$skip) ;

	$print_box_content_rows .= qq~<input name='id' value='$i{id}' style='display:none;'>~ if $i{id} ;

	$add_form_fields .= qq~
		<div class='row'>
			<div class='col-md-2'>
				<label class='control-label'>Customer</label>
			</div>
			<div class='col-md-1'>
				<label class='control-label'>Sport</label>
			</div>
			<div class='col-md-1'>
				<label class='control-label'>Credit&nbsp;Type</label>
			</div>	
			<div class='col-md-1'>
				<label class='control-label'>Credits</label>
			</div>
		</div>
	~ ;
 # align='center'
	$add_form_fields .= qq~<div class='row'>~ ;
	$fcol = 2 ;
	$add_form_fields .= &common_min_form_select_col("client_id") ;

	$fcol = 1 ;
	$add_form_fields .= &common_min_form_select_col("sport_type_id") ;
	$fcol = 1 ;
	$lcol = 3 ;

	# $i{credit_type} = $db{$table}{$i{id}}{credit_type} if $db{$table}{$i{id}}{credit_type} ;
	 
	$add_form_fields .= &common_min_form_select_col("credit_type") ;
	$fcol = 1 ;
	# $add_form_fields .= qq~</div>~ ;
	
	# $i{credits} = $db{$table}{$i{id}}{credits} if $db{$table}{$i{id}}{credits} ;
	 
	$required{credits} = 'data-validation="length number" data-validation-length="0-10"' ; 
	 
	$add_form_fields .= &common_min_form_input_col("credits",$i{credits}) ;
	$add_form_fields .= qq~</div>~ ;
	
	my $save_action = ($i{id}) ? 'update' : 'save' ;
	
	my $custom_class = ($invoice_exists && !$useropts{super}{$username} && !$useropts{it}{$username}) ? "custom" : "primary" ; 
	our $custom_back_button = ($save_action eq 'update') ? qq~&nbsp;<button type="button" class="btn btn-$custom_class" id="savebutt_new">Save New</button>&nbsp;~ : qq~~ ;
	our $addbkb = ($save_action eq 'update') ? 1 : 0 ;
	$add_form_fields .= &common_min_forms_end($iid,$table,$save_action,$skip) ;
	
	my $add_edit = ucfirst $iaction ; 
	
	my $orig_id = $i{id} ;
	
	$orig_id = "New" unless $orig_id;
	
	if ($save_action eq 'update') {
		$add_form_fields .= qq~<input type='hidden' value='$i{id}' name='orig_id'>~ ;
		$i{id} = &db_min_get_max($table,'id') ; 
	}
	
	$print_box_content_rows .= &common_min_box_top('',"&nbsp;$add_edit&nbsp;:&nbsp;$orig_id",$box_right_bg) ; 
	$print_box_content_rows .= $add_form_fields ;
	$print_box_content_rows .= &common_min_box_foot ;
	
	$trigger_jquery_raw .= qq~ 
		\$("#credits_allocated-form [id^='savebutt']").on("click", function (e) {
			if (this.id.includes("_new")) {
				\$("input[name='iaction']").val("save") ;
				\$("input[name='id']").val("$i{id}") ;				
			}
			if (!\$("#selectClient_id").val() || !\$("#selectSport_type_id").val() || !\$("#selectCredit_type").val() || !\$("input[name='credits']").val()) {
				noty({text:'Please select all of the input!',layout:"center",type:"error",timeout:10000}) ;
				return ; 
			}
			\$("#credits_allocated-form").submit() ;
		}) ;
	~ ; 
	
	$i{id} = $orig_id if $orig_id ne 'new' ;
	
} #------------------------------------------------------------------------------------------

sub select_opts {
	
	&common_min_select_opts('sport_type_id','sport_types','name','',0,'','') ;
	
	$i{client_id} = ($i{client_id}) ? $i{client_id} : $db{$table}{$i{id}}{client_id} ;
	$i{sport_type_id} = ($i{sport_type_id}) ? $i{sport_type_id} : $db{$table}{$i{id}}{sport_type_id} ;
	$i{credit_type} = ($i{credit_type}) ? $i{credit_type} : $db{$table}{$i{id}}{credit_type} ;
	$i{credits} = ($i{credits}) ? $i{credits} : $db{$table}{$i{id}}{credits} ;
	
	# $i{sport_type_id} = $db{$table}{$i{id}}{sport_type_id} if $db{$table}{$i{id}}{sport_type_id} ;
	
	$opts{sport_type_id} .= qq~<option value="all">All</option>~ ;

	$opts{sport_type_id} =~ s/value="\Q$i{sport_type_id}\E"/value="$i{sport_type_id}" SELECTED/g if $i{sport_type_id} ;
	
	&common_min_select_opts('client_id','customers','name','',0,'',"analytics='1'") ;
	
	# $i{client_id} = ($i{client_id}) ? $i{client_id} : $db{$table}{$i{id}}{client_id} ;
	
	$opts{client_id} =~ s/value="\Q$i{client_id}\E"/value="$i{client_id}" SELECTED/g if $i{client_id} ;
	
	my %radio_opts_hash = (1 => "standard",2 => "premium",3 => "individuals") ; 
	
	$opts{credit_type} = "<option " . join("/option><option ",map {"value='$_'>" . ucfirst $radio_opts_hash{$_} . "<"} sort { $a <=> $b } keys %radio_opts_hash) . "/option>" ;
	
	# $i{credit_type} = $db{$table}{$i{id}}{credit_type} if $db{$table}{$i{id}}{credit_type} ;
	
	$opts{credit_type} =~ s/value='\Q$i{credit_type}\E'/value='$i{credit_type}' SELECTED/g if $i{credit_type} ;
	
} #------------------------------------------------------------------------------------------

sub thead {
	
	&common_min_thead ;
	# $print_thead = qq(<THEAD><TR><TH>ID</TH><TH>NAME</TH><TH>EXCLUDED FROM EXPENSES</TH><TH>&nbsp;</TH></TR></THEAD>) ;
		
} #-------------------------------------------------------------------------------

sub page_opts {

	our $glyphicon = 'facetime-video' ;
	our $lcpage    = 'allocate-credit
	' ; $ucpage = uc $lcpage ; $ucfirstpage = ucfirst $lcpage ;
	our $table     = 'credits_allocated' ;
	
	&common_min_add_extras ;

	our $savjqy = 1 ;

} #-------------------------------------------------------------------------------

use common ;
use today ;

1;