package CLMApp::Controller::DistributorWarehouse;
use Mojo::Base 'Mojolicious::Controller';
use Data::Show;
use Moose;
use Moose::Autobox;
use Perl6::Junction qw/any/;
use Data::Show;
use JSON;
use Cwd;
use Digest::MD5 qw(md5 md5_hex md5_base64);
use Digest::SHA1  qw(sha1 sha1_hex sha1_base64);
use Storable 'dclone';

use Class::Tiny qw//, {
	title => 'Distributor Warehouse',
	table => 'DistributorWarehouse',
	module => 'distributorwarehouse',
	pk => 'distributorwarehouseid',
	columns => [qw//],
	prefetch => [qw/distributor/],
	order_by => ['me.distributorwarehousename']
};

sub index{
	my $c = shift;
	$c->stash(frm => undef,butt => undef);
	$c->stash(title=> $c->title(),table => $c->module() . 'table' ,module=> $c->module());


	$c->render(template => 'customer/index');
}

sub read {
	my $c = shift;
	
	# show $c->{form};
	my $p = $c->req->params->to_hash;
	if($c->stash($c->pk) eq 'add'){
		return $c->add();
	};
	my @c = $c->db->resultset($c->table)->search({$c->pk=>$c->stash($c->pk)}, 
		{result_class=>'DBIx::Class::ResultClass::HashRefInflator'}
		) or return $c->render(text => 'Record not found.', status => 405);
	# my @c =  [ $c->db->resultset($c->table)->find({$c->pk=>$c->stash($c->pk)})->distributor ]->map(sub {
	# 		my %c = $_->get_columns;
	# 		return \%c;
	# 	});

	my ($frm,$butt) = $c->populate_form('default',$c[0]);

	$c->stash(frm => $frm);
	$c->stash(butt => $butt);

	$c->render(template => 'customer/edit');
	# $c->render(json => $c[0]);
}

sub add{
	my $c = shift;
	my $p = $c->req->params->to_hash;

	my ($frm,$butt) = $c->populate_form('add', $p);

	$c->stash(frm => $frm);
	$c->stash(butt => $butt);

	$c->render(template => 'customer/edit');

}

sub create {
	my $c = shift;
	my $j = $c->req->params->to_hash;
	delete($j->{$c->pk});
	delete($j->{distributorwarehouses});
	my $s = $c->db->resultset($c->table)->create($j);
	my $pk = $c->pk;
	my %p = $c->db->resultset($c->table)->find({$c->pk() => $s->$pk})->get_columns;
	$c->render(json => \%p);
}

sub list {
	my $c = shift;
	$c->req->param('columns[12][search][value]', undef); 
	my $p = $c->req->params->to_hash;
	my $excols = shift;


	my $cols = [qw/distributorwarehouseid distributorcompanyid parentid distributorwarehouseamphireid distributorwarehousename distributorlocid siteshortname bplocationid cityname state address zip countrycode latitude longitude active psmactive clmactive arrowstreamid arrowstreamname dadcode/];

	if($p->{export}){
		$cols = [qw/distributor.distributoramphireid distributorwarehouseamphireid distributorwarehousename distributorlocid bplocationid cityname state address zip countrycode siteshortname latitude longitude arrowstreamid arrowstreamname dadcode/];	
		if($excols){
			$cols = $excols;
		}

	}

	my $prefetch = ['distributor'];
	show $p;

	my $jobj = $c->dtsearch({prefetch => $prefetch, params => $p, table=> $c->table, order_by => $c->order_by, sort => 'desc', group_by => [$c->pk], columns => $cols, eheaders => 1}); # sep_char => ',', ext => 'csv', quote_char => '"'
	return 1 if $jobj == 1;

	$c->render(json => $jobj);
}

