package CLMApp::Controller::BackOfficeSystem;
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';
$Storable::Deparse = 1;
$Storable::Eval = 1;

use Class::Tiny qw//, {
	title => 'Back Office Systems',
	table => 'BackOfficeSystem',
	module => 'backofficesystem',
	pk => 'systemid',
	columns => [qw/systemid systemname active description chaingroupamphireid/],
	prefetch => [qw//],
	order_by => ['me.systemid']

};

sub migrate{

	my $c = shift;
	my $systemid = $c->stash('systemid');

	my @s = $c->db->resultset('BackOfficeSystemCustomer')->search({'me.systemid' => $systemid},{
		'+select' => [{'GROUP_CONCAT' => 'me.customerid', '-as' => 'customerids'}],
		'+as' => [qw/customerids/],
		# prefetch => [qw/customer_related/],
		group_by => [qw/me.systemid/],
		result_class=>'DBIx::Class::ResultClass::HashRefInflator'
	}); 

	show @s;
	my @customerids = split(',', $s[0]->{customerids});
	show scalar(@customerids);
	my $cnt = $c->db->resultset('Customer')->search({'me.customerid' => { 'IN' => \@customerids }})->count;

#
	$c->db->resultset('Customer')->search({'me.customerid' => { 'IN' => \@customerids }})->update({brandedprocurement => 1});


	

	$c->render(text => "($cnt) Customers Migrated to BP");

}

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.". $c->pk =>$c->stash($c->pk)}, 
		{result_class=>'DBIx::Class::ResultClass::HashRefInflator'}
		) or return $c->render(text => 'Record not found.', status => 405);

# get related as arref
	$c[0]->{chainconceptid} = [$c->db->resultset($c->table)->search_related('back_office_system_chain_concepts', {"me.". $c->pk =>$c->stash($c->pk)})]->map(sub {
		my %r = $_[0]->get_columns;
		return $r{chainconceptid};
	});
	


	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 concept{
	my $c = shift;
	my $chainconceptid = $c->stash('chainconceptid');
	my @c = ();
	@c = $c->db->resultset('BackOfficeSystemChainConcept')->search({chainconceptid=>$chainconceptid}, 
		{result_class=>'DBIx::Class::ResultClass::HashRefInflator'}
		);

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

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});
	my $chainconceptid = $j->{chainconceptid}; 	delete($j->{chainconceptid});
	$j->{active} = 1;
	$j->{chaingroupid} ||= 0;
	show $j;
	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;
	my $backofficesystem =  $c->db->resultset($c->table)->find({ $c->pk() => $s->$pk });
	if($chainconceptid){
		my @chainconcepts = $c->db->resultset('ChainConcept')->search({ chainconceptid => { '-in' => $chainconceptid } }); # in ARRAY or STRING
		$backofficesystem->set_chainconcepts(\@chainconcepts);
	}
	


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

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

	my $cols = [qw/systemid systemname active description chaingroupamphireid/]; # chainconcept.chainconceptname
	# get prefetch and related?
	my $prefetch = [];
	my $ecols = {'chainconcept.chainconceptname' => \['GROUP_CONCAT(chainconcept.chainconceptname)'] };
	my $join = {'back_office_system_chain_concepts' => 'chainconcept',
		# 'back_office_system_customers' => 'customer'
	};
	my $group_by = [qw/me.systemid/];
	my $as =  [qw/chainconceptname/];
	my $select = { 'group_concat' => 'chainconcept.chainconceptname', -as => 'chainconceptname' };
	# my $join = [qw//];


	my $jobj = $c->dtsearch({
		select => $select, 
		# as => $as, 
		# ecolumns => $ecols, 
		join => $join, 
		prefetch => $prefetch, 
		group_by => $group_by, 
		columns => $cols,
		params => $p, table=> $c->table, order_by => $c->pk, sort => 'desc',});
	return 1 if $jobj == 1;

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

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

		# if(ref($j->{chainconceptamphireid}) eq 'ARRAY'){
		# 	$j->{chainconceptamphireid} = join(",", @{$j->{chainconceptamphireid}});
		# }
	my $bocc = { chainconceptid => $j->{chainconceptid},  systemid => $j->{systemid} };


