package CLMApp::Controller::Market;
use Mojo::Base 'Mojolicious::Controller';
use Data::Show;
use Moose;
use Moose::Autobox;
use Perl6::Junction qw/any/;
use Data::Show;
use 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 => 'Market',
# 	table => 'Market',
# 	module => 'market',
# 	pk => 'marketid',
# 	columns => [qw/marketid chaingroupid customwarehousename customwarehousenumber active/],
# 	prefetch => [qw//],
# 	order_by => [qw/me.marketid/]
# };


our $defaults = {
	title => 'Market',
	table => 'Market',
	module => 'market',
	pk => 'marketid',
	columns => [qw/marketid chaingroupid customwarehousename customwarehousenumber active distributorwarehouseid ordersystem invoicesystem/],
	prefetch => [qw/chaingrp distwhs ordersystems invoicesystems/],
	order_by => [qw/me.marketid/]
};

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

	delete($c[0]->{ordersystem}) if $c[0]->{ordersystem} == 0;
	delete($c[0]->{invoicesystem}) if $c[0]->{invoicesystem} == 0;
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;
	$j->{invoicesystem} ||= 0;
	$j->{ordersystem} ||= 0;	
	delete($j->{$c->pk});
	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;

	if($p->{marketlookup}){
		show $p;
		if($p->{distributorid} && $p->{distributorwarehouseid}){
			delete($p->{distributorid});
			$c->req->params->remove('distributorid');
		}
		if(!$p->{chaingroupid}){
			return $c->render(text => 'Insufficent criteria.');
		}
		delete($p->{marketlookup});
	}




	my $cols = [qw/marketid chaingroupid customwarehousename customwarehousenumber active distributorwarehouseid ordersystem invoicesystem distributorid/];  # invoicesystem ordersystem

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


	return 1 if $jobj == 1;
