package CLMApp::Controller::EmailNotification;
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 => 'Email Notification Triggers',
	table => 'EmailNotification',
	module => 'emailnotification',
	pk => 'emailnotificationid',
	columns => [qw/active emailnotificationid name actiontype chaingroupid chainconceptid distributorcompanyid distributorwarehouseid systemid targetlist precode postcode subject body deleted/],
	prefetch => [qw//],
	order_by => ['me.emailnotificationid']
};

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({'me.emailnotificationid'=>$c->stash($c->pk)}, 
		{prefetch => [qw/email_notification_warehouses/], 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;
	# 	});


show $c[0];
	$c[0]->{distributorwarehouseid} = [];
	foreach my $w (@{$c[0]->{email_notification_warehouses}}){
		push(@{ $c[0]->{distributorwarehouseid}   }, $w->{distributorwarehouseid});
	}

	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 ($frm,$butt) = $c->populate_form('add');

	$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});
	$j->{chaingroupid} ||= 0;
	$j->{chainconceptid} ||= 0;
	$j->{distributorcompanyid} ||= 0;
	$j->{systemid} ||= 0;
	my $distributorwarehouseid = $j->{distributorwarehouseid};
	$j->{distributorwarehouseid} = 0;





	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;


	if(ref($distributorwarehouseid) eq 'ARRAY'){
		$c->db->resultset('EmailNotificationWarehouse')->search({emailnotificationid => $p{emailnotificationid} })->delete;
		foreach my $wid (@$distributorwarehouseid){
			$c->db->resultset('EmailNotificationWarehouse')->create({ emailnotificationid => $p{emailnotificationid}, distributorwarehouseid => $wid});
		}
	}else{
		$c->db->resultset('EmailNotificationWarehouse')->search({emailnotificationid => $p{emailnotificationid}})->delete;
		if($distributorwarehouseid){
			$c->db->resultset('EmailNotificationWarehouse')->create({ emailnotificationid => $p{emailnotificationid}, distributorwarehouseid => $distributorwarehouseid});
		}
	}


	$c->render(json => \%p);
}

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

	my $cols = [qw/active emailnotificationid name actiontype chaingroupid chainconceptid distributorcompanyid distributorwarehouseid systemid targetlist precode postcode subject body deleted/];

	my $jobj = $c->dtsearch({params => $p, table=> $c->table, order_by => $c->order_by, sort => 'desc', group_by => [$c->pk], columns => $cols});
	return 1 if $jobj == 1;

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

sub update{	

	my $c = shift;
	my $j = $c->req->params->to_hash;


	if($j->{single}){
		$j->{active} = 0 if !exists($j->{active});
		delete($j->{single});

		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);	
		return $c->render(json=>\%c);
	}	


show $j;
	$j->{chaingroupid} ||= 0;
	$j->{chainconceptid} ||= 0;
	$j->{distributorcompanyid} ||= 0;
	$j->{distributorwarehouseid} ||= 0;
	$j->{systemid} ||= 0;

	if(ref($j->{distributorwarehouseid}) eq 'ARRAY'){

		$c->db->resultset('EmailNotificationWarehouse')->search({emailnotificationid => $c->stash($c->pk)})->delete;
		foreach my $wid (@{$j->{distributorwarehouseid}}){
			$c->db->resultset('EmailNotificationWarehouse')->create({ emailnotificationid => $c->stash($c->pk), distributorwarehouseid => $wid});
		}
		delete($j->{distributorwarehouseid});
	}elsif($j->{distributorwarehouseid}){

		$c->db->resultset('EmailNotificationWarehouse')->search({emailnotificationid => $c->stash($c->pk)})->delete;
		$c->db->resultset('EmailNotificationWarehouse')->create({ emailnotificationid => $c->stash($c->pk), distributorwarehouseid => $j->{distributorwarehouseid}});
		delete($j->{distributorwarehouseid});
	}else{
		$c->db->resultset('EmailNotificationWarehouse')->search({emailnotificationid => $c->stash($c->pk)})->delete;
	}


	if($j->{single}){
		$j->{active} = 0 if !exists($j->{active});
		delete($j->{single});
	}	

	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->param($c->pk));
  $c->db->resultset($c->table)->search({$c->pk() => $id})->delete();
  $c->render(json=>{$c->pk=>$id});
}

