package CLMApp::Controller::ChainUnit;
use strict;
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 => 'Chain Units',
	table => 'ChainUnit',
	module => 'chainunit',
	pk => 'chainunitid',
	columns => [qw/active chainunitid chainunitname chaingroupid chainconceptid/],
	prefetch => [qw/chaingrp chaincncpt customer/],
	order_by => ['me.chainunitname']
};
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->{chaingroupid}) if $j->{chaingroupid} == "";
	delete($j->{chainconceptid}) if $j->{chainconceptid} == "";
	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;
	my $p = $c->req->params->to_hash;

	my $as =  [qw/customernumber/];
	my $select = [{ 'GROUP_CONCAT' => 'customer.customernumber', -as => 'customernumber'  }
	];


	my $jobj = $c->dtsearch({as => $as, select => $select, prefetch => $c->prefetch, params => $p, table=> $c->table, order_by => $c->order_by, sort => 'desc', group_by => [$c->pk], columns => $c->columns});
	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);	
	$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',table => $c->module() . 'table' ,module => $c->module);


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

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


	my @res = $c->db->resultset('ChainUnit')->search({'me.active' => 1, 'customer.statusid' => 1},{
			prefetch => [qw/customer chaingrp chaincncpt/], 
			result_class=>'DBIx::Class::ResultClass::HashRefInflator',
	});

	my @data;
	foreach my $r (@res){
		my $cn = $r->{chainunitname};
		my $scn = $r->{customer}->{unitname} . ($r->{customer}->{customerunitnumber} ? ' ' . $r->{customer}->{customerunitnumber} : '');
		if($cn ne $scn){
			push(@data, $r->{customer});
		}
	}

	my $json = {
		"data" => \@data,
		"draw" => "1",
		"header" =>  [
			"active",
			"chainunitid",
			"chainunitname",
			"chaingroupid",
			"chainconceptid"
		],
		"recordsFiltered" =>  scalar(@data),
		"recordsTotal" =>  scalar(@data)
	};

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

}

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


	my $cols = [qw/active chainunitid chainunitname chaingroupid chainconceptid/];
	my $join = [qw/customer chaingrp chaincncpt/];
	my $prefetch = [qw/customer chaingrp chaincncpt/];
	#  'concept' => 'back_office_system_chain_concepts'
	my $as =  [qw/customerid/];
	my $select = [{ 'COUNT' => 'customer.customerid', -as => 'customerid'  }
	];
	my $ecols;
	my $having = \[ 'COUNT(customer.customerid) = 0' ];

	my $jobj = $c->dtsearch({as => $as, select => $select, ecols => $ecols, join => $join, params => $p, table=> $c->table, order_by => $p->{order_by} || 'me.chainunitid', sort => 'desc', group_by => [qw/me.chainunitid/], having => $having, columns => $cols, prefetch => $prefetch, defer => $having ? 0 : 1});

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

	return 1 if $jobj == 1;

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

sub report_unassigned{

	my $c = shift;

#	select * from ChainUnit where ChainGroupId=0 OR ChainConceptId=0;
	my $cols = [qw/active chainunitid chainunitname chaingroupid chainconceptid/];
	my $join = [qw/customer chaingrp chaincncpt/];
	my $prefetch = [qw/customer chaingrp chaincncpt/];
	#  'concept' => 'back_office_system_chain_concepts'
	my $p = $c->req->params->to_hash;
	$p->{ssearch} = {
		'-or' => [
			'me.chainconceptid' => 0,
			'me.chaingroupid' => 0
		],
	};
	
	

	# my $as =  [qw/customerid/];
	# my $select = [{ 'COUNT' => 'customer.customerid', -as => 'customerid'  }];
	my $ecols;
	#my $having = \[ 'COUNT(customer.customerid) = 0' ];

	my $jobj = $c->dtsearch({
		# as => $as, 
		# select => $select, 
		# ecols => $ecols,

	 join => $join, params => $p, table=> $c->table, order_by => $p->{order_by} || 'me.chainunitid', sort => 'desc', group_by => [qw/me.chainunitid/], 
	 #having => $having, 
	 columns => $cols, prefetch => $prefetch, 
	#	defer => $having ? 0 : 1
	});

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

	return 1 if $jobj == 1;

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




}


sub bulk_deactivate{

	my $c = shift;

	my @res = $c->db->resultset('ChainUnit')->search({'me.active' => 1, 'customer.brandedprocurement' => 1},{
			join => [qw/customer/], 
			result_class=>'DBIx::Class::ResultClass::HashRefInflator',
			# '+select' => [{'COUNT' => 'customer.customerid'},{'SUM' => 'customer.statusid'}],
			# '+as' => [qw/customercnt sumstatus/],
			group_by => 'chainunitid',
			having => \'SUM(customer.statusid) % 2 = 0'
	});


	my @reset;
	foreach my $r (@res){


		my $cnt = $c->db->resultset('Customer')->search({'me.chainunitid' => $r->{chainunitid}, 'me.statusid' => 1})->count;
		if($cnt == 0){
			$c->db->resultset('ChainUnit')->find({'chainunitid' => $r->{chainunitid} })->update({active => 0});

			push(@reset, $r);
		}
	}
	show scalar(@reset);


	$c->render(json => \@reset);


}


sub setup{
	my $c = shift;


	my $fform = {
		attrs => {
			name => 'chainunitform',
			onsubmit => 'javascript: return false;',
			title => '',
			action => '',
			method => 'POST',
			formon => 'form-always',
			formoff => 'form-never',
			cols => 1,
			autocomplete=>"new-password"
		},
		sorder => [],
		eorder => [qw/active chainunitid chaingroupid chainconceptid chainunitname/],
		elems =>     {
			active => {
			      attrs => { class => "", name => "active" },
				  labels => ['Enabled'],			      
				  title => "Active",
			      type => "checkbox",
			      vals => [1],
			      default => undef
			},			
			chainunitid => {
			      attrs => { class => "form-control input-md", name => "chainunitid" },
			      title => "ID",
			      type => "readonly",
			      val => undef,
			},
			chainunitname => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "chainunitname",
			                 required => "required",
			               },
			      title => "Chain Unit",
			      type => "textfield",
			      val => undef,
			},			
			chainunitamphireid => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "chainunitamphireid",
			                 required => "required",
			               },
			      title => "ITN ID",
			      type => "textfield",
			      val => undef,
			},
			parentid => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "parentid",
			                 required => "required",
			               },
			      title => "Group",
			      type => "textfield",
			      val => undef,
			},
			chaingroupid => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "chaingroupid",
			                    # required => "required",
			                  },
			      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/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 Group",
			      type => "select",
			      vals => [],
			      data => []
			    },	
			chainconceptid => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "chainconceptid",
			                    # required => "required",
			                  },
			      default => undef,
			      labels => [],
			      populate => {
			                    defaults => {
			                    	module => "ChainConcept",
			                    	options => {
						                prefetch => [],			                    		
			                    		order_by => "chainconceptname"
			                    	},
			                    	# fk => 'id',
			                    	where => [qw/active/],
			                    	vals => [1],
			                    },			                    
			                    labels => 'chainconceptname',
			                    vals => "chainconceptid",
			                    data => ["chaingroupid"]
			                  },				                  
			      title => "Chain Concept",
			      type => "select",
			      vals => [],
			      data => [],
			    },			    		
    	},
	};

	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;
