package CLMApp::Controller::CustomerSystem;
use Mojo::Base 'Mojolicious::Controller';
use Data::Show;
use Moose;
use Moose::Autobox;
use Perl6::Junction qw/any/;
use Data::Show;
# use JSON;
use Mojo::JSON qw/encode_json decode_json/;
use strict;
use Cwd;
use Digest::MD5 qw(md5 md5_hex md5_base64);
use Digest::SHA1  qw(sha1 sha1_hex sha1_base64);
use Storable 'dclone';
use File::Basename;
$Storable::Deparse = 1;
$Storable::Eval = 1;

# use Class::Tiny qw//, {
# 	title => 'Customer System',
# 	table => 'CustomerSystem',
# 	module => 'customersystem',
# 	pk => 'customersystemid',
# 	columns => [qw/customersystemid customerid systemtype systemid systemfiles marketid accountingcode filecode active/],
# 	prefetch => [qw//],
# 	order_by => [qw/me.customersystemid/]
# };


our $defaults = {
	title => 'Customer System',
	table => 'CustomerSystem',
	module => 'customersystem',
	pk => 'customersystemid',
	columns => [qw/customersystemid customerid systemtype systemid systemfiles marketid accountingcode filecode active/],
	prefetch => [qw/ordersystems invoicesystems markets systems_customer/],
	order_by => [qw/me.customersystemid/]
};