sub update{
	my $c = shift;
	my $j = $c->req->params->to_hash;
	delete($j->{distributorwarehouses});
	if($j->{single}){
		$j->{active} = 0 if !exists($j->{active});
		delete($j->{single});
	}else{	
		my $a = join(", ", ($j->{address}, $j->{cityname}, $j->{state}, $j->{zip}) );
		($j->{latitude},$j->{longitude}) = $c->gpslatlon($a);
	}

	my %c = $c->db->resultset($c->table)->find({ $c->pk() => $c->stash($c->pk) })->update($j)->get_columns or return $c->render(text => 'Record not found or cannot update.', status => 405);	
	$c->render(json=>\%c);
}

sub delete{
  my $c = shift;
  my($id) = ($c->stash($c->pk) || $c->param($c->pk));
  $c->db->resultset($c->table)->search({$c->pk() => $id})->delete();
  $c->render(json=>{$c->pk=>$id});
}

sub report{
	my $c = shift;

	$c->stash(frm => undef,butt => undef);
	$c->stash(title=> 'Report ' . $c->title(),table => $c->module() . 'table' ,module=> $c->module());


	$c->render(template => 'customer/report');
}

sub report_gps {
	my $c = shift;

	$c->req->param('ssearch', {
		'-or' => [
		'me.longitude' => ["-or" => [
			{ '=' => 0  },
			{ '=' => ""  },
			{ '=' => undef  }
		]],
		'me.latitude' => ["-or" => [
			{ '=' => 0  },
			{ '=' => ""  },
			{ '=' => undef  }
		]],
		],
		'me.active' => 1,
		'distributor.active' => 1
	});


	my $p = $c->req->params->to_hash;
	$c->list($p);
}



sub report_all {
	my $c = shift;
	my $p = $c->req->params->to_hash;
	$c->req->param('ssearch', {
		'distributor.active' => 1,
		'me.active' => 1
	});
# show $c->req->param('ssearch');


	return $c->list();
}


sub report_latlng{

	my $c = shift;
	$c->req->param('ssearch', {
		'distributor.active' => 1,
		'me.active' => 1,
		'me.clmactive' => 1
	});
	my $p = $c->req->params->to_hash;


	$p->{export} = 1;
	$p->{csv} = 1;
	$p->{csv_seperator} = "\t";

	my $cols = [qw/distributorwarehouseamphireid siteshortname address cityname state zip countrycode latitude longitude/];

#	my $excols = [qw/distributorwarehouseamphireid siteshortname warehouseaddress latitude longitude/];
my $excols = [qw/distributorwarehouseamphireid siteshortname bplocationid address cityname state zip countrycode latitude longitude/];
	my $join = [qw/distributor/];
	my $prefetch = [];
	my $ecols = [qw/warehouseaddress/];
	my $select = [{'CONCAT' => ['address','", "','cityname','", "','state','" "','zip','" "','countrycode'], '-as' => 'warehouseaddress' }];
	my $as = [qw/warehouseaddress/];
	my $dt =  DateTime->now(time_zone  => 'America/Chicago');


	my $jobj = $c->dtsearch({columns => $cols, excolumns => $excols, ecols => $ecols, join => $join, params => $p, table=> 'DistributorWarehouse', order_by => 'me.siteshortname', sort => 'asc', group_by => undef, select => $select, as => $as, prefetch => $prefetch, defer => 1, filename => 'DC_LOC.TXT'});
	
	return 1 if $jobj == 1;

	$c->render(json => $jobj);




}