sub template{

	my $c = shift;
	my $template = $c->req->param('template');
	my $rtemplate;

	if($template eq 'EMAIL_ON_ADD'){
		$rtemplate = q~
<P>New account(s) have been added.  Your ids are listed below, please update your system accordingly.</P><P><BR></P><P>


<table width="100%" border="1">
<thead>
	<tr>
		<th>COMPANY</th>
		<th>STORE#</th>
		<th>DISTRIBUTOR</th>
		<th>DIST CUSTOMER NBR</th>
		<th>WAREHOUSE ID</th>
		<th>AMPHIRE ID</th>	
	</tr>
</thead>
<tbody>
<% foreach my $r (@$customers){ %>
	<tr>
		<td><%= $r->{chaingrp}->{chaingroupname} %></td>
		<td><%= $r->{customerunitnumber} %></td>
		<td><%= $r->{distributor}->{name} %></td>
		<td><%= $r->{customernumber} %></td>
		<td><%= $r->{warehouse}->{distributorwarehouseamphireid} %></td>
		<td><%= $r->{amphireid} %></td>
	</tr>
<% } %>	
</tbody>
</table>



<P>If you have any questions or need to be removed from the distribution list, please contact:</P><P>Jenisse Hernandez<BR>Direct: 847.252.1967<BR><A HREF="MAILTO:matt.kot@dmadelivers.com">matt.kot@dmadelivers.com</A><BR></P><DIV><BR></DIV>


		~;

	}elsif($template eq 'EMAIL_ON_ADD_BP_MIGRATE' || $template eq 'EMAIL_TEMPLATE'){


	$rtemplate = q~
<P>New Branded Procurement (BP) account(s) have been added. The user name and passwords are listed below.</P><P><BR></P>

<table width="100%" border="1">
<thead>
	<tr>
		<th>COMPANY</th>
		<th>STORE#</th>
		<th>DISTRIBUTOR WAREHOUSE</th>
		<th>OWNERSHIP</th>
		<th>USERNAME</th>
		<th>PASSWORD</th>	
	</tr>
</thead>
<tbody>
<% foreach my $r (@$customers){ %>
	<tr>
		<td><%= $r->{chaingrp}->{chaingroupname} %></td>
		<td><%= $r->{customerunitnumber} %></td>
		<td><%= $r->{warehouse}->{siteshortname} %></td>
		<td><%= $r->{ownership} ? $r->{ownership} : 'N/A' %></td>
		<td><%= $r->{user} %></td>
		<td><%= $r->{user} %></td>
	</tr>
<% } %>	
</tbody>
</table>



<P>If you have any questions or need to be removed from the distribution list, please contact:</P><P>Jenisse Hernandez<BR>Direct: 847.252.1967<BR><A HREF="MAILTO:matt.kot@dmadelivers.com">matt.kot@dmadelivers.com</A><BR></P><DIV><BR></DIV>





	~;



	}


	$c->render(text => $rtemplate);

}



sub setup{
	my $c = shift;


	my $fform = {
		attrs => {
			name => 'emailnotificationform',
			onsubmit => 'javascript: return false;',
			title => '',
			action => '',
			method => 'POST',
			formon => 'form-always',
			formoff => 'form-never',
			cols => 1,
			autocomplete=>"new-password"
		},
		sorder => [],
		eorder => [qw/active emailnotificationid name actiontype chaingroupid chainconceptid distributorcompanyid distributorwarehouseid  targetlist precode postcode subject body  deleted/],
		elems =>     {

			active => {
			      attrs => { class => "", name => "active" },
				  labels => ['Enabled'],			      
				  title => "Active",
			      type => "checkbox",
			      vals => [1],
			      default => undef
			},	
			deleted => {
			      attrs => { class => "form-control input-md", name => "deleted" },
			      title => "Deleted",
			      type => "hidden",
			      val => 0,
			},					
			emailnotificationid => {
			      attrs => { class => "form-control input-md", name => "emailnotificationid" },
			      title => "ID",
			      type => "hidden",
			      val => undef,
			},
			name => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "name",
			                 required => "required",
			               },
			      title => "Notice Name",
			      type => "textfield",
			      val => undef,
			},
			subject => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "subject",
			                 # required => "required",
			               },
			      title => "Email Subject",
			      type => "textfield",
			      val => undef,
			},
			body => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "body",
			                 style => "text-transform: none;",
			                 # required => "required",
			               },
			      title => "Email Body",
			      type => "textarea",
			      val => undef,
			},	
