#!/usr/bin/perl

# $ENV{DBIC_TRACE}=1;
use JSON;
use strict;
use Data::Show;
use lib '/home/sites/clm.dmadelivers.com/www/clmapp/lib';
use CLMApp::Schema;
use DateTime;
use Text::CSV;
use POSIX;


my $dbix = CLMApp::Schema->connect("dbi:mysql:host=rds1.dmadelivers.com;db=dmaclm", 'dmaclm', '3lUz1OV2!',{unsafe=>1,RaiseError=>0,PrintError=>1});

&default;


sub default{


# update Customer SET OpStatusDate=REGEXP_REPLACE( REPLACE(LastChangedDate,'-',''),' .*', '' ) where OpStatusDate!=REGEXP_REPLACE( REPLACE(SetupDate,'-',''),' .*', '' ) AND OpStatusDate!=REGEXP_REPLACE( REPLACE(LastChangedDate,'-',''), ' .*','') AND OpStatusDate!='20210912'	

		my $rsearch = {
			opstatusdate => {'!=' => '20210912'},
		};

		my @customers = $dbix->resultset('Customer')->search($rsearch,{
		# prefetch => ['status','distributor','concept','chaingrp','chainunit','user','warehouse','orderflag','market','ordersystems','invoicesystems'],
		# '+select' => [
		# 		{ 'group_concat' => 'system.systemname', -as => 'systemname'  },
		# 		{ 'group_concat' => 'system.systemid', -as => 'systemid'  }
		# ], 
		# '+as' => [qw/systemname systemid/],
		# columns => $columns,
		# join => {'back_office_system_customers' => 'system'},
		result_class=>'DBIx::Class::ResultClass::HashRefInflator',
		group_by => [qw/me.customerid/],
		order_by => [qw/me.customerid/],
	   });

		my $cnt = 0; my @cfix;
		foreach my $cust (@customers){

			my $sdate = $cust->{setupdate}; $sdate =~ s/-//g; $sdate =~ s/\s(.*)//;
			my $udate = $cust->{lastchangeddate}; $udate =~ s/-//g; $udate =~ s/\s(.*)//;
			my $opstatusdate = $cust->{opstatusdate};
			if($opstatusdate != $sdate && $opstatusdate != $udate){
				$cnt++;
				push(@cfix, {opstatusdate => $udate, customerid => $cust->{customerid}});
			}
		}

		show $cnt;
		show \@cfix;
		foreach my $cfix (@cfix){
			$dbix->resultset('Customer')->search({customerid => $cfix->{customerid}})->update({opstatusdate => $cfix->{opstatusdate}});
		}



}