sub setup{
	my $c = shift;


	my $fform = {
		attrs => {
			name => 'distributorwarehouseform',
			onsubmit => 'javascript: return false;',
			title => '',
			action => '',
			method => 'POST',
			formon => 'form-always',
			formoff => 'form-never',
			cols => 2,
			autocomplete=>"new-password"
		},
		sorder => [],
		eorder => [qw/active distributorwarehouseid distributorcompanyid distributorwarehouseamphireid distributorwarehousename distributorlocid siteshortname bplocationid spacer  spacer address cityname state zip countrycode arrowstreamid arrowstreamname dadcode latitude longitude clmactive psmactive/],
		elems =>     {
			empty => { attrs =>{ name => 'empty'}, type => 'empty' },
			dadcode => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "dadcode",
			                 # required => "required",
			               },
			      title => "Distributor Assigned DC Code",
			      type => "textfield",
			      val => undef,
			},
			clmactive => {
			      attrs => { class => "", name => "clmactive" },
				  labels => ['Enabled','Disabled'],			      
				  title => "CLM Active",
			      type => "radiogroup",
			      vals => [1,0],
			      default => undef
			},
			psmactive => {
			      attrs => { class => "", name => "psmactive" },
				  labels => ['Enabled','Disabled'],			      
				  title => "PSM Active",
			      type => "radiogroup",
			      vals => [1,0],
			      default => undef
			},						
			active => {
			      attrs => { class => "", name => "active" },
				  labels => ['Enabled','Disabled'],			      
				  title => "ITN Active",
			      type => "radiogroup",
			      vals => [1,0],
			      default => undef
			},			
			distributorwarehouseid => {
			      attrs => { class => "form-control input-md", name => "distributorwarehouseid" },
			      title => "ID",
			      type => "hidden",
			      val => undef,
			},
			distributorcompanyid => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "distributorcompanyid",
			                    required => "required",
			                  },
			      default => undef,
			      labels => [],
			      # populate => {
			      #               defaults => "distributorcompany",
			      #               labels => "name",
			      #               vals => "distributorcompanyid",
			      #             },
			      populate => {
			                    # defaults => "user",
			                    defaults => {
			                    	module => "DistributorCompany",
			                    	options => {
						                prefetch => [],			                    		
			                    		order_by => "name"
			                    	},
			                    	# fk => 'id',
			                    	where => [qw/active/],
			                    	vals => [1],
			                    },			                    
			                    labels => 'name',
			                    # sub {
			                    # 	my ($el,$dv) = (@_);
			                    # 	return sprintf("%s - %s %s - %s", $dv->{iacctnmbr} || 'N/A', $dv->{fname}, $dv->{lname}, $dv->{company});
			                    # },
			                    vals => "distributorcompanyid",
			                    data => [qw//]
			                  },			      
			      title => "Distributor",
			      type => "select",
			      vals => [],
			    },			
			parentid => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "parentid",
			                 required => "required",
			               },
			      title => "Distributor",
			      type => "textfield",
			      val => undef,
			},			
			distributorwarehouseamphireid => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "distributorwarehouseamphireid",
			                 required => "required",
			               },
			      title => "DCSiteID",
			      type => "textfield",
			      val => undef,
			},
			arrowstreamid => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "arrowstreamid",
			                 required => "required",
			               },
			      title => "AS ID",
			      type => "textfield",
			      val => undef,
			},
			arrowstreamname => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "arrowstreamname",
			                 # required => "required",
			               },
			      title => "AS Partner Abbrv",
			      type => "textfield",
			      val => undef,
			},


			distributorwarehousename => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "distributorwarehousename",
			                 required => "required",
			               },
			      title => "Name",
			      type => "textfield",
			      val => undef,
			},
			distributorlocid => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "distributorlocid",
			                 required => "required",
			               },
			      title => "DCCode (LocID)",
			      type => "textfield",
			      val => undef,
			},
			siteshortname => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "siteshortname",
			                 required => "required",
			               },
			      title => "Site Short Name",
			      type => "textfield",
			      val => undef,
			},			
			cityname => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "cityname",
			                 required => "required",
			               },
			      title => "City",
			      type => "textfield",
			      val => undef,
			},
			state => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "state",
			                 required => "required",
			               },
			      title => "State",
			      type => "textfield",
			      val => undef,
			},
			address => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "address",
			                 required => "required",
			               },
			      title => "Address",
			      type => "textfield",
			      val => undef,
			},
			zip => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "zip",
			                 required => "required",
			               },
			      title => "Zip",
			      type => "textfield",
			      val => undef,
			},
			latitude => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "latitude",
			                 required => "required",
			               },
			      title => "Lat.",
			      type => "readonly",
			      val => undef,
			},
			longitude => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "longitude",
			                 required => "required",
			               },
			      title => "Lon.",
			      type => "readonly",
			      val => undef,
			},
			# countrycode => {
			#       attrs => {
			#                     class => "input-md form-control",
			#                     name => "countrycode",
			#                     required => "required",
			#                   },
			#       default => undef,
			#       labels => [],
			#       populate => { defaults => "country", labels => "displayname", vals => "countrycode" },
			#       title => "Country",
			#       type => "select",
			#       vals => [],
			# },
			countrycode => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "countrycode",
			                    required => "required",
			                  },
			      default => 'USA-United States',
			      labels => [],
			      # populate => {
			      #               defaults => "chaingroup",
			      #               labels => "chaingroupname",
			      #               vals => "chaingroupid",
			      #               data => ['chaingroupvp','chaingrouppam']
			      #             },
			      populate => {
			                    # defaults => "user",
			                    defaults => {
			                    	module => "Country",
			                    	options => {
						                prefetch => [],			                    		
			                    		order_by => "displayname"
			                    	},

			                    	# fk => 'id',
			                    	where => [qw//],
			                    	vals => [],			                    	

			                    },			                    
			                    labels => 'displayname',
			                    # sub {
			                    # 	my ($el,$dv) = (@_);
			                    # 	return sprintf("%s - %s %s - %s", $dv->{iacctnmbr} || 'N/A', $dv->{fname}, $dv->{lname}, $dv->{company});
			                    # },
			                    vals => "countrycode",
			                    data => [],
			                  },			      
			      title => "Country",
			      type => "select",
			      vals => [],
			      data => []
			    },				
			bplocationid => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "bplocationid",
			               },
			      title => "BP Location ID",
			      type => "textfield",
			      val => undef,
			},
			spacer => {
				attrs => { name => 'spacer'}, type => 'spacer'
			}		
    	},
	};

	my $aform = dclone $fform;
	$aform->{attrs}->{name} = $c->module() . 'addform';
	$aform->{attrs}->{formon} = 'form-always';
	$aform->{attrs}->{formoff} = 'form-never';

	$c->{_forms}->{default} = $c->form($fform);
	$c->{_forms}->{add} = $c->form($aform);

	$c->{_buttongroup}->{add} = $c->form([
			{
				type => 'buttongroup',
				attrs => [{
					class => 'btn btn-success',
					name => 'add',
					type => 'button'
				},					
				],
				labels => ["Add Record"],
			},
	]);



	$c->{_buttongroup}->{default} = $c->form([
			# {
			# 	type => 'buttongroup',
			# 	class => 'form-never',
			# 	attrs => [{
			# 		class => 'btn btn-warning form-never',
			# 		name => 'edit',
			# 		type => 'button'
			# 	},	
			# 	{
			# 		class => 'btn btn-danger form-never',
			# 		name => 'delete',
			# 		type => 'button'
			# 	},							
			# 	],
			# 	labels => ["Edit","Delete"],
			# 	# vals => [qw/save reset/],
			# },		
		    {
				type => 'buttongroup',
				class => 'form-always',
				attrs => [{
					class => 'btn btn-success',
					name => 'save',
					type => 'button'
				},
				{
					class => 'btn btn-default ',
					name => 'close',
					type => 'button',
					'data-dismiss' => 'modal'
				},
				{
					class => 'btn btn-danger',
					name => 'delete',
					type => 'button'
				},				
				],
				labels => ["Save","Close","Delete"],
				# vals => [qw/save reset/],
			},

	]);

}

1;