sub title{ return $defaults->{title}; }
sub table{ return $defaults->{table}; }
sub module{ return $defaults->{module}; }
sub pk{ return $defaults->{pk}; }
sub columns{ return $defaults->{columns}; }
sub prefetch{ return $defaults->{prefetch}; }
sub order_by{ return $defaults->{order_by}; }
sub where_session{ my $c = shift; return $defaults->{where_session} ? $defaults->{where_session}->($c) : {}; }
sub sortd{ return $defaults->{sortd} || 'desc'; }


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;
	# 	});

	if($c[0]->{systemfiles} =~ /^"/){
			$c[0]->{systemfiles} =~ s/"//g;
			$c[0]->{systemfiles} = '["' . $c[0]->{systemfiles} .'"]';
	}
	show $c[0];
	$c[0]->{systemfiles} = $c[0]->{systemfiles} && $c[0]->{systemfiles} =~ /^\[/ ? decode_json($c[0]->{systemfiles}) : [];
	show $c[0];

	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->{created} = \'NOW()';
	$j->{updated} = \'NOW()';
	$j->{createdby} = $c->session->{user_id} || 1;
	$j->{updatedby} = $c->session->{user_id} || 1;	
	$j->{systemfiles} = $j->{systemfiles} ? encode_json($j->{systemfiles})  : encode_json([]); 

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

sub list {
	my $c = shift;



	# $c->request->param("columns[8][data]" => "deleted");
	# $c->request->param("columns[8][search][value]" => "0");

	my $p = $c->req->params->to_hash;
	show $p;
	$p->{deleted} = 0;

	my $cols = [qw/active customersystemid customerid systemtype systemid systemfiles marketid accountingcode filecode deleted created createdby updated updatedby/];

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

	show $jobj;

	my @ndata;
	foreach my $d (@{$jobj->{data}}){
		push(@ndata, $d) if $d->{deleted} == 0;
	}
	$jobj->{data} = \@ndata;

show $jobj;	

	return 1 if $jobj == 1;

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

sub update{
	my $c = shift;
	my $j = $c->req->params->to_hash;
	$j->{updated} = \'NOW()';
	$j->{updatedby} = $c->session->{user_id} || 1;		
	if($j->{single}){
		$j->{active} = 0 if !exists($j->{active});
		delete($j->{single});
	}



	$j->{systemfiles} = ref($j->{systemfiles}) eq 'ARRAY' ? encode_json($j->{systemfiles})  : $j->{systemfiles} ? encode_json([$j->{systemfiles}]) : encode_json([]); 
	# show $j;
	# show $j->{systemfiles};

	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})->update({active => 0, deleted => 1});
  $c->render(json=>{$c->pk=>$id});
}

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

	show $p;

	my @systems = $c->db->resultset('CustomerSystem')->search({customerid => $p->{customerid}},{result_class=>'DBIx::Class::ResultClass::HashRefInflator'}
		) or return $c->render(text => 'No records found.', status => 405);
	show @systems;

		my @markets = $c->db->resultset('Market')->search({
				distributorwarehouseid => $p->{distributorwarehouseid},
				chaingroupid => $p->{chaingroupid},
		},{result_class=>'DBIx::Class::ResultClass::HashRefInflator'}
	) or return $c->render(text => 'No records found.', status => 405);

		my $market = $markets[0];

	show @markets;			

	foreach my $system (@systems){

		$c->db->resultset('CustomerSystem')->search({customerid => $p->{customerid}, systemid => $system->{systemid}})->update({marketid => $p->{marketid}});



	}

	$c->render(text => 'Success', status => 200);

}


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



	my $fform = {
		attrs => {
			name => 'customersystemform',
			onsubmit => 'javascript: return false;',
			title => '',
			action => '',
			method => 'POST',
			# formon => 'form-always',
			# formoff => 'form-never',
			formon => 'form-on',
			formoff => 'form-off',
			cols => 1,
			autocomplete=>"new-password"
		},
		sorder => [],
		eorder => [qw/active customersystemid customerid systemtype systemid empty systemfiles marketid accountingcode filecode created createdby updated updatedby/],
		elems =>     {
			spacer => { attrs => { name => 'spacer '}, type => 'spacer'},
			empty => { attrs =>{ name => 'empty'}, type => 'empty' },

			customersystemid => {
			      attrs => { class => "form-control input-md", name => "customersystemid" },
			      title => "customersystemid",
			      type => "hidden",
			      val => undef,
			},
			customerid => {
			      attrs => { class => "form-control input-md", name => "customerid" },
			      title => "Customer ID",
			      type => "textfield",
			      val => undef,
			},
			systemtype => {
			      attrs => { class => "form-control input-md", name => "systemtype" },
			      default => undef,
			      labels => ["STORE ORDER","BOH"],
			      title => "System Type",
			      type => "select",
			      vals => [0,1],
			},
			systemid => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "systemid",
			                  },
			      default => undef,
			      labels => [],
			      populate => {
			                    defaults => {
			                    	module => "OrderInvoiceSystem",
			                    	options => {
						                prefetch => [qw//],	                    		
			                    		order_by => "systemname"
			                    	},
			                    	# fk => 'id',
			                    	where => [qw/deleted/],
			                    	vals => [0],
			                    },			                    
			                    labels => 'systemname',
			                    vals => "id",
			                    data => [qw/ordersystem invoicesystem systemfiles/]
				   },	
			      title => "System Id",
			      type => "select",
			      vals => [],
			      data => [qw/ordersystem invoicesystem systemfiles/]
			},
			# systemfiles => {
			#       attrs => { class => "form-control input-md", name => "systemfiles" },
			#       title => "Files",
			#       type => "textfield",
			#       val => undef,
			# },
			systemfiles => {
			      attrs => { class => "", name => "systemfiles" },
			      title => "Files",
			      type => "checkboxgroup",
			      vals => ["PO","ACK","CONF","SALES INVOICE","CREDIT","PA","OG"],
			      labels => ["PO","ACK","CONF","SALES INVOICE","CREDIT","PA","OG"],
			      defaults => $d->{systemfiles} ? $d->{systemfiles} : []
			},			
			marketid => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "marketid",
			                  },
			      default => undef,
			      labels => [],
			      populate => { 
			      		defaults => "marketid", 
			                    defaults => {
			                    	module => "Market",
			                    	options => {
			                    		order_by => [qw/chaingrp.chaingroupname customwarehousename customwarehousenumber/],
			                    		prefetch => [qw/chaingrp/]
			                    	},
			                    	# fk => 'id',
			                    	prefetch => [qw/chaingrp/],
			                    	where => [qw/me.active/],
			                    	vals => [1],

			                    },				      		
                    labels => sub {
                    	my ($el,$dv) = (@_);
                    	return sprintf("%s - %s - %s", $dv->{'chaingrp'}->{'chaingroupname'}, $dv->{customwarehousename}, $dv->{customwarehousenumber});
                    },	
								vals => "marketid",
								data => ['customwarehousename','customwarehousenumber']
			       },
			      title => "Market",
			      type => "select",
			      vals => [],
			      data => []
			},	
			accountingcode => {
			      attrs => { class => "form-control input-md", name => "accountingcode" },
			      title => "Acct. Code",
			      type => "textfield",
			      val => undef,
			},
			filecode => {
			      attrs => { class => "form-control input-md", name => "filecode" },
			      title => "File Code",
			      type => "textfield",
			      val => undef,
			},
			active => {
			      attrs => { class => "", name => "active" },
				  labels => ['Enabled'],			      
				  title => "Active",
			      type => "checkbox",
			      vals => [1],
			      default => 1
			},
			created => {
			      attrs => { class => "form-control input-md", name => "created" },
			      title => "created",
			      type => "hidden",
			      val => undef,
			},
			createdby => {
			      attrs => { class => "form-control input-md", name => "createdby" },
			      title => "createdby",
			      type => "hidden",
			      val => undef,
			},
			updated => {
			      attrs => { class => "form-control input-md", name => "updated" },
			      title => "Last Updated",
			      type => "readonly",
			      val => undef,
			},
			updatedby => {
			      attrs => { class => "form-control input-md", name => "updatedby" },
			      title => "Last Updated By",
			      type => "readonly",
			      val => undef,
			},			
			# active => {
			    #   attrs => {
			    #                 class => "input-md form-control",
			    #                 name => "active",
			    #                # required => "required",
			    #               },
			    #   default => undef,
			    #   labels => [],
			    #   populate => {
			    #                 defaults => {
			    #                 	module => "CustomerSystem",
			    #                 	options => {
						 #                prefetch => [],			                    		
			    #                 		order_by => "active"
			    #                 	},
			    #                 	where => [qw/deleted/],
			    #                 	vals => [0],			                    	
			    #                 },			                    
			    #                 labels => 'active',
							# 		# sub {my ($el,$dv) = (@_);return sprintf("%s - %s %s - %s", $dv->{x} || 'N/A', $dv->{x}, $dv->{x}, $dv->{x});},
			    #                 vals => "active",
			    #                 data => [qw//],
			    #               },			      
			    #   title => "active",
			    #   type => "select",
			    #   vals => [],
			    #   data => []
			# },
	
    	},
	};

	my $aform = dclone $fform;
	$aform->{attrs}->{name} = 'customersystemaddform';
	$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'
				},	
				# {
				# 	class => 'btn btn-default ',
				# 	name => 'close',
				# 	type => 'button',
				# 	'data-dismiss' => 'modal'
				# },
				{
					class => 'btn btn-warning form-cancel',
					name => 'cancel',
					type => 'button'
				},									
				# {
				# 	class => 'btn btn-warning form-cancel',
				# 	name => 'cancel',
				# 	type => 'button'
				# },							
				],
				labels => ["Add Record","Cancel"],
			},
	]);

	$c->{_buttongroup}->{default} = $c->form([
			{
				type => 'buttongroup',
				class => 'form-never',
				attrs => [{
					class => 'btn btn-warning',
					name => 'edit',
					type => 'button'
				},	
				{
					class => 'btn btn-danger',
					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-warning form-cancel',
					name => 'cancel',
					type => 'button'
				},				
				],
				labels => ["Save","Cancel"],
				# vals => [qw/save reset/],
			},

	]);

}

1;