systemid => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "systemid",
			                  },
			      # defaults => [],
			      default => undef,
			      labels => [],
			      # populate => {
			      #               defaults => "backofficesystem",
			      #               labels => "systemname",
			      #               vals => "systemid",
			      #             },
			      populate => {
			                    defaults => {
			                    	module => "BackOfficeSystem",
			                    	options => {
						                prefetch => [qw//],	                    		
			                    		order_by => "systemname"
			                    	},
			                    	# fk => 'id',
			                    	where => [qw/active/],
			                    	vals => [1],
			                    },			                    
			                    labels => 'systemname',
			                    vals => "systemid",
			                    # data => ["chaingroupid"]
				   },	
			      title => "Backoffice System(s)",
			      type => "select",
			      vals => [],
			    },							
			targetlist => {
			      attrs =>  { class => "form-control input-md tagstextarea", name => "targetlist",  'data-role' => "tagsinput" },
			      title => "Target List",
			      type => "textarea",
			      val => undef,
			},			
			actiontype => {
			      attrs => { class => "form-control input-md", name => "actiontype", required => "required" },
			      default => undef,
			      labels => ["Email On Add New","Email on BP Add or Migrate BP","Email Template"],
			      title => "Trigger Action", 
			      type => "select",
			      vals => [qw/EMAIL_ON_ADD EMAIL_ON_ADD_BP_MIGRATE EMAIL_TEMPLATE/],
			},			
			chainconceptid => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "chainconceptid",
			                  },
			      default => undef,
			      labels => [],
			      populate => {
			                    defaults => {
			                    	module => "ChainConcept",
			                    	options => {
						                prefetch => [qw/chaingrp/],	                    		
			                    		order_by => "chainconceptname"
			                    	},
			                    	# fk => 'id',
			                    	where => [qw/me.active chaingrp.active/],
			                    	vals => [1,1],
			                    },			                    
			                    labels => 'chainconceptname',
			                    vals => "chainconceptid",
			                    data => ["chaingroupid"]
			                  },				                  
			      title => "Chain Concept",
			      type => "select",
			      vals => [],
			      data => [],
			},
						chaingroupid => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "chaingroupid",
			                  },
			      default => undef,
			      labels => [],
			      # populate => {
			      #               defaults => "chaingroup",
			      #               labels => "chaingroupname",
			      #               vals => "chaingroupid",
			      #               data => ['chaingroupvp','chaingrouppam']
			      #             },
			      populate => {
			                    # defaults => "user",
			                    defaults => {
			                    	module => "ChainGroup",
			                    	options => {
						                prefetch => [],			                    		
			                    		order_by => "chaingroupname"
			                    	},

			                    	# fk => 'id',
			                    	where => [qw/me.active/],
			                    	vals => [1],		                    	

			                    },			                    
			                    labels => 'chaingroupname',
			                    # sub {
			                    # 	my ($el,$dv) = (@_);
			                    # 	return sprintf("%s - %s %s - %s", $dv->{iacctnmbr} || 'N/A', $dv->{fname}, $dv->{lname}, $dv->{company});
			                    # },
			                    vals => "chaingroupid",
			                    data => ['chaingroupvp','chaingrouppam'],
			                  },			      
			      title => "Chain",
			      type => "select",
			      vals => [],
			      data => []
			    },
				distributorcompanyid => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "distributorcompanyid",
			                  },
			      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/me.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 => [],
			    },
			distributorwarehouseid => {
			      attrs => {
			                    class => "input-md form-control selectpicker",
			                    name => "distributorwarehouseid",
			                    multiple => 'multiple'
			                  },
			      defaults => [],
			      labels => [],
			      # populate => {
			      #               defaults => "distributorwarehouse",
			      #               labels => "distributorwarehousename",
			      #               vals => "distributorwarehouseid",
			      #               data => ["distributorcompanyid"]
			      #             },
			      populate => {
			                    # defaults => "user",
			                    defaults => {
			                    	module => "DistributorWarehouse",
			                    	options => {
						                prefetch => [qw/distributor/],			                    		
			                    		order_by => "distributorwarehousename"
			                    	},
			                    	# fk => 'id',
			                    	where => [qw/me.active/],
			                    	vals => [1],
			                    },			                    
			                    labels => 'distributorwarehousename',
			                    # sub {
			                    # 	my ($el,$dv) = (@_);
			                    # 	return sprintf("%s - %s %s - %s", $dv->{iacctnmbr} || 'N/A', $dv->{fname}, $dv->{lname}, $dv->{company});
			                    # },
			                    vals => "distributorwarehouseid",
			                    data => [qw/distributorcompanyid/]
			                  },			                  
			      title => "Warehouse",
			      type => "select",
			      vals => [],
			      data => []
			    },			    
    	},
	};

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

	$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;


1;