show $jobj;
	$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});
	}	

	$j->{invoicesystem} ||= 0;
	$j->{ordersystem} ||= 0;

	# find current records in Customer & CustomerSystem
		# my @customers = $c->db->resultset('Customer')->search({marketid => $j->{marketid}, 
		# 	chaingroupid => $j->{chaingroupid}}, # distributorwarehouseid => $j->{distributorwarehouseid}
		# {result_class=>'DBIx::Class::ResultClass::HashRefInflator'}
		# ) or return $c->render(text => 'Record not found.', status => 405);

		# my @customersystems = $c->db->resultset('CustomerSystem')->search({marketid => $j->{marketid}}, 
		# {result_class=>'DBIx::Class::ResultClass::HashRefInflator'}
		# ) or return $c->render(text => 'Record not found.', status => 405);

		# foreach my $cs (@customers){
		# 	$c->db->resultset('Customer')->search({customerid => $cs->{customerid}})->update({ordersystem => $j->{ordersystem}, invoicesystem => $j->{invoicesystem}});
		# 	$c->db->resultset('CustomerSystem')->search({customerid => $cs->{customerid}, systemtype => 0})->update({systemid => $j->{ordersystem}});
		# 	$c->db->resultset('CustomerSystem')->search({customerid => $cs->{customerid}, systemtype => 1})->update({systemid => $j->{invoicesystem}});
		# }

		# foreach my $cs (@customersystems){
		# 	$c->db->resultset('CustomerSystem')->search({customerid => $cs->{customerid}, systemtype => 0})->update(ordersystem => $j->{ordersystem});
		# 	$c->db->resultset('CustomerSystem')->search({customerid => $cs->{customerid}, systemtype => 1})->update(invoicesystem => $j->{invoicesystem});
		# }



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


	my $fform = {
		attrs => {
			name => 'marketform',
			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 marketid chaingroupid distributorid distributorwarehouseid customwarehousename customwarehousenumber ordersystem invoicesystem/],
		elems =>     {
			spacer => { attrs => { name => 'spacer '}, type => 'spacer'},
			# empty => { attrs =>{ name => 'empty'}, type => 'empty' },
			distributorid => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "distributorid",
			                  },
			      default => undef,
			      labels => [],
			      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 => ['chaingroupvp','chaingrouppam'],
			                  },			      
			      title => "Distributor",
			      type => "select",
			      vals => [],
			      data => []
			},
			marketid => {
			      attrs => { class => "form-control input-md", name => "marketid" },
			      title => "marketid",
			      type => "hidden",
			      val => undef,
			},
			ordersystem => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "ordersystem",
			                  },
			      default => undef,
			      labels => [],
			      populate => {
			                    # defaults => "user",
			                    defaults => {
			                    	module => "OrderInvoiceSystem",
			                    	options => {
						                prefetch => [],			                    		
			                    		order_by => "systemname"
			                    	},

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

			                    },			                    
			                    labels => 'systemname',
			                    # sub {
			                    # 	my ($el,$dv) = (@_);
			                    # 	return sprintf("%s - %s %s - %s", $dv->{iacctnmbr} || 'N/A', $dv->{fname}, $dv->{lname}, $dv->{company});
			                    # },
			                    vals => "id",
			                    # data => ['chaingroupvp','chaingrouppam'],
			                  },			      
			      title => "Order System",
			      type => "select",
			      vals => [],
			      data => []
			},	
			invoicesystem => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "invoicesystem",
			                  },
			      default => undef,
			      labels => [],
			      populate => {
			                    # defaults => "user",
			                    defaults => {
			                    	module => "OrderInvoiceSystem",
			                    	options => {
						                prefetch => [],			                    		
			                    		order_by => "systemname"
			                    	},

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

			                    },			                    
			                    labels => 'systemname',
			                    # sub {
			                    # 	my ($el,$dv) = (@_);
			                    # 	return sprintf("%s - %s %s - %s", $dv->{iacctnmbr} || 'N/A', $dv->{fname}, $dv->{lname}, $dv->{company});
			                    # },
			                    vals => "id",
			                    # data => ['chaingroupvp','chaingrouppam'],
			                  },			      
			      title => "Invoice System",
			      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//],
			                    	vals => [],			                    	

			                    },			                    
			                    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 => []
			    },
			distributorwarehouseid => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "distributorwarehouseid",
			                  },
			      default => undef,
			      labels => [],
			      # populate => {
			      #               defaults => "chaingroup",
			      #               labels => "chaingroupname",
			      #               vals => "chaingroupid",
			      #               data => ['chaingroupvp','chaingrouppam']
			      #             },
			      populate => {
			                    # defaults => "user",
			                    defaults => {
			                    	module => "DistributorWarehouse",
			                    	options => {
						                prefetch => [qw/distributor/],			                    		
			                    		order_by => [{'-asc' => 'distributor.name'},{'-asc' => 'me.distributorwarehouseid'}]
			                    	},

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

			                    },			                    
			                    labels =>
			                    sub {
			                    	my ($el,$dv) = (@_);
			                    	return sprintf("%s - %s", $dv->{distributor}->{name}, $dv->{distributorwarehousename});
			                    },
			                    vals => "distributorwarehouseid",
			                    data => ['distributorcompanyid'],
			                  },			      
			      title => "Warehouse",
			      type => "select",
			      vals => [],
			      data => []
			    },			    
			customwarehousename => {
			      attrs => { class => "form-control input-md lcase", name => "customwarehousename" },
			      title => "Custom Warehouse Name",
			      type => "textfield",
			      val => undef,
			},
			customwarehousenumber => {
			      attrs => { class => "form-control input-md lcase", name => "customwarehousenumber" },
			      title => "Custom Warehouse Number",
			      type => "textfield",
			      val => undef,
			},
			active => {
			      attrs => { class => "", name => "active" },
				  labels => ['Enabled'],			      
				  title => "Active",
			      type => "checkbox",
			      vals => [1],
			      default => undef
			},	
			# active => {
			    #   attrs => {
			    #                 class => "input-md form-control",
			    #                 name => "active",
			    #                # required => "required",
			    #               },
			    #   default => undef,
			    #   labels => [],
			    #   populate => {
			    #                 defaults => {
			    #                 	module => "Market",
			    #                 	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} = 'marketaddform';
	$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-off',
				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-on',
				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","Close","Cancel"],
				# vals => [qw/save reset/],
			},

	]);

}

1;