# method one has_many

	# my $chainconceptid = ref($j->{chainconceptid}) ne 'ARRAY' ? [$j->{chainconceptid}] : $j->{chainconceptid};
	# $c->db->resultset($c->table)->find({ $c->pk() => $c->stash($c->pk) })->delete_related('back_office_system_chain_concepts');
	# foreach my $cid (@$chainconceptid}){
	# $c->db->resultset($c->table)->find({ $c->pk() => $c->stash($c->pk) })->create_related('back_office_system_chain_concepts', {chainconceptid => $cid });
	# }
show $j;
# method two many_to_many
	if($j->{single}){
		$j->{active} = 0 if !exists($j->{active});
		delete($j->{single});
	}else{

		my $backofficesystem =  $c->db->resultset($c->table)->find({ $c->pk() => $c->stash($c->pk) });
		if($j->{chainconceptid}){


			# $c->db->resultset($c->table)->find({ $c->pk() => $c->stash($c->pk) })->delete_related('back_office_system_chain_concepts');
	  		my @chainconcepts = $c->db->resultset('ChainConcept')->search({ chainconceptid => { '-in' => $j->{chainconceptid} } }); # in ARRAY or STRING
			$backofficesystem->set_chainconcepts(\@chainconcepts);
		}else{
			$c->db->resultset($c->table)->find({ $c->pk() => $c->stash($c->pk) })->delete_related('back_office_system_chain_concepts');
		}
	}

	delete($j->{chainconceptid});
show $j;

	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 setup{
	my $c = shift;


	my $fform = {
		attrs => {
			name => 'backofficesystemform',
			onsubmit => 'javascript: return false;',
			title => '',
			action => '',
			method => 'POST',
			formon => 'form-always',
			formoff => 'form-never',
			cols => 1,
			autocomplete=>"new-password"
		},
		sorder => [],
		eorder => [qw/systemid systemname chaingroupid chainconceptid description/],
		elems =>     {
			systemid => {
			      attrs => { class => "form-control input-md", name => "systemid" },
			      title => "ID",
			      type => "hidden",
			      val => undef,
			},
			systemname => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "systemname",
			                 required => "required",
			               },
			      title => "Sys. Name",
			      type => "textfield",
			      val => undef,
			},
			active => {
			      attrs => { class => "", name => "active" },
				  labels => ['Enabled'],			      
				  title => "Active",
			      type => "checkbox",
			      vals => [1],
			      default => 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 selectpicker",
			                    name => "chainconceptid",
			                    # required => "required",
			                  },
			      # default => undef,
			      labels => [],
			      defaults => [],
			      populate => {
			                    # defaults => "user",
			                    defaults => {
			                    	module => "ChainConcept",
			                    	options => {
						                prefetch => [],			                    		
			                    		order_by => "chainconceptname"
			                    	},

			                    	# fk => 'id',
			                    	where => [qw/active/],
			                    	vals => [1],
			                    },			                    
			                    labels => 'chainconceptname',
			                    # sub {
			                    # 	my ($el,$dv) = (@_);
			                    # 	return sprintf("%s - %s %s - %s", $dv->{iacctnmbr} || 'N/A', $dv->{fname}, $dv->{lname}, $dv->{company});
			                    # },
			                    vals => "chainconceptid",
			                    data => ["chaingroupid"]
			                  },				                  
			      title => "Chain Concept",
			      type => "selectpicker",
			      vals => [],
			      data => [],
			    },		
			description => {
			      attrs => {
			                 class => "form-control input-md",
			                 name => "description",
			                 # required => "required",
			               },
			      title => "Description",
			      type => "textarea",
			      val => undef,
			},									
    	},
	};

	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;
