package CLMApp::Controller::Bpmigration;
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 File::Copy qw(copy move);
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 => 'Bpmigration',
# 	table => 'Bpmigration',
# 	module => 'bpmigration',
# 	pk => 'bpmigrationid',
# 	columns => [qw/bpmigrationid chaingroupid chainconceptid distributorwarehouseid active/],
# 	prefetch => [qw//],
# 	order_by => [qw/me.bpmigrationid/]
# };


our $defaults = {
	title => 'BP Migration',
	table => 'Bpmigration',
	module => 'bpmigration',
	pk => 'bpmigrationid',
	columns => [qw/bpmigrationid chaingroupid chainconceptid distributorcompanyid distributorwarehouseid systemid active/],
	prefetch => [qw/chaingrp concept warehouse distributor emailnotifications backoffice/],
	order_by => [qw/me.bpmigrationid/]
};

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 credential{

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

	$c->stash(frm => undef,butt => undef);
	$c->stash(title=> $c->title(),table =>'bpcrendtialtable' ,module=> $c->module());

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

}


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


# get filter - should be a function for this stuff
	

	show $p;

	delete($p->{"columns[12][search][value]"});
	delete($p->{"columns[13][search][value]"});


	if($p->{"columns[15][search][value]"}){
		my $date = $p->{"columns[15][search][value]"};
		$p->{"columns[15][data]"} = 'bpflagdate';
		$p->{"columns[15][search][value]"} = { '>=' => $date . ' 00:00:00' };
	}

	my $export = 0;
	my $email = 0;
	if($p->{export}){
		$export = 1;
		delete($p->{export});
		$p->{showall} = 1;
	}
	if($p->{email}){
		$email = 1;
		delete($p->{email});
		$p->{showall} = 1;
	}

	my $prefetch = ['distributor','chaingrp','concept','warehouse','chainunit'];

	my $as =  [qw/user unit updated/]; # systemname systemid
	my $select = [	
		# { 'group_concat' => 'system.systemname', -as => 'systemname'  },
		# { 'group_concat' => 'back_office_system_customers.systemid', -as => 'systemid'  },
		{ 'concat' => [qw/me.customernumber distributor.bpdcode warehouse.bplocationid/], -as => 'user'},
		{ 'concat' => [\'"DMA"',\'"-"','me.chainunitid'], -as => 'unit'},
		{ 'date' => 'bpflagdate', -as => 'updated'}
	];
	my $cols = [qw/me.customerid me.customernumber me.ownership me.customerunitnumber me.unitname/]; # = {'system.systemname' => \['GROUP_CONCAT(system.systemname)'] };
	$p->{'columns[15][data]'} = 'me.bpflagdate';
	$p->{'columns[12][data]'} = 'me.customernumber';



	my $jobj = $c->dtsearch({
		as => $as, 
		select => $select, 
		# ecolumns => $ecols, 
		# join => $join, 
		params => $p, 
		table=> 'Customer', 
		order_by => $p->{order_by} || 'me.customerid',
		# order_by => [{'-asc' => [qw/distributor.name chaingrp.chaingroupname /]}] 
		# sort => 'desc', 
		group_by => [qw/me.customerid/], 
		# having => $having, 
		# exheader => $header, 
		# excolumns=> $excols, 
		columns => $cols, 
		prefetch => $prefetch, 
		# defer => $having ? 0 : 1
	});
	return 1 if $jobj == 1;





		foreach my $r (@{$jobj->{data}}){
		# foreach my $r (@cs){


			if($r->{user} =~ /^(201|501)~(.*)$/){
			  $r->{user} = $2;
			}
			

			my @bo = $c->db->resultset('BackOfficeSystemCustomer')->search({
					"me.customerid" => $r->{customerid}
				},
				{
					prefetch => [qw/system/],
					'+select' => [{'GROUP_CONCAT' => 'system.systemname'}],
					'+as' => [qw/systemname/],
					group_by => [qw/me.customerid/],
					result_class=>'DBIx::Class::ResultClass::HashRefInflator'
				}
			);			
# show @bo;
			$r->{systemname} = $bo[0]->{systemname};

			# $r->{systemid} = [$c->db->resultset('Customer')->search_related('back_office_system_customers', {"me.customerid" => $r->{customerid}})]->map(sub {
			#   my %r = $_[0]->get_columns;
			#   return $r{systemid};
			# });

            if($r->{user} =~ /^(\d+)\s*GFSUSGFS_(\d+).*$/){
                $r->{user} = $1 . 'GFSUS' . $2;
            }

			if($r->{user} =~ /\d+~(\d+)(FSA|SSA).*_(\d+).*/){
				$r->{user} = $1 . $2 . $3;

			# 44213759USFSUSFS_9O-DMA
			}
			if($r->{user} =~ /USFS/){
				if($r->{user} =~ /^(\d+)USFS/){
					$r->{user} = $1 . 'USFS9O';
				}
			}

			if($r->{warehouse}->{siteshortname} eq 'USF-LOV' && $r->{user} =~ /(84193580|34192773|34192765|54192794|64192768|74192766)/){
					$r->{user} .= 'LOV';
			}


            $r->{user} =~ s/\s+//g;

            $r->{password} = $r->{user};

            if( $r->{systemname} =~ /BUYEFF|BIRCHPW/ ){
                $r->{password} = $r->{distributor}->{distributorcode} . $r->{customerid};
                $r->{password} = ucfirst(lc($r->{password}));
            }



# show $r;
# last;

		}

	if($export){

			  my $fdir = '/tmp/';
              my $filename = 'BP.Login.' . time() . '.xls';
              my $filepath = $fdir . $filename;
              # @c = $c->db->resultset($args->{table})->search($rsearch,$rparams); 

              my $excols = [qw/chaingrp.chaingroupname concept.chainconceptname distributor.name warehouse.siteshortname unitname customerunitnumber customernumber ownership user password systemname updated/];
              my $exheader = ["Chain Group","Chain Concept","Distributor","Warehouse","Account Name","Store Nbr","Cust Nbr","Ownership","User","Password","Back Office","Updated"];
              
              my ( $fh, $ofilename ) = $c->export_hr($jobj->{data}, 
              		headers => $exheader, 
              		filename => $filepath, 
              		nouc => 1,
              		columns => $excols);

              my $dfilepath = getcwd() . '/public/files/' . $filename;
              move $filepath, $dfilepath;
              $c->res->headers->location('/files/' . $filename);
              $c->rendered(302);

              return 1;
   }elsif($email){


	my $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>ACCT NAME</th>
		<th>STORE#</th>
		<th>WHS</th>
		<th>USERNAME</th>
		<th>PASSWORD</th>	
	</tr>
</thead>
<tbody>
<% foreach my $r (@$customers){ %>
	<tr>
		<td><%= $r->{chaingrp}->{chaingroupname} %></td>
		<td><%= $r->{unitname} %></td>
		<td><%= $r->{customerunitnumber} %></td>
		<td><%= $r->{warehouse}->{siteshortname} %></td>
		<td><%= $r->{user} %></td>
		<td><%= $r->{password} %></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>





	~;

		my $html;
		my $mails = {};
		foreach my $r (@{$jobj->{data}}){
			# my $subject = ($r->{chaingrp}->{chaingroupname} ? $r->{chaingrp}->{chaingroupname} . ' ' : '') . ($r->{distributor}->{bpdcode} ? $r->{distributor}->{bpdcode} . ' ' : '') . ($r->{systemname} ? $r->{systemname} . ' ' : '') . 'BP LOGINS'; 			
			my $subject = ($r->{chaingrp}->{chaingroupname} ? $r->{chaingrp}->{chaingroupname} . ' ' : '') . ($r->{distributor}->{bpdcode} ? $r->{distributor}->{bpdcode} . ' ' : '') . 'BP LOGINS'; 

			push(@{ $mails->{$subject} }, $r);

		}

		foreach my $s (keys %$mails){
  
              my $data = $c->render_to_string(inline => $rtemplate, customers => $mails->{$s});

              $c->mail(
                mail   => {
                  To       => $c->config->{mail}->{cc},
                  # To => 'dma@ace4it.com',
                  From => $c->config->{mail}->{from}, # message NOT from sending user so messages stay in the system
                  'Reply-to' => $c->config->{mail}->{replyto},
                  Cc => $c->config->{mail}->{cc},
                  Bcc    => $c->config->{mail}->{bcc},
                  # Bcc => 'dma@ace4it.com',
                  Subject  => $s || 'BP LOGINS',
                  Data     => $data,
                },
                how => $c->config->{mail}->{how},
                howargs => $c->config->{mail}->{howargs},   

              );

              $html .= $data;
         }

        return $c->render(text => $html);

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

	
}



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

	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 $u = $c[0];
	
	my $update = {};
	$update->{statusid} = 1;
	$update->{chainconceptid} = $u->{chainconceptid} if $u->{chainconceptid};
	$update->{chaingroupid} = $u->{chaingroupid} if $u->{chaingroupid};
	$update->{distributorwarehouseid} = $u->{distributorwarehouseid} if $u->{distributorwarehouseid};
	$update->{distributorcompanyid} = $u->{distributorcompanyid} if $u->{distributorcompanyid};
	$update->{systemid} = $u->{systemid} if $u->{systemid};


	my $cnt = $c->db->resultset('Customer')->search($update)->count;
	$c->db->resultset('Customer')->search($update)->update({brandedprocurement => $u->{active}, lastchangeddate => \'NOW()', lastupdatedbyid => $c->session->{user_id}, bpflagdate => \'NOW()' });

	my @cust = $c->db->resultset('Customer')->search($update,{result_class=>'DBIx::Class::ResultClass::HashRefInflator'});

	$c->check_email_notification(\@cust,1);

	my $a = $u->{active} ? 'Active' : 'Inactive';

	$c->render(text => "($cnt) Marked as $a BP");
}

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

	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 $u = $c[0];
	
	my $update = {};
	# $update->{statusid} = 1;
	$update->{chainconceptid} = $u->{chainconceptid} if $u->{chainconceptid};
	$update->{chaingroupid} = $u->{chaingroupid} if $u->{chaingroupid};
	$update->{distributorwarehouseid} = $u->{distributorwarehouseid} if $u->{distributorwarehouseid};
	$update->{distributorcompanyid} = $u->{distributorcompanyid} if $u->{distributorcompanyid};


	my $cnt = $c->db->resultset('Customer')->search($update)->count;
	$c->db->resultset('Customer')->search($update)->update({brandedprocurementdeleted => 1});

	my $a = $u->{active} ? 'Active' : 'Inactive';

	$c->render(text => "($cnt) Marked BP as Deleted");
}


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

	# $search->{chainconceptid} = $p->{chainconceptid} if $p->{chainconceptid};
	my $chainconceptid = [{chainconceptid => 0}];
	push(@$chainconceptid, {chainconceptid => $p->{chainconceptid}}) if $p->{chainconceptid};	
	
	my $chaingroupid = [{chaingroupid => 0}];
	push(@$chaingroupid, {chaingroupid => $p->{chaingroupid}}) if $p->{chaingroupid};

	my $distributorwarehouseid = [{distributorwarehouseid => 0}];
	push(@$distributorwarehouseid, {distributorwarehouseid => $p->{distributorwarehouseid}}) if $p->{distributorwarehouseid};

	my $distributorcompanyid = [{distributorcompanyid => 0}];
	push(@$distributorcompanyid, {distributorcompanyid => $p->{distributorcompanyid}}) if $p->{distributorcompanyid};

	my $search = {'-and' => [
		{active => 1},
		{'-or' => $chainconceptid},
		{'-or' => $chaingroupid},
		{'-or' => $distributorwarehouseid},
		{'-or' => $distributorcompanyid},
	]};


	# push(@{$search->{'-and'}}, {distributorcompanyid => $p->{distributorcompanyid}}) if $p->{distributorcompanyid};
	# $search->{'-or'} = $distributorwarehouseid;
	# $search->{distributorwarehouseid} = |$p->{distributorwarehouseid} if $p->{distributorwarehouseid};
	# $search->{distributorcompanyid} = $p->{distributorcompanyid} if $p->{distributorcompanyid};


	my $count = $c->db->resultset($c->table)->search($search)->count;
	my $set = $count ? 1 : 0;

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

}

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 ($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->{distributorwarehouseid} ||= 0;
	$j->{distributorcompanyid} ||= 0;
	$j->{systemid} ||= 0;


	if(!$j->{chaingroupid} && !$j->{chainconceptid} && !$j->{distributorwarehouseid} && !$j->{distributorcompanyid} && !$j->{systemid}){
		return  $c->render(text => 'At least one filter must be specified.', status => 405);
	}


	my $ecnt = $c->db->resultset('EmailNotification')->search({
			chaingroupid => $j->{chaingroupid},
			chainconceptid => $j->{chainconceptid},
			distributorcompanyid => $j->{distributorcompanyid},
			distributorwarehouseid => $j->{distributorwarehouseid},
			systemid => $j->{systemid},
		},{})->count;
	if(!$ecnt){

		my @template = $c->db->resultset('EmailNotification')->search({name=>'AUTO BP MIGRATE TEMPLATE'},
			{result_class => 'DBIx::Class::ResultClass::HashRefInflator'});

		my $chaingroup = $c->db->resultset('ChainGroup')->find({chaingroupid => $j->{chaingroupid}}) or undef;
		my $distributor = $c->db->resultset('DistributorCompany')->find({distributorcompanyid => $j->{distributorcompanyid}}) or undef;
		my $systemid = $c->db->resultset('BackOfficeSystem')->find({systemid => $j->{systemid}}) or undef;

		my $t = time();
		my $subject = ($chaingroup ? $chaingroup->chaingroupname . ' ' : '') . ($distributor ? $distributor->distributorcode . ' ' : '') . ($systemid ? $systemid->systemname . ' ' : '') . 'BP LOGINS'; 
 		my $name = $t . ' ' . $subject;



		$c->db->resultset('EmailNotification')->create({
			chaingroupid => $j->{chaingroupid},
			chainconceptid => $j->{chainconceptid},
			distributorcompanyid => $j->{distributorcompanyid},
			systemid => $j->{systemid},
			# distributorwarehouseid => $j->{distributorwarehouseid},
			actiontype => 'EMAIL_ON_ADD_BP_MIGRATE',
			name => $name,
			subject => $subject,
			targetlist => $template[0]->{targetlist},
			precode => undef,
			postcode => undef,
			active => 1,
			deleted => 0,
			body => $template[0]->{body}

		});



	}


	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 $cols = [qw/bpmigrationid chaingroupid chainconceptid distributorcompanyid distributorwarehouseid systemid active/];

	my $jobj = $c->dtsearch({params => $p, 
		table=> $c->table, 
		order_by => $c->order_by, 
		sort => 'desc',
		join => [qw/emailnotifications/], 
		group_by => [$c->pk], 
		select => [{GROUP_CONCAT => 'emailnotifications.name', '-as' => 'emailnotification'}], 
		as => [qw/emailnotification/],
		columns => $cols, 
		prefetch => $c->prefetch});


show $jobj->{data};
	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->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 => 'bpmigrationform',
			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/bpmigrationid active chaingroupid chainconceptid distributorcompanyid distributorwarehouseid/],
		elems =>     {
			spacer => { attrs => { name => 'spacer '}, type => 'spacer'},
			# empty => { attrs =>{ name => 'empty'}, type => 'empty' },

			bpmigrationid => {
			      attrs => { class => "form-control input-md", name => "bpmigrationid" },
			      title => "bpmigrationid",
			      type => "hidden",
			      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 => []
			    },			
			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 => [],
			    },
		chainconceptid => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "chainconceptid",
			                    # required => "required",
			                  },
			      default => undef,
			      labels => [],
			      populate => {
			                    defaults => {
			                    	module => "ChainConcept",
			                    	options => {
						                prefetch => [qw/chaingrp/],	                    		
			                    		order_by => "chainconceptname"
			                    	},
			                    	# fk => 'id',
			                    	where => [qw//],
			                    	vals => [],
			                    },			                    
			                    labels => 'chainconceptname',
			                    vals => "chainconceptid",
			                    data => ["chaingroupid"]
			                  },				                  
			      title => "Chain Concept",
			      type => "select",
			      vals => [],
			      data => [],
			    },
				distributorcompanyid => {
			      attrs => {
			                    class => "input-md form-control",
			                    name => "distributorcompanyid",
			                    # required => "required",
			                  },
			      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//],
			                    	vals => [],
			                    },			                    
			                    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",
			                    name => "distributorwarehouseid",
			                    # required => "required",
			                  },
			      default => undef,
			      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//],
			                    	vals => [],
			                    },			                    
			                    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 => []
			    },
			active => {
			      attrs => { class => "", name => "active" },
				  labels => ['Enabled'],			      
				  title => "Active",
			      type => "checkbox",
			      vals => [1],
			      default => undef
			},	
    	},
	};

	my $aform = dclone $fform;
	$aform->{attrs}->{name} = 'bpmigrationaddform';
	$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;
