<?php

require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');
include 'header.php';
require_once 'web_constant.php';
include('xcrud/xcrud.php');
 
?>
<style>
.ui-front {
  z-index: 10000000000000000 !important;
}
</style>
<!--<form action="" method="POST">-->
<?php
$bdd=new DB();
$security_password_row=$bdd->getOne("SELECT password FROM security_password WHERE name='product'");
$bdd->disconnect();

$bdd = new DB();
$rows = $bdd->getAll("SELECT Tabs, Submenu FROM permissions WHERE UId = $UId");
$bdd->disconnect();

$permissionsArray = array();

foreach ($rows as $row) {
    $tabs = $row['Tabs'];
    $submenus = explode(',', $row['Submenu']);

    if (!isset($permissionsArray[$tabs])) {
        $permissionsArray[$tabs] = array();
    }

    $permissionsArray[$tabs] = array_merge($permissionsArray[$tabs], $submenus);
}
	
echo Xcrud::load_css();
$xcrud=Xcrud::get_instance();
$xcrud->table('customer');
$xcrud->column_width('date','200px');
$xcrud->columns('taxReceipt,SMCtaxReceipt,crtm,fitness,permit,rcCopy,otp,delivery_image,front_photo,rear_photo,chassis,sticker',true);
$xcrud->relation('salesman','salesman','id','name');
$xcrud->relation('rto','rto','id','name');
$xcrud->relation('make','meter_make','id','name');
//$xcrud->limit(3);
if($_GET['status']!='IssueDocs' && $_GET['status']!='FullSuccessfull'){
	$xcrud->columns('document_received_date,document_issue_date',true);
}
if($_GET['status']!='FullSuccessfull'){
	$xcrud->columns('document_issue_date',true);
}

if($_GET['status']=='Upload' || $_GET['status']=='Insp'){
	$xcrud->highlight('Product','!=','4s','green');
	//$xcrud->highlight('Product','=','X-Wide','green');
}
if($_GET['status']=='Pending'){
	$xcrud->where('status','Pending');
	//$xcrud->column_callback('date', 'highlight_task_date');	
}

if($_GET['status']=='Allotment')
	$xcrud->where('status','Allotment');
if($_GET['status']=='Proceed')
	$xcrud->where('status','Proceed');
if($_GET['status']=='Upload'){
	$xcrud->where('status','Upload');
	$xcrud->order_by('Remark', 'DESC'); 
}else{
	$xcrud->order_by('date', 'DESC'); 
}
if($_GET['status']=='Insp')
	$xcrud->where('status','Insp');
if($_GET['status']=='Payment')
	$xcrud->where('status','Payment');
if($_GET['status']=='SemiSuccessfull'){
	$xcrud->where('status','SemiSuccessfull');
}
if($_GET['status']=='hsrp')
	$xcrud->where('status','hsrp');
if($_GET['status']=='Fitment')
	$xcrud->where('status','Fitment');
if($_GET['status']=='Ready')
	$xcrud->where('status','Ready');
if($_GET['status']=='RC')
	$xcrud->where('status','RC');
if($_GET['status']=='Register')
	$xcrud->where('status','Register');
if($_GET['status']=='IssueDocs')
	$xcrud->where('status','IssueDocs');
if($_GET['status']=='FullSuccessfull')
	$xcrud->where('status','FullSuccessfull');
if($_GET['status']=='Rejected')
	$xcrud->where('status','Rejected');
$xcrud->validation_required('name,contact_no,date,salesman');
$xcrud->relation('added_by','user','user_id','name');

$xcrud->change_type('order_status','bool');
$xcrud->change_type('receive','bool');
$xcrud->change_type('fittment','bool');
//$xcrud->change_type('delivery_image','image');



//$xcrud->condition('contact_no','','','validation_pattern',array('contact_no','[0-9]'));
//$xcrud->pass_default('added_by',$_SESSION['admin_id']);
//if($_GET['status']=='Completed' || $_GET['status']=='All'){
if($_GET['status']=='Upload'){
	if($type=='admin'){
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs,FullSuccessfull');
	}else{
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment');
	}
}else if($_GET['status']=='Allotment'){
	if($type=='admin'){
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs,FullSuccessfull');
	}else{
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment');
	}
}else if($_GET['status']=='Proceed'){
	if($type=='admin'){
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs,FullSuccessfull');
	}else{
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment');
	}
}else if($_GET['status']=='Payment'){
	if($type=='admin'){
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs,FullSuccessfull');
	}else{
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment');
	}
}else if($_GET['status']=='Insp'){
	if($type=='admin'){
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs,FullSuccessfull');
	}else{
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment');
	}
}else if($_GET['status']=='SemiSuccessfull'){
	if($type=='admin'){
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs,FullSuccessfull');
		$xcrud->button('javascript:;','Remove Tax Receipt','fa fa-arrow-left','',array('data-toggle'=>'modal','data-target'=>'#taxReceiptModal','onclick'=>'setTaxReceiptInfo({customer_id})'));
	}else{
		if (in_array('Update-TaxReceipt', $permissionsArray['Semi-Successfull'])) {
			$xcrud->button('javascript:;','Remove Tax Receipt','fa fa-arrow-left','',array('data-toggle'=>'modal','data-target'=>'#taxReceiptModal','onclick'=>'setTaxReceiptInfo({customer_id})'));
		}
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull');
	}
}else if($_GET['status']=='hsrp'){
	if($type=='admin'){
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs,FullSuccessfull');
	}else{
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp');
	}
}else if($_GET['status']=='Fitment'){
	if($type=='admin'){
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs,FullSuccessfull');
		//$xcrud->button('tel:{contact_no}','Call','fa fa-phone');
	}else{
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register');
	}
	
}else if($_GET['status']=='Ready' || $_GET['status']=='RC'){
	if($type=='admin'){
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs,FullSuccessfull');
		//$xcrud->button('tel:{contact_no}','Call','fa fa-phone');
	}else{
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs');
	}
}else if($_GET['status']=='Register'){
	if($type=='admin'){
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs,FullSuccessfull');
		//$xcrud->button('tel:{contact_no}','Call','fa fa-phone');
	}else{
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs');
	}
}else if($_GET['status']=='IssueDocs'){
	if($type=='admin'){
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs,FullSuccessfull');
		//$xcrud->button('tel:{contact_no}','Call','fa fa-phone');
		$xcrud->button('javascript:;','Remark','clip-bubble','',array('data-toggle'=>'modal','data-target'=>'#customerRemarkModal','onclick'=>'updateCustRemarkInfo({customer_id})'));
	}else{
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs');
		if (in_array('Remark', $permissionsArray['IssueDocs'])) {
			$xcrud->button('javascript:;','Remark','clip-bubble','',array('data-toggle'=>'modal','data-target'=>'#customerRemarkModal','onclick'=>'updateCustRemarkInfo({customer_id})'));
		}
	}
}else if($_GET['status']=='FullSuccessfull'){
	if($type=='admin'){
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs,FullSuccessfull');
	}else{
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs,FullSuccessfull');
	}
}else{
	if($type!='admin'){
		$xcrud->change_type('status','text');
		$xcrud->readonly('status');
	}else{
		//$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Register,FullSuccessfull');
		$xcrud->change_type('status','select','Pending','Pending,Allotment,Proceed,Upload,Insp,Payment,SemiSuccessfull,hsrp,Fitment,Ready,RC,Register,IssueDocs,FullSuccessfull');
	}
}
//$xcrud->change_type('taxReceipt','file','',array('path'=>'../uploads/2018/{name}-{contact_no}'));
if($type!='admin'){
$xcrud->readonly('added_by,taxReceipt,crtm,fitness,permit,rcCopy');
$xcrud->disabled('date,created_date,allotment_time,proceed_time,upload_time,insp_time,payment_time,semi_successfull_time,hsrp_time,fitment_time,ready_time,rc_time,register_time,issue_docs_time');
}
$xcrud->readonly('name,contact_no');


$xcrud->change_type('chassis_no', 'text');

// Add client-side validation using JavaScript
$xcrud->validation_required('chassis_no', true);
//$xcrud->validation_pattern('chassis_no', '^.{8}$');


$xcrud->unset_title();
$xcrud->unset_add();
if($type!='admin'){
	$xcrud->unset_remove();
}
if($type!='admin'){
	if($_GET['status']!='hsrp' && $_GET['status']!='Register'){
		$xcrud->unset_print();
		$xcrud->unset_csv();
	}
}
/*if($_GET['status']!='All' && $_GET['status']!='Completed'){
	$xcrud->unset_edit();
}*/

if($type=='admin' && $_REQUEST["status"]=="Upload" || $_REQUEST["status"]=="Insp") {
	$xcrud->button('view.php?id={customer_id}&Uname=\'' . $Uname . '\'','View','fa fa-eye','');
}

if($type!='admin'){
	if ($_REQUEST["status"]=="Pending") {
		if (in_array('Scan', $permissionsArray['Pending'])) {
			$xcrud->button('scanImage.php?id={customer_id}&Uname=\'' . $Uname . '\'','scan','fa fa-qrcode','');
		}
		if (in_array('Documents', $permissionsArray['Pending'])) {
			$xcrud->button('javascript:;','Documents','fa fa-bars','',array('onclick'=>'openLocation({customer_id})'));
		}
		if (in_array('Path', $permissionsArray['Pending'])) {
			$xcrud->button('javascript:;','Path','fa fa-folder','',array('onclick'=>'openLocationPath({customer_id})'));
		}
		if (in_array('Update-Customer', $permissionsArray['Pending'])) {
			$xcrud->button('javascript:;','Update Customer','fa fa-edit','',array('data-toggle'=>'modal','data-target'=>'#custInfoModal','onclick'=>'updateCustInfo({customer_id})'));
		}
	}
}

if($type!='admin'){
	if ($_REQUEST["status"]=="All") {
		$xcrud->button('javascript:;','Documents','fa fa-bars','',array('onclick'=>'openLocation({customer_id})'));
	}
	if ($_REQUEST["status"]=="Allotment") {
		if (in_array('Documents', $permissionsArray['Allotment'])) {
			$xcrud->button('javascript:;','Documents','fa fa-bars','',array('onclick'=>'openLocation({customer_id})'));
		}
		if (in_array('Path', $permissionsArray['Allotment'])) {
			$xcrud->button('javascript:;','Path','fa fa-folder','',array('onclick'=>'openLocationPath({customer_id})'));
		}
		if (in_array('Update-Customer', $permissionsArray['Allotment'])) {
			$xcrud->button('javascript:;','Update Customer','fa fa-edit','',array('data-toggle'=>'modal','data-target'=>'#custInfoModal','onclick'=>'updateCustInfo({customer_id})'));
		}
		if (in_array('Update-Registration-No', $permissionsArray['Allotment'])) {
			//$xcrud->button('javascript:;','Update Registration No','fa fa-bolt','',array('data-toggle'=>'modal','data-target'=>'#updateRegistrationNoModal','onclick'=>'updateRegistrationNo({customer_id})'));
		}
	}
}

if($type!='admin'){
	if ($_REQUEST["status"]=="Proceed") {
		if (in_array('Documents', $permissionsArray['Proceed'])) {
			$xcrud->button('javascript:;','Documents','fa fa-bars','',array('onclick'=>'openLocation({customer_id})'));
		}
		if (in_array('Path', $permissionsArray['Proceed'])) {
			$xcrud->button('javascript:;','Path','fa fa-folder','',array('onclick'=>'openLocationPath({customer_id})'));
		}
		if (in_array('Update-Customer', $permissionsArray['Proceed'])) {
			$xcrud->button('javascript:;','Update Customer','fa fa-edit','',array('data-toggle'=>'modal','data-target'=>'#custInfoModal','onclick'=>'updateCustInfo({customer_id})'));
		}
		if (in_array('Update-Registration-No', $permissionsArray['Proceed'])) {
			//$xcrud->button('javascript:;','Update Registration No','fa fa-bolt','',array('data-toggle'=>'modal','data-target'=>'#updateRegistrationNoModal','onclick'=>'updateRegistrationNo({customer_id})'));
		}
	}
}

if($type!='admin'){
	if ($_REQUEST["status"]=="Upload") {
		if (in_array('Scan', $permissionsArray['Upload'])) {
			$xcrud->button('scanImage.php?id={customer_id}&Uname=\'' . $Uname . '\'','scan','fa fa-qrcode','');
		}
		if (in_array('Documents', $permissionsArray['Upload'])) {
			$xcrud->button('javascript:;','Documents','fa fa-bars','',array('onclick'=>'openLocation({customer_id})'));
		}
		if (in_array('Path', $permissionsArray['Upload'])) {
			$xcrud->button('javascript:;','Path','fa fa-folder','',array('onclick'=>'openLocationPath({customer_id})'));
		}
		if (in_array('Update-Customer', $permissionsArray['Upload'])) {
			$xcrud->button('javascript:;','Update Customer','fa fa-edit','',array('data-toggle'=>'modal','data-target'=>'#custInfoModal','onclick'=>'updateCustInfo({customer_id})'));
		}
		if (in_array('Done', $permissionsArray['Upload'])) {
			$xcrud->button('javascript:;','Done','fa fa-check','',array('onclick'=>"changeCompletedStatus({customer_id},'$Uname','{Product}')"));
		}
	}
}

if($type!='admin'){
	if ($_REQUEST["status"]=="Insp") {
		if (in_array('Scan', $permissionsArray['Insp'])) {
			$xcrud->button('scanImage.php?id={customer_id}&Uname=\'' . $Uname . '\'','scan','fa fa-qrcode','','',array('SMCtaxReceipt','!=','SMCtaxReceipt.pdf'));
			$xcrud->button('scanImage.php?id={customer_id}&Uname=\'' . $Uname . '\'','SMCtaxReceipt','fa fa-file','','',array('SMCtaxReceipt','=','SMCtaxReceipt.pdf'));
		}
		if (in_array('Documents', $permissionsArray['Insp'])) {
			$xcrud->button('javascript:;','Documents','fa fa-bars','',array('onclick'=>'openLocation({customer_id})'));
		}
		if (in_array('Path', $permissionsArray['Insp'])) {
			$xcrud->button('javascript:;','Path','fa fa-folder','',array('onclick'=>'openLocationPath({customer_id})'));
		}
		if (in_array('Update-Customer', $permissionsArray['Insp'])) {
			$xcrud->button('javascript:;','Update Customer','fa fa-edit','',array('data-toggle'=>'modal','data-target'=>'#custInfoModal','onclick'=>'updateCustInfo({customer_id})'));
		}
		if (in_array('Update-Registration-No', $permissionsArray['Insp'])) {
			///$xcrud->button('javascript:;','Update Registration No','fa fa-bolt','',array('data-toggle'=>'modal','data-target'=>'#updateRegistrationNoModal','onclick'=>'updateRegistrationNo({customer_id})'));
		}
		/*if (in_array('Next', $permissionsArray['Insp'])) {
			$xcrud->button('javascript:;','Next','fa fa-check','',array('onclick'=>"updateInspStatus({customer_id},'$Uname','{Product}')"),array('SMCtaxReceipt','=','SMCtaxReceipt.pdf'));
			
			$xcrud->button('javascript:;','Check SMC','fa fa-check','',array('onclick'=>"changeStatus({customer_id},'$Uname','{Product}')"),array('SMCtaxReceipt','!=','SMCtaxReceipt.pdf'));
		}*/
		if (in_array('Remark', $permissionsArray['Insp'])) {
			$xcrud->button('javascript:;','Remark','fa fa-times','',array('data-toggle'=>'modal','data-target'=>'#RemarkInfoModal','onclick'=>'updateRemark({customer_id})'));
		}
		if (in_array('Next', $permissionsArray['Insp'])) {
			/*$xcrud->button('scanImage.php?id={customer_id}&Uname=\'' . $Uname . '\'','scan','fa fa-qrcode','','',array('SMCtaxReceipt','!=','SMCtaxReceipt.pdf'));
			$xcrud->button('scanImage.php?id={customer_id}&Uname=\'' . $Uname . '\'','SMCtaxReceipt','fa fa-file','','',array('SMCtaxReceipt','=','SMCtaxReceipt.pdf'));*/
			$xcrud->button('javascript:;','Next','fa fa-check','',array('onclick'=>"updateInspStatus({customer_id},'$Uname','{Product}')"),array('smc','=','No'));
		
			$xcrud->button('javascript:;','Next ','fa fa-check','',array('onclick'=>"changeStatus({customer_id},'$Uname','{Product}')"),array('smc','=','Yes'));
		}
		
	}
}

if($type!='admin'){
	if ($_REQUEST["status"]=="Payment") {
		if (in_array('Scan', $permissionsArray['Payment'])) {
			$xcrud->button('scanImage.php?id={customer_id}&Uname=\'' . $Uname . '\'','scan','fa fa-qrcode','');
		}
		if (in_array('Documents', $permissionsArray['Payment'])) {
			$xcrud->button('javascript:;','Documents','fa fa-bars','',array('onclick'=>'openLocation({customer_id})'));
		}
		if (in_array('Path', $permissionsArray['Payment'])) {
			$xcrud->button('javascript:;','Path','fa fa-folder','',array('onclick'=>'openLocationPath({customer_id})'));
		}
		if (in_array('Update-Customer', $permissionsArray['Payment'])) {
			$xcrud->button('javascript:;','Update Customer','fa fa-edit','',array('data-toggle'=>'modal','data-target'=>'#custInfoModal','onclick'=>'updateCustInfo({customer_id})'));
		}
	}
}

if($type!='admin'){
	if ($_REQUEST["status"]=="SemiSuccessfull") {
		if (in_array('Documents', $permissionsArray['Semi-Successfull'])) {
			$xcrud->button('javascript:;','Documents','fa fa-bars','',array('onclick'=>'openLocation({customer_id})'));
		}
		if (in_array('Path', $permissionsArray['Semi-Successfull'])) {
			$xcrud->button('javascript:;','Path','fa fa-folder','',array('onclick'=>'openLocationPath({customer_id})'));
		}
		if (in_array('Update-Customer', $permissionsArray['Semi-Successfull'])) {
			$xcrud->button('javascript:;','Update Customer','fa fa-edit','',array('data-toggle'=>'modal','data-target'=>'#custInfoModal','onclick'=>'updateCustInfo({customer_id})'));
		}
		if (in_array('Update-Registration-No', $permissionsArray['Semi-Successfull'])) {
			//$xcrud->button('javascript:;','Update Registration No','fa fa-bolt','',array('data-toggle'=>'modal','data-target'=>'#updateRegistrationNoModal','onclick'=>'updateRegistrationNo({customer_id})'));
		}
	}
}

if($type!='admin'){
	if ($_REQUEST["status"]=="hsrp") {
		if (in_array('Documents', $permissionsArray['HSRP'])) {
			$xcrud->button('javascript:;','Documents','fa fa-bars','',array('onclick'=>'openLocation({customer_id})'));
		}
		if (in_array('Path', $permissionsArray['HSRP'])) {
			$xcrud->button('javascript:;','Path','fa fa-folder','',array('onclick'=>'openLocationPath({customer_id})'));
		}
		if (in_array('Update-Customer', $permissionsArray['HSRP'])) {
			$xcrud->button('javascript:;','Update Customer','fa fa-edit','',array('data-toggle'=>'modal','data-target'=>'#custInfoModal','onclick'=>'updateCustInfo({customer_id})'));
		}
		if (in_array('Update-Registration-No', $permissionsArray['HSRP'])) {
			//$xcrud->button('javascript:;','Update Registration No','fa fa-bolt','',array('data-toggle'=>'modal','data-target'=>'#updateRegistrationNoModal','onclick'=>'updateRegistrationNo({customer_id})'));
		}
		if (in_array('Scan', $permissionsArray['HSRP'])) {
			$xcrud->button('scanImage.php?id={customer_id}&Uname=\'' . $Uname . '\'','scan','fa fa-qrcode','','',array('SMCtaxReceipt','!=','SMCtaxReceipt.pdf'));
			$xcrud->button('scanImage.php?id={customer_id}&Uname=\'' . $Uname . '\'','SMCtaxReceipt','fa fa-file','','',array('SMCtaxReceipt','=','SMCtaxReceipt.pdf'));
		}
	}
}

if($type!='admin'){
	if ($_REQUEST["status"]=="Fitment") {
		if (in_array('Call', $permissionsArray['Fitment'])) {
			$xcrud->button('tel:{contact_no}','Call','fa fa-phone');
		}
		if (in_array('Documents', $permissionsArray['Fitment'])) {
			$xcrud->button('javascript:;','Documents','fa fa-bars','',array('onclick'=>'openLocation({customer_id})'));
		}
		if (in_array('Path', $permissionsArray['Fitment'])) {
			$xcrud->button('javascript:;','Path','fa fa-folder','',array('onclick'=>'openLocationPath({customer_id})'));
		}
		if (in_array('Update-Customer', $permissionsArray['Fitment'])) {
			$xcrud->button('javascript:;','Update Customer','fa fa-edit','',array('data-toggle'=>'modal','data-target'=>'#custInfoModal','onclick'=>'updateCustInfo({customer_id})'));
		}
		if (in_array('Update-Registration-No', $permissionsArray['Fitment'])) {
			//$xcrud->button('javascript:;','Update Registration No','fa fa-bolt','',array('data-toggle'=>'modal','data-target'=>'#updateRegistrationNoModal','onclick'=>'updateRegistrationNo({customer_id})'));
		}
	}
}

if($type!='admin'){
	if ($_REQUEST["status"]=="Ready" ) {
		if (in_array('Call', $permissionsArray['Ready-to-go'])) {
			$xcrud->button('tel:{contact_no}','Call','fa fa-phone');
		}
		if (in_array('Scan', $permissionsArray['Ready-to-go'])) {
			$xcrud->button('ReadyToGo.php?id={customer_id}&Uname=\'' . $Uname . '\'','scan','fa fa-qrcode','');
		}
		if (in_array('Documents', $permissionsArray['Ready-to-go'])) {
			$xcrud->button('javascript:;','Documents','fa fa-bars','',array('onclick'=>'openLocation({customer_id})'));
		}
		if (in_array('Path', $permissionsArray['Ready-to-go'])) {
			$xcrud->button('javascript:;','Path','fa fa-folder','',array('onclick'=>'openLocationPath({customer_id})'));
		}
		if (in_array('Update-Customer', $permissionsArray['Ready-to-go'])) {
			$xcrud->button('javascript:;','Update Customer','fa fa-edit','',array('data-toggle'=>'modal','data-target'=>'#custInfoModal','onclick'=>'updateCustInfo({customer_id})'));
		}
		if (in_array('Update-Registration-No', $permissionsArray['Ready-to-go'])) {
			//$xcrud->button('javascript:;','Update Registration No','fa fa-bolt','',array('data-toggle'=>'modal','data-target'=>'#updateRegistrationNoModal','onclick'=>'updateRegistrationNo({customer_id})'));
		}
	}
	if ( $_REQUEST["status"]=="RC") {
		if (in_array('Call', $permissionsArray['RC'])) {
			$xcrud->button('tel:{contact_no}','Call','fa fa-phone');
		}
		if (in_array('Scan', $permissionsArray['RC'])) {
			$xcrud->button('ReadyToGo.php?id={customer_id}&Uname=\'' . $Uname . '\'','scan','fa fa-qrcode','');
		}
		if (in_array('Documents', $permissionsArray['RC'])) {
			$xcrud->button('javascript:;','Documents','fa fa-bars','',array('onclick'=>'openLocation({customer_id})'));
		}
		if (in_array('Path', $permissionsArray['RC'])) {
			$xcrud->button('javascript:;','Path','fa fa-folder','',array('onclick'=>'openLocationPath({customer_id})'));
		}
		if (in_array('Update-Customer', $permissionsArray['RC'])) {
			$xcrud->button('javascript:;','Update Customer','fa fa-edit','',array('data-toggle'=>'modal','data-target'=>'#custInfoModal','onclick'=>'updateCustInfo({customer_id})'));
		}
		if (in_array('Update-Registration-No', $permissionsArray['RC'])) {
			//$xcrud->button('javascript:;','Update Registration No','fa fa-bolt','',array('data-toggle'=>'modal','data-target'=>'#updateRegistrationNoModal','onclick'=>'updateRegistrationNo({customer_id})'));
		}
	}
}

if($type!='admin'){
	if ($_REQUEST["status"]=="Register") {
		if (in_array('Call', $permissionsArray['Register'])) {
			$xcrud->button('tel:{contact_no}','Call','fa fa-phone');
		}
		if (in_array('Documents', $permissionsArray['Register'])) {
			$xcrud->button('javascript:;','Documents','fa fa-bars','',array('onclick'=>'openLocation({customer_id})'));
		}
		if (in_array('Path', $permissionsArray['Register'])) {
			$xcrud->button('javascript:;','Path','fa fa-folder','',array('onclick'=>'openLocationPath({customer_id})'));
		}
		if (in_array('Update-Customer', $permissionsArray['Register'])) {
			$xcrud->button('javascript:;','Update Customer','fa fa-edit','',array('data-toggle'=>'modal','data-target'=>'#custInfoModal','onclick'=>'updateCustInfo({customer_id})'));
		}
		if (in_array('Update-Registration-No', $permissionsArray['Register'])) {
			//$xcrud->button('javascript:;','Update Registration No','fa fa-bolt','',array('data-toggle'=>'modal','data-target'=>'#updateRegistrationNoModal','onclick'=>'updateRegistrationNo({customer_id})'));
		}
		if (in_array('Docs', $permissionsArray['Register'])) {
			$xcrud->button('javascript:;','Docs','fa fa-check','',array('onclick'=>'changeRegister({customer_id},\'' . $Uname . '\')'));
		}
	}
}

if($type!='admin'){
	if ($_REQUEST["status"]=="IssueDocs") {
		if (in_array('Call', $permissionsArray['IssueDocs'])) {
			$xcrud->button('tel:{contact_no}','Call','fa fa-phone');
		}
		if (in_array('Documents', $permissionsArray['IssueDocs'])) {
			$xcrud->button('javascript:;','Documents','fa fa-bars','',array('onclick'=>'openLocation({customer_id})'));
		}
		if (in_array('Scan', $permissionsArray['IssueDocs'])) {
			//$xcrud->button('ReadyToGo.php?id={customer_id}&Uname=\'' . $Uname . '\'','scan','fa fa-qrcode','');
			$xcrud->button('IssueDocs.php?id={customer_id}&Uname=\'' . $Uname . '\'','scan','fa fa-qrcode','');
		}
	}
}

if($type!='admin'){
	if ($_REQUEST["status"]=="FullSuccessfull") {
		if (in_array('Documents', $permissionsArray['Full-Successfull'])) {
			$xcrud->button('javascript:;','Documents','fa fa-bars','',array('onclick'=>'openLocation({customer_id})'));
		}
		if (in_array('Path', $permissionsArray['Full-Successfull'])) {
			$xcrud->button('javascript:;','Path','fa fa-folder','',array('onclick'=>'openLocationPath({customer_id})'));
		}
		if (in_array('Update-Customer', $permissionsArray['Full-Successfull'])) {
			$xcrud->button('javascript:;','Update Customer','fa fa-edit','',array('data-toggle'=>'modal','data-target'=>'#custInfoModal','onclick'=>'updateCustInfo({customer_id})'));
		}
		if (in_array('Update-Registration-No', $permissionsArray['Full-Successfull'])) {
			//$xcrud->button('javascript:;','Update Registration No','fa fa-bolt','',array('data-toggle'=>'modal','data-target'=>'#updateRegistrationNoModal','onclick'=>'updateRegistrationNo({customer_id})'));
		}
	}
}

if($type=='admin'){
	if($type!='restricted_user'){											//UV_Change
		if($_REQUEST["status"]=="Pending" || $_REQUEST["status"]=="Upload" || $_REQUEST["status"]=="Payment"){	
			$xcrud->button('scanImage.php?id={customer_id}&Uname=\'' . $Uname . '\'','scan','fa fa-qrcode','');
		}
		if($_GET['status']=='Ready'){
				$xcrud->button('ReadyToGo.php?id={customer_id}&Uname=\'' . $Uname . '\'','scan','fa fa-qrcode','');
		}
		if($_GET['status']=='Insp' || $_GET['status']=='hsrp'){
			$xcrud->button('scanImage.php?id={customer_id}&Uname=\'' . $Uname . '\'','scan','fa fa-qrcode','','',array('SMCtaxReceipt','!=','SMCtaxReceipt.pdf'));
			$xcrud->button('scanImage.php?id={customer_id}&Uname=\'' . $Uname . '\'','SMCtaxReceipt','fa fa-file','','',array('SMCtaxReceipt','=','SMCtaxReceipt.pdf'));
		}
		$xcrud->button('javascript:;','Documents','fa fa-bars','',array('onclick'=>'openLocation({customer_id})'));
		$xcrud->button('javascript:;','Path','fa fa-folder','',array('onclick'=>'openLocationPath({customer_id})'));
		$xcrud->button('javascript:;','Update Customer','fa fa-edit','',array('data-toggle'=>'modal','data-target'=>'#custInfoModal','onclick'=>'updateCustInfo({customer_id})'));
	}
}

if($type=='restricted_user'){
	$xcrud->unset_add();
	$xcrud->unset_view();
	$xcrud->unset_edit();
	$xcrud->unset_remove();
}

if($type=='admin'){
	$xcrud->button('javascript:;','View Customer Info','fa fa-list','',array('data-toggle'=>'modal','data-target'=>'#CustomerInfo','onclick'=>'CustomerInfo({customer_id})'));
	if($_GET['status']!='Pending' && $_GET['status']!='Upload' && $_GET['status']!='Payment'){
		//$xcrud->button('javascript:;','Update Registration No','fa fa-bolt','',array('data-toggle'=>'modal','data-target'=>'#updateRegistrationNoModal','onclick'=>'updateRegistrationNo({customer_id})'));
	}

	if($_GET['status']=='Upload'){
		$xcrud->button('javascript:;','Done','fa fa-check','',array('onclick'=>"changeCompletedStatus({customer_id},'$Uname','{Product}')"));
	}

	if($_GET['status']=='Insp'){
		//$xcrud->button('javascript:;','Next','fa fa-check','',array('onclick'=>"changeStatus({customer_id},'$Uname','{Product}')"));
		
		$xcrud->button('javascript:;','Next','fa fa-check','',array('onclick'=>"updateInspStatus({customer_id},'$Uname','{Product}')"),array('smc','=','No'));
		
		$xcrud->button('javascript:;','Next ','fa fa-check','',array('onclick'=>"changeStatus({customer_id},'$Uname','{Product}')"),array('smc','=','Yes'));
		
		/*$array = array();
		
		$array[0] = "smc='Yes'";
		$array[1]="SMCtaxReceipt='SMCtaxReceipt.pdf'";
		
		$xcrud->button('javascript:;','Next','fa fa-check','',array('onclick'=>"updateInspStatus({customer_id},'$Uname','{Product}')"),$array);
		$array[0] = array();
		$array[0]['smc'] = 'Yest';
		$array[0]['email'] = 'john@example.com';

		$array[1] = array();
		$array[1]['name'] = 'Jane Doe';
		$array[1]['email'] = 'jane@example.com';*/

		//$xcrud->button('javascript:;','Next1','fa fa-check','',array('onclick'=>"updateInspStatus({customer_id},'$Uname','{Product}')"),"(smc='Yes' AND SMCtaxReceipt='SMCtaxReceipt.pdf')");
			
		//$xcrud->button('javascript:;','Check SMC','fa fa-check','',array('onclick'=>"changeStatus({customer_id},'$Uname','{Product}')"),array('SMCtaxReceipt','!=','SMCtaxReceipt.pdf'));
		
		$xcrud->button('javascript:;','Remark','fa fa-times','',array('data-toggle'=>'modal','data-target'=>'#RemarkInfoModal','onclick'=>'updateRemark({customer_id})'));
	}
	if($_GET['status']=='Register'){
		$xcrud->button('javascript:;','Docs','fa fa-check','',array('onclick'=>'changeRegister({customer_id},\'' . $Uname . '\')'));
	}
	if($_GET['status']=='IssueDocs'){
		$xcrud->button('IssueDocs.php?id={customer_id}&Uname=\'' . $Uname . '\'','scan','fa fa-qrcode','');
	}
}
/*
if($_GET['status']=='SemiSuccessfull'){
	$xcrud->button('javascript:;','Update Registration No','fa fa-bolt','',array('data-toggle'=>'modal','data-target'=>'#updateRegistrationNoModal','onclick'=>'updateRegistrationNo({customer_id})'));
}*/
?>
<style>
	.bold-remark {
    font-weight: bold;
}
</style>	
<?php

if($_GET['status']!='Pending' && $_GET['status']!='Upload' && $_GET['status']!='Payment'){
	$xcrud->column_pattern('order_status', '<a href="javascript:changeOrderStatus({customer_id}, \'' . $Uname . '\')">{value}</a>');
	$xcrud->column_pattern('receive', '<a href="javascript:changeReceiveStatus({customer_id}, \'' . $Uname . '\')">{value}</a>');
	$xcrud->column_pattern('fittment', '<a href="javascript:changeFittmentStatus({customer_id}, \'' . $Uname . '\')">{value}</a>');
}

if($_GET['status']!='Pending' && $_GET['status']!='Upload' && $_GET['status']!='Payment' && $_GET['status']=='hsrp' && $type=='admin')
{
	$xcrud->column_pattern('order_status', '<a href="javascript:changeOrderStatus({customer_id}, \'' . $Uname . '\')">{value}</a>');
	$xcrud->column_pattern('receive', '<input name="choice[]" type="checkbox" value="{customer_id}" /><a href="javascript:changeReceiveStatus({customer_id}, \'' . $Uname . '\')">{value}</a>');
	$xcrud->column_pattern('fittment', '<a href="javascript:changeFittmentStatus({customer_id}, \'' . $Uname . '\')">{value}</a>');
}
if($_GET['status']=='Proceed')
{
	//$xcrud->column_pattern('status', '<input name="choice[]" type="checkbox" value="{customer_id}" /><a href="javascript:changeProceedStatus({customer_id}, \'' . $Uname . '\')">{value}</a>');
	$xcrud->column_pattern('status', '<input name="choice[]" type="checkbox" value="{customer_id}" /><a href="javascript:openProceedModal({customer_id}, \'' . $Uname . '\')">{value}</a>');
	$xcrud->button('javascript:;','Revert Status','fa fa-mail-reply','',array('data-toggle'=>'modal','data-target'=>'#revertStatsuModal','onclick'=>'revertStatus({customer_id})'));
}
if($_GET['status']=='RC'){
	$xcrud->button('javascript:;','Change Status','fa fa-check','',array('data-toggle'=>'modal','data-target'=>'#registerStatusModal','onclick'=>'registeStatus({customer_id})'));
}

//$xcrud->button('javascript:;','Compare','fa fa-exchange','',array('data-toggle'=>'modal','data-target'=>'#compareModal','onclick'=>'getCompareData({customer_id})'));

$xcrud->set_attr('status',array('id'=>'custStatus','onChange'=>'checkStatus(this.value)'));
$xcrud->set_attr('customer_id',array('id'=>'customer_id'));

$xcrud->label('order_status','Order');

?>

<div class="row">
<?php
if($_GET['status']=='Upload'){
	echo '<div class="col-sm-10"><button class="btn btn-blue btn-block">Customer</button></div><div class="col-sm-2"><a class="btn btn-blue btn-block" href="compare_data">Compare Data</a></div>';
}else{
	echo '<div class="col-sm-12"><button class="btn btn-blue btn-block">Customer</button></div>';
}
?>

	
	<div class="col-sm-12">&nbsp</div>
<?php
if ($_REQUEST["status"]=="hsrp") {
?>
	<div class="row" style="margin-left: 10px;margin-right: 10px;">
		<div class="row fileupload-buttonbar">
			<div class="col-lg-12">
				<form method="post" enctype="multipart/form-data">
					<span class="btn btn-success fileinput-button"><input type="file" name="lid_file" accept=".xls,.xlsx"></span>
					<button type="submit" name="update_lid" class="btn btn-primary start"><i class="glyphicon glyphicon-upload"></i><span>Update</span></button>
					<button type="reset" class="btn btn-warning cancel"><i class="glyphicon glyphicon-file"></i><span><a href="uploads/HSRP Installation Dealer Report.xlsx">Sample</a></span></button>
				</form>
			</div>
			
		</div>
	</div>
<?php
}
?>
	<div class="col-sm-12">	
	<?php
		if(isset($_POST['submit_late_by'])){
			$late_by_start_date=$_POST['late_by_start_date']." 00:00:00";
			$late_by_end_date=$_POST['late_by_end_date']." 23:59:59";
			$late_by_status=trim($_POST['late_by_status']);
			if($late_by_status=="Register"){
				$xcrud->where("(register_time>='{$late_by_start_date}' AND register_time<='{$late_by_end_date}') AND (NOW()>=register_time)");
			}else if($late_by_status=="IssueDocs"){ 
				$xcrud->where("(issue_docs_time>='{$late_by_start_date}' AND issue_docs_time<='{$late_by_end_date}') AND (NOW()>=issue_docs_time)");
			}
		}
		echo $xcrud->render();
		
	?>
	</div>
	
<?php
	if($_GET['status']=='hsrp' && $type=='admin')
	{
?>
		<div class="col-sm-12" style="display:none"> 		
			Select Rec All <input type="checkbox" name="select-all" id="select-all" />
			<input type="submit" name="submit" value="Submit" class=""/>
		</div>
<?php
	} else if($_GET['status']=='Proceed' && $type=='admin')
	{
?>
		<div class="col-sm-12"> 		
			Select Rec All <input type="checkbox" name="select-all" id="select-all" />
			<input type="submit" name="Proceed" value="Submit" class=""/>
		</div>
<?php
	}
?>
	</div>

<?php
if(isset($_GET['status']) && ($_GET['status']=='Register' || $_GET['status']=='IssueDocs')){
?>
	<div class="row" style="margin-bottom:10px">
		<form method="POST">
		<input type="hidden" value="<?php echo $_GET['status'];?> " name="late_by_status" required>
		<div class="col-sm-2">
			<input type="date" class="form-control" name="late_by_start_date" required>
		</div>
		<div class="col-sm-2">
			<input type="date" class="form-control" name="late_by_end_date" required>
		</div>
		<div class="col-sm-2">
			<button class="btn btn-primary" name="submit_late_by">Search Late By</button>
		</div>
		</form>
	</div>
<?php } ?>
</div>

<!-- Change Proceed Status model-->
<div id="changeProceedStatusModal" class="modal fade" role="dialog">
  <div class="modal-dialog modal-sm">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <!--<button type="button" class="close" data-dismiss="modal">&times;</button>-->
        <h4 class="modal-title">Do you want to proceed?</h4>
      </div>
      <div class="modal-body">
         <form method="post">
			<input type="hidden" id="hidden_change_proceed_status_customer_id">
<?php
$bdd=new DB();
$rto_rows=$bdd->getAll("SELECT * FROM rto");
$bdd->disconnect();
echo "<select class='form-control' id='change_proceed_status_rto' required>";
echo "<option value=''>Select RTO</option>";
foreach($rto_rows as $rto_row){
	echo "<option value='{$rto_row['id']}'>{$rto_row['name']}</option>";
}
echo "</select>";
?>
			<select class='form-control' id='smc_applicable' name='smc_applicable' required>
				<option value=''>Select SMC Applicable</option>
				<option value='Yes'>Yes</option>
				<option value='No'>No</option>
			</select>
			<button type="button" onClick="changeProceedStatus('0','<?php echo $Uname;?>')" name="submit_insp_status" class="btn btn-success" style="margin-top:5px;width: 30%;;margin-right:35%">Proceed</button>
			<button type="button" class="btn btn-info" data-dismiss="modal" onClick="closeProceedStatusModal()" style="margin-top:5px;width: 30%;">Close</button>
		</form>
      </div>
      <!--<div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal" onClick="closeInspStatusModal()">Close</button>
      </div>-->
    </div>
  </div>
</div>

<!-- Compare data model-->
<div id="compareModal" class="modal fade" role="dialog">
  <div class="modal-dialog modal-lg">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Customer compare data</h4>
      </div>
      <div class="modal-body">
		<div id="customer_compare_data_div"></div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- Change update Status model-->
<div id="uploadStatusModal" class="modal fade" role="dialog">
  <div class="modal-dialog modal-sm">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <!--<button type="button" class="close" data-dismiss="modal">&times;</button>-->
        <h4 class="modal-title">Is Additional selected?</h4>
      </div>
      <div class="modal-body">
         <form method="post" name="upload_status_form">
			<input type="hidden" id="hidden_upload_status_modal_customer_id">
			<b>Password:</b> <input class="form-control" type="password" id="update_product_password">
			<button type="button" onClick="updateCompletedStatus('0','<?php echo $Uname;?>')" name="submit_upload_status" class="btn btn-success" style="margin-top:5px;width: 30%;margin-right:35%">Update</button>
			<button type="button" class="btn btn-info" data-dismiss="modal" onClick="closeUploadStatusModal()" style="margin-top:5px;width: 30%;">Close</button>
		</form>
      </div>
      <!--<div class="modal-footer">
		<button type="button" onClick="updateCompletedStatus('0','<?php echo $Uname;?>')" name="submit_upload_status" class="btn btn-info" style="margin-top:5px;width: 100%;">Yes</button>
        <button type="button" class="btn btn-info" data-dismiss="modal" onClick="closeUploadStatusModal()">No</button>
      </div>-->
    </div>
  </div>
</div>

<!-- Change Insp update Status model-->
<div id="uploadInspStatusModal" class="modal fade" role="dialog">
  <div class="modal-dialog modal-sm">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <!--<button type="button" class="close" data-dismiss="modal">&times;</button>-->
        <h4 class="modal-title">Is Additional selected?</h4>
      </div>
      <div class="modal-body">
         <form method="post" name="upload_status_form">
			<input type="hidden" id="hidden_insp_status_modal_customer_id">
			<b>Password:</b> <input class="form-control" type="password" id="update_insp_product_password">
			<button type="button" onClick="changeInspStatus('0','<?php echo $Uname;?>')" name="submit_insp_status" class="btn btn-success" style="margin-top:5px;width: 30%;;margin-right:35%">Update</button>
			<button type="button" class="btn btn-info" data-dismiss="modal" onClick="closeInspStatusModal()" style="margin-top:5px;width: 30%;">Close</button>
		</form>
      </div>
      <!--<div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal" onClick="closeInspStatusModal()">Close</button>
      </div>-->
    </div>
  </div>
</div>

<!-- Change Insp update Status model-->
<div id="checkInspReceiptModal" class="modal fade" role="dialog">
  <div class="modal-dialog modal-sm">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <!--<button type="button" class="close" data-dismiss="modal">&times;</button>-->
        <h4 class="modal-title">Check SMC Tax Receipt</h4>
      </div>
      <div class="modal-body">
			<p><b>Please upload SMC Tax Receipt file</b></p>
         <form method="post" name="upload_status_form">
			<input type="hidden" id="hidden_insp_receipt_modal_customer_id">
			<!--<button type="button" onClick="updateInspStatus('0','<?php echo $Uname;?>')" name="submit_insp_status" class="btn btn-success" style="margin-top:5px;width: 30%;;margin-right:35%">Update</button>-->
			<button type="button" class="btn btn-info" data-dismiss="modal" onClick="closeInspReceiptModal()" style="margin-top:5px;width: 30%;">Close</button>
		</form>
      </div>
    </div>
  </div>
</div>

<!-- cusomer Remark model-->
<div id="customerRemarkModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Customer Remaks</h4>
      </div>
      <div class="modal-body">
         <form method="post" name="customer_remark_form">
			<input type="hidden" name="hidden_customer_id">
			<input type="text" class="form-control" name="customer_name" style="width: 60%;float: left;margin-right: 5px;" readonly>
			<input type="text" class="form-control" name="contact_no" style="width: 30%;" readonly>
			<div>Remark:<textarea class="form-control" name="remark" required></textarea></div>
			<button type="submit" name="submit_cust_remark" class="btn btn-info" style="margin-top:5px">Submit</button>
		</form>
		<table id="customer_remark_list" class="table" style="margin-top:5px"></table>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- Customer Modal -->
<div id="custInfoModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Update Customer Detail</h4>
      </div>
      <div class="modal-body">
         <form method="post">
			<input type="hidden" id="hidden_cust_id" name="hidden_cust_id">
			<div><b>Name:</b><input type="text" class="form-control" name="name" id="name"></div>
			<div class="form-group"><b>Contact No:</b><input type="text" class="form-control" name="contact_no" id="contact_no"></div>
			<div><b>Chassis No:</b>
				<!--<input type="text" class="form-control" name="chassis_no" id="chassis_no" pattern=".{8,}" title="Please enter at least 8 characters">-->
				<input class="form-control" type="text" placeholder="Chassis No." id="chassis_no" name="chassis_no">
			</div>
			<div><b>Allotment No:</b><input type="text" class="form-control" name="AllotmentNo" id="AllotmentNo"></div>	
			<?php
			if($_GET['status']!='hsrp'){
			$bdd = new DB();
			
			$query = "SELECT * FROM product";
			$products = $bdd->getAll($query);
			?>

			<div><b>Product:</b></div>
			<div>
			<select class="form-control" name="Product" required id="product" onChange="UpdateMeterNo(this)">
			<option value="">---</option>
				<?php
				// Check if products were fetched successfully
				if ($products) {
					foreach ($products as $product) {
						// Use the product data to populate the select options
						echo '<option value="' . $product['name'] . '">' . $product['name'] . '</option>';
					}
				} else {
					echo '<option value="">No products available</option>';
				}
			?>
			</select>
			</div>
			
			<div><b>Meter Make:</b></div>
			<div>
			<select class="form-control" name="meter_make" id="meter_make">
			<option value="">Select Make</option>
				<?php
				$make_query = "SELECT * FROM meter_make";
				$meter_make_result = $bdd->getAll($make_query);
				// Check if products were fetched successfully
				if ($meter_make_result) {
					foreach ($meter_make_result as $make) {
						// Use the product data to populate the select options
						echo '<option value="' . $make['id'] . '">' . $make['name'] . '</option>';
					}
				} else {
					echo '<option value="">No Make available</option>';
				}
			?>
			</select>
			</div>
			<div><b>Meter No:</b><input type="text" class="form-control" name="meter_no" id="meter_no"></div>
			<?php
				$bdd->disconnect();
			}
			?>
			<button type="submit" name="submit_cust_info" class="btn btn-info" style="margin-top:5px">Submit</button>
		</form> 
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<div id="RemarkInfoModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Remark Customer</h4>
      </div>
      <div class="modal-body">
         <form method="post">
		 <input type="hidden" id="hidden_Remark_id" name="hidden_Remark_id">
		  <div>Remark:<input type="text" class="form-control" name="Remark" id="Remark"></div>
		  
		  <button type="submit" name="submit_Remark_info" class="btn btn-info" style="margin-top:5px">Submit</button>
		</form> 
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<div id="CustomerInfo" class="modal fade" role="dialog">
  <div class="modal-dialog modal-lg">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Customer Info</h4>
      </div>
      <div class="modal-body">
         
		 <input type="hidden" id="hidden_Remark_id" name="hidden_Remark_id">
		  <div>Customer Info:</div>
		  
		 
      </div>
    </div>
  </div>
</div>

<div id="taxReceiptModal" class="modal fade" role="dialog">
  <div class="modal-dialog modal-sm">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Remove Tax Receipt</h4>
      </div>
      <div class="modal-body">
		<!--<a href="scanImage.php?id={customer_id}&Uname='$Uname'&type=remove"><Button type="btn" style="width:100%">Remvoe</Button></a>-->
		<a href="#" id="tax_receipt_link"><Button type="btn" style="width:100%">Remvoe</Button></a>
      </div>
    </div>
  </div>
</div>
<!-- Revert Status Modal -->
<div id="revertStatsuModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Do you really want to revert status.</h4>
      </div>
      <div class="modal-body">
		<form method="post">
			<input type="hidden" id="hidden_customer_id" name="hidden_customer_id">
			<button type="submit" name="submit_revert_status" class="btn btn-info" style="margin-top:5px">Submit</button>
		</form>
      </div>
    </div>
  </div>
</div>

<!-- Register Status Modal -->
<div id="registerStatusModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Do you really want to change status to Register.</h4>
      </div>
      <div class="modal-body">
		<form method="post">
			<input type="hidden" id="hidden_register_status_customer_id" name="hidden_register_status_customer_id">
			<button type="submit" name="submit_register_status" class="btn btn-info" style="margin-top:5px">Submit</button>
		</form>
      </div>
    </div>
  </div>
</div>

<!-- Register Modal -->
<div id="updateRegistrationNoModal" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Update Update Registration No</h4>
      </div>
      <div class="modal-body">
		<!--<form method="post">
			<input type="text" id="hidden_cust_id1" name="hidden_cust_id1">
			<div>Name:<input type="text" class="form-control" name="name1" id="name1" readonly></div>
			<div>Registration No:<input type="text" class="form-control" name="registration_no" id="registration_no" value="GJ-" autofocus></div>
			
			<button type="submit" name="submit_registration_no" class="btn btn-info" style="margin-top:5px">Submit</button>
		</form>!-->
		<script> var pathpermit = ""; var pathfitness = ""; var cid = ""; </script>
		Permit:
		<a id="permitjpg" style="display:none" href="javascript:void(0);" onclick="newPopup('permit');">
        <img id="permitjpgimg" style="width: 80%;" src=""></a>

		<a style="display:none" id="permitpdf" href="">PDF</i></a>
<?php	if($type=='admin'){ ?>
		&nbsp<span id="permitdel"  class="btn btn-danger btnhide" onclick="delete_file(pathpermit,cid,'permit')" style="float: right;padding: 0px; display:none;" ><i class="glyphicon glyphicon-remove"></i></span>
<?php }else{ ?>
	<span id="permitdel"></span>
<?php }?>
		<br>

		<div id="permitdiv">
			<form method="post" enctype="multipart/form-data">
				<input type="hidden" id="hidden_cust_id1" name="hidden_cust_id1">
				<br>
				<input type="file" id="permit" name="permit" REQUIRED onchange="checkexe('permit')">
				<br>
				<input type="submit" name="permit_upload" class="button" value="Permit-Upload" id="but_permit">
			</form>
		</div>
		
		<br>
		

      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
<!--</form>-->

<!-- User Task Remark model-->
<!--
<div id="taskremarkModal" class="modal fade" role="dialog">
  <div class="modal-dialog modal-lg">
    
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">Task Remak</h4>
      </div>
      <div class="modal-body">
		
		<form method="post">
			<input type="text" name="hidden_task_user_id" id="hidden_task_user_id">
			<textarea class="form-control" name="taskremark" id="taskremark"></textarea>
			<button type="submit" class="btn btn-success">SAVE</button>
		</form>
		
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>
-->
<?php
include "footer.php";
echo Xcrud::load_js();

if(isset($_POST['submit_cust_remark'])){
	$bdd=new DB();
	$date=date('Y-m-d H:i:s');
	$result=$bdd->execute("INSERT INTO `customer_remark` (`customer_id`, `remark`, `datetime`) VALUES ('".$_POST['hidden_customer_id']."', '".$_POST['remark']."', '$date')");
	$bdd->disconnect();
}

if(isset($_POST['submit_revert_status'])){
	$bdd=new DB();
	$crow=$bdd->getOne('SELECT chassis_no FROM customer WHERE customer_id='.$_POST['hidden_customer_id']);
	$bdd->execute("UPDATE customer SET status = 'Allotment' WHERE customer_id=".$_POST['hidden_customer_id']);
	$bdd->disconnect();
	
	//update revert status in to ticl detail databae
	$url= web_constant::$ip_ticl."api.php";
	$ch = curl_init();
	curl_setopt($ch, CURLOPT_URL,$url);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query(array('type' => 'revertSelectStatus','ChassisNo'=>$crow['chassis_no'])));
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	$output = curl_exec($ch);
	curl_close($ch);
}

if(isset($_POST['submit_register_status'])){
	$current_register_time=date('Y-m-d H:i:s',strtotime('+1 week'));
	
	$bdd=new DB();
	$bdd->execute("UPDATE customer SET register_time='$current_register_time',status = 'Register' WHERE customer_id=".$_POST['hidden_register_status_customer_id']);
	
	$existingEntries = $bdd->getOne("SELECT * FROM modification WHERE CId =". $_POST['hidden_register_status_customer_id']);
	if ($existingEntries > 0) {
		$bdd=new DB();
		$resu=$bdd->execute("UPDATE modification SET Rc = '$Uname',Rc_date='$current_datetime' WHERE CId=".$_POST['hidden_register_status_customer_id']);
		$bdd->disconnect();
	} else {
		$bdd=new DB();
		$insertResult = $bdd->execute("INSERT INTO modification (Rc, Rc_date, CId) VALUES ('$Uname','$current_datetime',$user_id)");
		$bdd->disconnect();
	}
		
	$bdd->disconnect();
	echo "<script>window.location='customer?status=RC'</script>";
}

if(isset($_POST['permit_upload']))
{
	$user_id = $_POST['hidden_cust_id1'];
	$bdd=new DB();

	$crow=$bdd->getOne('SELECT name,contact_no,date,chassis_no,date FROM customer WHERE customer_id='.$_POST['hidden_cust_id1']);
	
	$bdd->disconnect();
		
	$year=date('Y',strtotime($crow['date']));
	$month=date('m',strtotime($crow['date']));
	$directory_path = "uploads/".$year."/".$month."/".$crow['name']."-".$crow['contact_no'].'-'.$crow['chassis_no'];
    
    // Retrieve the uploaded permit file
    $permit_name = basename($_FILES["permit"]["name"]);
	
    $permit_target_file = $directory_path .'/'. $permit_name ;

    $permitFileType = pathinfo($permit_target_file,PATHINFO_EXTENSION);


	if(strtolower($permitFileType)=='pdf'){
		$name = "Permit.pdf";
		$permit_target_file = $directory_path .'/Permit.pdf' ;
	}
	elseif(strtolower($permitFileType)=='jpg'){
		$name = "Permit.jpg";
		$permit_target_file = $directory_path .'/Permit.jpg' ;
	}

	if (move_uploaded_file($_FILES["permit"]["tmp_name"], $permit_target_file)) {
		$bdd=new DB();
		$result=$bdd->execute("UPDATE customer SET permit='".$name."',status = 'FullSuccessfull' WHERE customer_id=".$_POST['hidden_cust_id1']);
		$bdd->disconnect();

		$bdd=new DB();
		$existingEntries = $bdd->getOne("SELECT * FROM modification WHERE CId =". $_POST['hidden_cust_id1']);
		$bdd->disconnect();
		if ($existingEntries > 0) {
			$bdd=new DB();
			$resu=$bdd->execute("UPDATE modification SET Register = '$Uname' WHERE CId=".$_POST['hidden_cust_id1']);
			$bdd->disconnect();
		} else {
			$bdd=new DB();
			$insertResult = $bdd->execute("INSERT INTO modification (Register, CId) VALUES ('$Uname',$user_id)");
			$bdd->disconnect();
		}

		echo "<script>alert('The files have been uploaded ad Customet is set to Full Successfull.');location.href='customer?status=".$_GET['status']."';</script>";
	} else {
		echo "<script>alert('Sorry, there was an error uploading your files.');location.href='customer?status=".$_GET['status']."';</script>";
	}
}

if(isset($_POST['fitness_upload']))
{
	$user_id = $_POST['hidden_cust_id2'];
	$bdd=new DB();

	$crow=$bdd->getOne('SELECT name,contact_no,date,chassis_no,date FROM customer WHERE customer_id='.$_POST['hidden_cust_id2']);
	
	$bdd->disconnect();
		
	$year=date('Y',strtotime($crow['date']));
	$month=date('m',strtotime($crow['date']));
	$directory_path = "uploads/".$year."/".$month."/".$crow['name']."-".$crow['contact_no'].'-'.$crow['chassis_no'];

    // Retrieve the uploaded fitness file
    $fitness_name = basename($_FILES["fitness"]["name"]);
	
    $fitness_target_file = $directory_path .'/'. $fitness_name;

	$fitnessFileType = pathinfo($fitness_target_file,PATHINFO_EXTENSION);

    $fitnessFileName = pathinfo($fitness_target_file,PATHINFO_FILENAME);
   
	if(strtolower($fitnessFileType)=='pdf'){
		$name = "Fitness.pdf";
		$fitness_target_file = $directory_path .'/Fitness.pdf' ;
	}
	elseif(strtolower($fitnessFileType)=='jpg'){
		$name = "Fitness.jpg";
		$fitness_target_file = $directory_path .'/Fitness.jpg' ;
	}

	if (move_uploaded_file($_FILES["fitness"]["tmp_name"], $fitness_target_file)) {
		$bdd=new DB();
		$result=$bdd->execute("UPDATE customer SET fitness='".$name."' WHERE customer_id=".$_POST['hidden_cust_id2']);
		$bdd->disconnect();
		echo "<script>alert('The files have been uploaded.');location.href='customer?status=".$_GET['status']."';</script>";
	} else {
		echo "<script>alert('Sorry, there was an error uploading your files.');location.href='customer?status=".$_GET['status']."';</script>";
	}
}


if(isset($_POST['submit_registration_no']))
{
	$user_id = $_POST['hidden_cust_id1'];
	$bdd=new DB();
	$crow=$bdd->getOne('SELECT registration_no FROM customer WHERE customer_id='.$_POST['hidden_cust_id1']);
	$bdd->disconnect();
	if($crow['registration_no']==$_POST['registration_no'])
	{
		echo "<script>alert('You did not update anything')</script>";
	}
	else
	{
		$bdd=new DB();
		$result=$bdd->execute("UPDATE customer SET registration_no='".$_POST['registration_no']."', status='hsrp' WHERE customer_id=".$_POST['hidden_cust_id1']);
		$bdd->disconnect();		

		if($result){

			$bdd=new DB();
			$existingEntries = $bdd->getOne("SELECT * FROM modification WHERE CId =". $_POST['hidden_cust_id1']);
			$bdd->disconnect();
			if ($existingEntries > 0) {
				$bdd=new DB();
				$resu=$bdd->execute("UPDATE modification SET Semi = '$Uname',Semi_date='$current_datetime' WHERE CId=".$_POST['hidden_cust_id1']);
				$bdd->disconnect();
			} else {
				$bdd=new DB();
				$insertResult = $bdd->execute("INSERT INTO modification (Semi, Semi_date, CId) VALUES ('$Uname','$current_datetime',$user_id)");
				$bdd->disconnect();
			}

			echo "<script>alert('Customer update Successfuly');location.href='customer?status=".$_GET['status']."';</script>";
		}
		else
		{
			echo "<script>alert('Error while updating. Try again')</script>";
		}
	}
}

if(isset($_POST['submit_cust_info']))
{
	$user_id = $_POST['hidden_cust_id'];
	$meter_make = $_POST['meter_make'] ?: NULL;
	$meter_no = $_POST['meter_no'] ?: NULL;
	
	$bdd=new DB();
	$name = preg_replace('/\s+/', '_', $_POST['name']);
	$crow=$bdd->getOne('SELECT name,contact_no,date,chassis_no,AllotmentNo,date,documents,Product,make,meter_no FROM customer WHERE customer_id='.$_POST['hidden_cust_id']);
	$bdd->disconnect();
	$say=1;
	if($crow['name']==$name && $crow['contact_no']==$_POST['contact_no'] && $crow['chassis_no']==$_POST['chassis_no']&& $crow['AllotmentNo']==$_POST['AllotmentNo'] && $crow['Product']==$_POST['Product'] && $crow['make']==$_POST['meter_make'] && $crow['meter_no']==$_POST['meter_no']){
		echo "<script>alert('You did not update anything')</script>";
	}else{
		
		$bdd=new DB();
		$result=$bdd->execute("UPDATE customer SET name='".$name."',contact_no='".$_POST['contact_no']."',chassis_no='".$_POST['chassis_no']."',AllotmentNo='".$_POST['AllotmentNo']."',Product='".$_POST['Product']."',make=" . (!$meter_make ? 'NULL' : (int)$meter_make) . ",meter_no=" . (!$meter_no ? 'NULL' : "'".$meter_no."'") . "  WHERE customer_id=".$_POST['hidden_cust_id']);
		$bdd->disconnect();
		if($result){

			if($_GET['status']=='Pending')
			{
				
				$bdd=new DB();
				$row=$bdd->getOne('SELECT name,contact_no,date,chassis_no,status as stb FROM customer WHERE customer_id='.$_POST['hidden_cust_id']);
				$bdd->disconnect();
				$year=date('Y',strtotime($row['date']));
				$month=date('m',strtotime($row['date']));
				$status = $row['stb'];
				$pathA="uploads/".$year."/".$month."/".$row['name']."-".$row['contact_no'].'-'.$row['chassis_no'];

				$fileNames = ["IdProof", "AddressProof", "SIGN"];

				$allFilesExist = true;

				foreach ($fileNames as $fileName) {
					$fileFound = false;
					$files = scandir($pathA);
					
					foreach ($files as $file) {
						if (strpos($file, $fileName) === 0) {
							$fileFound = true;
							break;
						}
					}
				
					if (!$fileFound) {
						$allFilesExist = false;
						break; 
					}
				}

				if ($allFilesExist) {
					$current_allotment_time=date('Y-m-d H:i:s',strtotime('1 hour'));
					$bdd=new DB();
					$result=$bdd->execute("UPDATE customer SET allotment_time='$current_allotment_time',documents='Half-Done',status = 'Allotment' WHERE customer_id=".$_POST['hidden_cust_id']);
					$bdd->disconnect();

					$bdd=new DB();
					$insertResult = $bdd->execute("INSERT INTO modification (Pending,Pending_date, CId) VALUES ('$Uname','$current_datetime',$user_id)");
					$bdd->disconnect();
				} else {
					echo "<script>alert('Upload all the necessary documents to continue')</script>";
					$say=0;
				}


			} else if($_GET['status']=='Allotment'){
				
				if (date('H') > 16){
					$current_proceed_time=date('Y-m-d H:i:s',strtotime('18 hour'));	
				}else{
					$current_proceed_time=date('Y-m-d H:i:s',strtotime('1 hour'));
				}
				
				$bdd=new DB();
				$result=$bdd->execute("UPDATE customer SET proceed_time='$current_proceed_time',status = 'Proceed' WHERE customer_id=".$_POST['hidden_cust_id']);
				$bdd->disconnect();
				
				/*$url= web_constant::$ip_ticl."api.php";
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL,$url);
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query(array('type' => 'getBillNo','ChassisNo'=>$_POST['chassis_no'])));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				$output = curl_exec($ch);
				curl_close($ch);
				
				$output_array=json_decode($output,true);
				$bill_no=trim($output_array['bill_no']);
				
				if($bill_no!=""){
					$bill_file_path=$_SERVER['DOCUMENT_ROOT']."scanner/uploads/bill_no/{$bill_no}.pdf";
					
					$year=date('Y',strtotime($crow['date']));
					$month=date('m',strtotime($crow['date']));

					$destination_file=$_SERVER['DOCUMENT_ROOT']."scanner/uploads/".$year."/".$month."/".$crow['name']."-".$crow['contact_no'].'-'.$_POST['chassis_no'].'/MfgInvoice.pdf';

					copy($bill_file_path, $destination_file);
				}*/

				$bdd=new DB();
				$existingEntries = $bdd->getOne("SELECT * FROM modification WHERE CId =". $_POST['hidden_cust_id']);
				$bdd->disconnect();
  				if($existingEntries > 0){
					if($existingEntries['Allotment']!=$Uname){
						$bdd=new DB();
						$result=$bdd->execute("UPDATE modification SET Allotment = '$Uname',Allotment_date='$current_datetime' WHERE CId=".$_POST['hidden_cust_id']);
						$bdd->disconnect();
					}
				} else {
					$bdd=new DB();
					$insertResult = $bdd->execute("INSERT INTO modification (Allotment, Allotment_date, CId) VALUES ('$Uname','$current_datetime',$user_id)");
					$bdd->disconnect();
				}
				//update in to ticl detail databae
				$url= web_constant::$ip_ticl."api.php";
				$ch = curl_init();
				curl_setopt($ch, CURLOPT_URL,$url);
				curl_setopt($ch, CURLOPT_POST, 1);
				curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query(array('type' => 'setSelectStatus','ChassisNo'=>$_POST['chassis_no'])));
				curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
				$output = curl_exec($ch);
				curl_close($ch);
				
			} else {
				echo "<script>alert('Upload all the necessary documents to continue')</script>";
			}
			$year=date('Y',strtotime($crow['date']));
			$month=date('m',strtotime($crow['date']));
			$directory_path = 'uploads/'.$year.'/'.$month.'/';
			
			rename($directory_path.$crow['name'].'-'.$crow['contact_no'].'-'.$crow['chassis_no'],$directory_path.$name.'-'.$_POST['contact_no'].'-'.$_POST['chassis_no']);
			if($say==1){
				echo "<script>alert('Customer update Successfuly');location.href='customer?status=".$_GET['status']."';</script>";
			} else {
				echo "<script>location.href='customer?status=".$_GET['status']."';</script>";
			}
		}else{
			echo "<script>alert('Error while updating. Try again')</script>";
		}
	}
}

if(isset($_POST['submit_Remark_info']))
{
	$bdd=new DB();
	$crow=$bdd->getOne('SELECT Remark FROM customer WHERE customer_id='.$_POST['hidden_Remark_id']);
	$bdd->disconnect();
	if($crow['Remark']==$_POST['Remark']){
		echo "<script>alert('You did not update anything')</script>";
	}else{
		$bdd=new DB();
		$result=$bdd->execute("UPDATE customer SET Remark='".$_POST['Remark']."'  WHERE customer_id=".$_POST['hidden_Remark_id']);
		$bdd->disconnect();
		if($result){
			
			$bdd=new DB();
			$result=$bdd->execute("UPDATE customer SET status = 'Upload' WHERE customer_id=".$_POST['hidden_Remark_id']);
			$bdd->disconnect();
			
			echo "<script>alert('Customer Remark Successfuly');location.href='customer?status=".$_GET['status']."';</script>";
		}else{
			echo "<script>alert('Error while updating. Try again')</script>";
		}
	}
}


if(isset($_POST['submit']) )
{
	if($_POST['choice'])
	{
		$i=0;
		$updated=array();
		$AlreadyUpdated=array();
		$NotUpdated=array();

		foreach($_POST['choice'] as $val)
		{
			$array[$i] = $val;				

			$bdd=new DB();
			$crow=$bdd->getOne("SELECT receive FROM customer WHERE customer_id=".$array[$i]);
			$bdd->disconnect();

			if($crow['receive']=='0')
			{
				$td=date('Y-m-d');
				$bdd=new DB();
				$result=$bdd->execute("UPDATE customer SET receive='1', receive_date='$td', status='Fitment' WHERE customer_id=".$array[$i]);
				$bdd->disconnect();

				$bdd=new DB();
				$existingEntries = $bdd->getOne("SELECT * FROM modification WHERE CId =". $array[$i]);
				$bdd->disconnect();
  				if ($existingEntries > 0) {
					$bdd=new DB();
					$resu=$bdd->execute("UPDATE modification SET Hsrp = '$Uname',Hsrp_date='$current_datetime' WHERE CId=".$array[$i]);
					$bdd->disconnect();
				} else {
					$user_id = $array[$i];
					$bdd=new DB();
					$insertResult = $bdd->execute("INSERT INTO modification (Hsrp,Hsrp_date, CId) VALUES ('$Uname','$current_datetime',$user_id)");
					$bdd->disconnect();
				}

				if($result)
				{
					$updated[$i] = $array[$i];
					$status = 1;
				}
				else
				{
					$NotUpdated[$i] = $array[$i];
				}
			}
			else
			{
				$AlreadyUpdated[$i] = $array[$i];
			}
			$i++;
		}
	}
	if($status==1)
	{
		echo "<script>alert('Receive Updated')</script>";
	}
	else
	{
		echo "<script>alert('Error. Try Again')</script>";
	}
	header( "Location: customer.php?status=hsrp");
}

if(isset($_POST['Proceed']) )
{
	if($_POST['choice'])
	{
		$i=0;
		$updated=array();
		$AlreadyUpdated=array();
		$NotUpdated=array();

		foreach($_POST['choice'] as $val)
		{
			$array[$i] = $val;				

			$bdd=new DB();
			$result=$bdd->execute("UPDATE customer SET status='Upload' WHERE customer_id=".$array[$i]);
			$bdd->disconnect();

			$bdd=new DB();
			$existingEntries = $bdd->getOne("SELECT * FROM modification WHERE CId =". $array[$i]);
			$bdd->disconnect();
			if ($existingEntries > 0) {
				$bdd=new DB();
				$resu=$bdd->execute("UPDATE modification SET Proceed = '$Uname',Proceed_date='$current_datetime' WHERE CId=".$array[$i]);
				$bdd->disconnect();
			} else {
				$user_id = $array[$i];
				$bdd=new DB();
				$insertResult = $bdd->execute("INSERT INTO modification (Proceed,Proceed_date, CId) VALUES ('$Uname','$current_datetime',$user_id)");
				$bdd->disconnect();
			}

			if($result)
			{
				$updated[$i] = $array[$i];
				$status = 1;
			}
			else
			{
				$NotUpdated[$i] = $array[$i];
			}
			
			$i++;
		}
	}
	if($status==1)
	{
		echo "<script>alert('Proceed Updated')</script>";
	}
	else
	{
		echo "<script>alert('Error. Try Again')</script>";
	}
	header( "Location: customer.php?status=Proceed");
}

if (isset($_POST["update_lid"])){
	print_r($_POST);
	$bdd=new DB();
	$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
  echo "Type:".$_FILES["lid_file"]["type"];
	if(in_array($_FILES["lid_file"]["type"],$allowedFileType)){
        $targetPath = 'temp/'.$_FILES['lid_file']['name'];
        move_uploaded_file($_FILES['lid_file']['tmp_name'], $targetPath);
        $Reader = new SpreadsheetReader($targetPath);
        $sheetCount = count($Reader->sheets());
        for($i=0;$i<$sheetCount;$i++){
            $Reader->ChangeSheet($i);
            foreach ($Reader as $Row){
				$chassis_no = preg_replace('!\s+!', ' ',$Row[0]);
				$reg_no = preg_replace('!\s+!', ' ',$Row[1]);
				$front_lid = preg_replace('!\s+!', ' ',$Row[2]);
				$rear_lid = preg_replace('!\s+!', ' ',$Row[3]);
				$date=date('Y-m-d');
                if (!empty($chassis_no) && !empty($reg_no) && !empty($front_lid) && !empty($rear_lid)) {
					$hsrpRow=$bdd->getOne("SELECT customer_id FROM `customer` WHERE complete_chassis_no='$chassis_no' AND registration_no='$reg_no' AND status='hsrp' AND front_lid IS NULL AND rear_lid IS NULL");
					if(!empty($hsrpRow)){
						//echo "<br>Cust:".$hsrpRow['customer_id'];
						$bdd->execute("UPDATE customer SET front_lid='$front_lid', rear_lid='$rear_lid',receive='1',receive_date='$date',status='Fitment' WHERE customer_id='".$hsrpRow['customer_id']."'");
						$existingEntries = $bdd->getOne("SELECT * FROM modification WHERE CId =". $hsrpRow['customer_id']);
						if ($existingEntries > 0) {
							$resu=$bdd->execute("UPDATE modification SET Hsrp = '$Uname',Hsrp_date='$current_datetime' WHERE CId=".$hsrpRow['customer_id']);
						} else {
							$user_id = $hsrpRow['customer_id'];
							$insertResult = $bdd->execute("INSERT INTO modification (Hsrp,Hsrp_date, CId) VALUES ('$Uname','$current_datetime',$user_id)");
						}
					}
                }
             }
		}
		echo "<script>alert('Detail updated');</script>";
	}else{ 
		echo "<script>alert('Invalid File Type. Upload Excel File');</script>";
	}
	$bdd->disconnect();
}
?>

<script type="text/javascript">

function updateCustRemarkInfo(id){
	dataString='action=updateCustRemarkInfo&id='+id;
	
	$.ajax({
		type:'POST',
		url:'ajax_data.php',
		data:dataString,
		success:function(data){
				value=JSON.parse(data);
				document.customer_remark_form.elements['hidden_customer_id'].value=value['customer'].customer_id
				document.customer_remark_form.elements['customer_name'].value=value['customer'].name
				document.customer_remark_form.elements['contact_no'].value=value['customer'].contact_no
				$('#customer_remark_list').html(value['remark'])
		}
	});
}

function delete_file(path,cid,name){
	if (confirm("Are you sure you want to delete this file ?")) {
		$.ajax({
			type: "GET",
			url: "ImageLap.php",
			data: ({
				location: path,
				name: name,
				id: cid
			}),
			cache: false,
			success: function(html) {
			//	alert(html);
				$("#orgImg" + i).remove();
				$("#btnMain" + i).remove();
				window.location.reload();
			}
		});
	} else {
		return false;
	}
}
function changeOrderStatus(id,Uname){
	dataString='action=changeOrderStatus&id='+id+'&Uname='+Uname;
	$.ajax({
		type:'POST',
		url:'ajax_data.php',
		data:dataString,
		success:function(data){
			value=JSON.parse(data);
			alert(value.message);
			location.reload();
		}
	});
}

function changeReceiveStatus(id,Uname){
	dataString='action=changeReceiveStatus&id='+id+'&Uname='+Uname;
	$.ajax({
		type:'POST',
		url:'ajax_data.php',
		data:dataString,
		success:function(data){
			value=JSON.parse(data);
			alert(value.message);
			location.reload();
		}
	});
}

function openProceedModal(id,uname){
	$('#hidden_change_proceed_status_customer_id').val(id);
	var locModal = document.getElementById('changeProceedStatusModal');
	locModal.style.display = "block";
	locModal.classList.add("in");
	locModal.style.paddingRight = "17px";
}

function changeProceedStatus(id,Uname){
	var id=$('#hidden_change_proceed_status_customer_id').val();
	var rto=$('#change_proceed_status_rto').val();
	var smc=$('#smc_applicable').val();
	if(rto==""){
		alert("select RTO");
	}else if(smc==""){
		alert("select SMC");
	}else{
		dataString='action=changeProceedStatus&id='+id+'&Uname='+Uname+'&rto='+rto+'&smc='+smc;
		if(id!="" || rto!=""){
			$.ajax({
				type:'POST',
				url:'ajax_data.php',
				data:dataString,
				success:function(data){
					value=JSON.parse(data);
					//alert(value.message);
					location.reload();
				}
			});
		}else{
			alert("something went wrong. contact developer");
		}
	}
}

function changeFittmentStatus(id,Uname){
	dataString='action=changeFittmentStatus&id='+id+'&Uname='+Uname;
	$.ajax({
		type:'POST',
		url:'ajax_data.php',
		data:dataString,
		success:function(data){
			value=JSON.parse(data);
			alert(value.message);
			location.reload();
		}
	});
}

function CustomerInfo(id) {
    dataString='action=CustomerInfo&id='+id;
	
    $.ajax({
        type: 'POST',
        url: 'ajax_data.php',
		data:dataString,
        success: function (response) {
            $('#CustomerInfo .modal-body').html(response);
        }
    });
}


function openLocation(id){
	dataString='action=openLocation&id='+id;
	$.ajax({
		type:'POST',
		url:'ajax_data.php',
		data:dataString,
		success:function(data){
			//alert(data);
			window.location=data;
		}
	});
}
function openLocationPath(id){
	dataString='action=openLocationPath&id='+id;
	$.ajax({
		type:'POST',
		url:'ajax_data.php',
		data:dataString,
		success:function(data){
			prompt('Path',data);
		}
	});
}

function checkStatus(value){
	var id=$("input[name=primary]").val();
	if(value=="Payment"){
		dataString='action=checkStatus&id='+id;
		$.ajax({
			type:'POST',
			url:'ajax_data.php',
			data:dataString,
			success:function(data){
				if(data==0){
					alert('Please Upload All Documents');
					$('#custStatus').val('Completed');
				}
			}
		});
	}
}

function updateCustInfo(id){
	dataString='action=updateCustInfo&id='+id;
	$.ajax({
		type:'POST',
		url:'ajax_data.php',
		data:dataString,
		success:function(data){
				value=JSON.parse(data);
				$('#hidden_cust_id').val(id);
				$('#name').val(value.name);
				$('#contact_no').val(value.contact_no);
				$('#chassis_no').val(value.chassis_no);
				$('#AllotmentNo').val(value.AllotmentNo);
				$('#product').val(value.product);
				$('#meter_make').val(value.make);
				$('#meter_no').val(value.meter_no);
		}
	});
}

function changeStatus(id,Uname,product){
	/*if(product!="4s"){
		$('#hidden_insp_status_modal_customer_id').val(id);
		var locModal = document.getElementById('uploadInspStatusModal');
		locModal.style.display = "block";
		locModal.classList.add("in");
		locModal.style.paddingRight = "17px";
	}else{
		updateInspStatus(id,Uname)
	}*/
	
	
	dataString='action=checkSmcStatus&id='+id;
	$.ajax({
		type:'POST',
		url:'ajax_data.php',
		data:dataString,
		success:function(data){
			value=JSON.parse(data);
			//alert(value.status);
			if(value.status=='success'){
				updateInspStatus(id,Uname)
			}else if(value.status=='error'){
				//alert("Please upload SMC tax receipt");
				$('#hidden_insp_receipt_modal_customer_id').val(id);
				var locModal = document.getElementById('checkInspReceiptModal');
				locModal.style.display = "block";
				locModal.classList.add("in");
				locModal.style.paddingRight = "17px";
			}
		}
	});
}

function changeInspStatus(id,Uname){
	if(id=="0"){
		var temp_id=document.getElementById('hidden_insp_status_modal_customer_id').value;
		id=temp_id
	}
	var update_insp_product_password=document.getElementById('update_insp_product_password').value;
	if(update_insp_product_password!=<?php echo "'".$security_password_row['password']."'";?>){
		alert('Password not match');
		return false;
	}else{
		updateInspStatus(id,Uname)
	}
}
function closeInspStatusModal(){
	var locModal = document.getElementById('uploadInspStatusModal');
	locModal.style.display = "none";
	locModal.classList.remove("in");
}

function closeInspReceiptModal(){
	var locModal = document.getElementById('checkInspReceiptModal');
	locModal.style.display = "none";
	locModal.classList.remove("in");
}

function closeProceedStatusModal(){
	var locModal = document.getElementById('changeProceedStatusModal');
	locModal.style.display = "none";
	locModal.classList.remove("in");
}



function updateInspStatus(id,Uname){
	if(id=="0"){
		var temp_id=document.getElementById('hidden_insp_receipt_modal_customer_id').value;
		id=temp_id
	}
	dataString='action=changeStatus&id='+id+'&Uname='+Uname;
	$.ajax({
		type:'POST',
		url:'ajax_data.php',
		data:dataString,
		success:function(data){
			value=JSON.parse(data);
			alert(value.message);
			location.reload();
		}
	});
}

function changeRegister(id,Uname){
	var isConfirmed = confirm("Are you sure you want to send to Issue Docs?");

    if (isConfirmed) {
		dataString='action=changeRegister&id='+id+'&Uname='+Uname;
		$.ajax({
			type:'POST',
			url:'ajax_data.php',
			data:dataString,
			success:function(data){
				value=JSON.parse(data);
				alert(value.message);
				location.reload();
			}
		});
	} else {
		alert("Canceld")
	}
}

function changeCompletedStatus(id,Uname,product){
	if(product!="4s"){
		$('#hidden_upload_status_modal_customer_id').val(id);
		var locModal = document.getElementById('uploadStatusModal');
		locModal.style.display = "block";
		locModal.classList.add("in");
		locModal.style.paddingRight = "17px";
	}else{
		updateCompletedStatus(id,Uname)
	}
}

function closeUploadStatusModal(){
	var locModal = document.getElementById('uploadStatusModal');
	locModal.style.display = "none";
	locModal.classList.remove("in");
}

function updateCompletedStatus(id,Uname){
	if(id=="0"){
		var temp_id=document.getElementById('hidden_upload_status_modal_customer_id').value;
		var update_product_password=document.getElementById('update_product_password').value;
		if(update_product_password!=<?php echo "'".$security_password_row['password']."'";?>){
			alert('Password not match');
			return false;
		}
		id=temp_id
	}
	dataString='action=changeCompletedStatus&id='+id+'&Uname='+Uname;
	$.ajax({
		type:'POST',
		url:'ajax_data.php',
		data:dataString,
		success:function(data){
			console.log(data);
			value=JSON.parse(data);
			alert(value.message);
			location.reload();
		}
	});
}

function updateRemark(id){
	$('#hidden_Remark_id').val(id);
}

function updateRegistrationNo(id){
	dataString='action=updateRegistrationNo&id='+id;
	$.ajax({
		type:'POST',
		url:'ajax_data.php',
		data:dataString,
		dataType: 'json',
		success:function(response){
			if(response.permitpdf!="nothing")
			{
				pathpermit = response.permitpdf;
				document.getElementById('permitdel').style.display = "block";
				document.getElementById('permitpdf').style.display = "block";
				document.getElementById('permitdiv').style.display = "none";
				document.getElementById('permitpdf').href = response.permitpdf;
			}
			else if(response.permitjpg!="nothing")
			{
				pathpermit = response.permitjpg;
				document.getElementById('permitdel').style.display = "block";
				document.getElementById('permitjpg').style.display = "block";
				document.getElementById('permitdiv').style.display = "none";
				document.getElementById('permitjpgimg').src = response.permitjpg;
			}
			if(response.fitnesspdf!="nothing")
			{
				pathfitness = response.fitnesspdf;
				document.getElementById('fitnessdel').style.display = "block";
				document.getElementById('fitnesspdf').style.display = "block";
				document.getElementById('fitnessdiv').style.display = "none";
				document.getElementById('fitnesspdf').href = response.fitnesspdf;
			}
			else if(response.fitnessjpg!="nothing")
			{
				pathfitness = response.fitnessjpg;
				document.getElementById('fitnessdel').style.display = "block";
				document.getElementById('fitnessjpg').style.display = "block";
				document.getElementById('fitnessdiv').style.display = "none";
				document.getElementById('fitnessjpgimg').src = response.fitnessjpg;
			}
			var name = response.name;
			cid = response.id;
			$('#hidden_cust_id1').val(id);
			$('#hidden_cust_id2').val(id);
			$('#name1').val(name);
		}
	});
}

$(document).ready(function() {
	$(document).trigger('xcrudafterrequest');
  $("#registration_no").keyup(function(event) {
	var letters = /^[A-Za-z]+$/;
	var num = /^-{0,1}\d+$/;
	var $this = $(this);
	var input = $this.val();
	$this.val(input.toUpperCase());
	//GJ-05-AB-1234
	var str1 = input.substring(0, 2);
	var num1 = input.substring(3, 5);
	var str2 = input.substring(6, 8);
	var num2 = input.substring(9, 13);
	
	if(!str1.match(letters)){
		alert('First two values are not letters');
		return false;
    }
	if(num1.length>1 && !num1.match(num)){
		alert('Forth or fifth values are not numeric');
		$("#registration_no").focus();
		return false;
	}
	if(str2.length>1 && !str2.match(letters)){
		alert('Seventh or eighth values are not letters');
		$("#registration_no").focus();
		return false;
    }
	if(num2.length>1 && !num2.match(num)){
		alert('Last four values are not numeric');
		$("#registration_no").focus();
		return false;
	}
	
	input = input.replace(/[\W\s\._\-]+/g, '');	 
	
	var split = 4;
	var chunk = [];
	 
	for (var i = 0, len = input.length; i < len; i += split) {
		//split = ( i >= 2 && i <= 8 ) ? 4 : 2;
		split = ( i <= 4 ) ? 2 : 4;
		chunk.push( input.substr( i, split ) );
	}
	
	$this.val(function() {
		return chunk.join("-").toUpperCase();
	});	
  });
  
  $("#chassis_no").autocomplete({
		source: function( request, response ) {
			//var table_type=$("#table_type").val()
			$.ajax({
				url: "autosugestion_data.php",
				type: 'post',
				dataType: "json",
				data: {
					search:request.term,
					action:'searchChassiNo'
					//table_name:table_type
					
				},
				success: function( data ) {
					response( data );
				}
			});
		},
		select: function (event, ui) {
			$('#chassis_no').val(ui.item.id)
			return false
		}
	});
	
});
/*$(document).ready(function() {
   $('.csv_password').on('click', function() {
        var csv_pass=prompt('enter password');
        var data_csv_string="action=cvs_password&csv_pass="+csv_pass;
        $.ajax({
            type:'POST',
            url:'ajax_data.php',
            data:data_csv_string,
            success:function(data){
            	alert(data);
                if(data==0){
                	window.location.replace('home.php');
                    //window.location='home.php';         
                }
            }
        });
   });
});*/

//Select all checkbox script

    $('#select-all').click(function(event) {   
    if(this.checked) {
        $(':checkbox').each(function() {
            this.checked = true;                        
        });
    } else {
        $(':checkbox').each(function() {
            this.checked = false;                       
        });
    }
}); 

function checkexe(name){
	
	var name = name;

	const filename = event.target.files[0].name;
   
	const extension = filename.split('.').pop().toLowerCase();
	   
   if (extension!="pdf" && extension!="jpg") {
	   alert(`Please upload PDF or JPG file`);
	   if(name=="fitness")
	   {
		document.getElementById("but_fitness").disabled = true;
	   }
	   else if(name=="permit"){
		document.getElementById("but_permit").disabled = true;
	   } 
	}else{
		if(name=="fitness")
		{
			document.getElementById("but_fitness").disabled = false;
		}
		else if(name=="permit"){
			document.getElementById("but_permit").disabled = false;
		}
   }
}
function newPopup(val){
	if(val=="permit"){
		var img = document.getElementById('permitjpg');
	}
	else if(val=="fitness"){
		var img = document.getElementById('fitnessjpg');
	}
	var currentSize = img.style.transform;

	if (currentSize === 'scale(1.5)') {
		img.style.transform = 'scale(1)';
	} else {
		img.style.transform = 'scale(1.5)';
	}
}

function revertStatus(id){
	$("#hidden_customer_id").val(id);
}
function registeStatus(id){
	$("#hidden_register_status_customer_id").val(id);
}

function getCompareData(id){
	dataString='action=getCustomerCompareData&id='+id;
	$.ajax({
		type:'POST',
		url:'ajax_data.php',
		data:dataString,
		success:function(data){
			value=JSON.parse(data);
			//value=data;
			var data_str="<table  class='table-bordered'><tr><th></th><th>Name</th><th>Chassis</th><th>Engin</th><th>Sale Amount</th><th>Hypo</th></tr>";
			data_str+="<tr><td>DISCLAIMER</td><td>"+value.dname+"</td><td>"+value.dchassis+"</td><td>"+value.dengin+"</td><td>"+value.dsale_amount+"</td><td>"+value.dhypo+"</td></tr>"
			data_str+="<tr><td>TaxInvoice</td><td>"+value.iname+"</td><td>"+value.ichassis+"</td><td>"+value.iengin+"</td><td>"+value.isale_amount+"</td><td>"+value.ihypo+"</td></tr>"
			data_str+="<tr><td>Result</td><td>"+value.is_name+"</td><td>"+value.is_chassis+"</td><td>"+value.is_engin+"</td><td>"+value.is_sale_amount+"</td><td>"+value.is_hypo+"</td></tr>"
			data_str+="</table>";
			$("#customer_compare_data_div").html(data_str);
		}
	});
}

function UpdateMeterNo(data){
	var product=data.value.toLowerCase();
	if(product.indexOf('cargo') > -1){
		//alert(data.value);
		$('#meter_no').val("N.A.");
		$('#meter_make').val("4");
	}else{
		$('#meter_make').val("");
		$('#meter_no').val("");
	}
}

function setTaxReceiptInfo(id){
	const tax_rec_url="scanImage.php?id="+id+"&Uname='<?php echo $Uname ?>'&type=remove";
	$("#tax_receipt_link").attr("href",tax_rec_url);
}

/*function openTaskremarkModal(id){
	document.getElementById('hidden_task_user_id').value=id;
	var locModal = document.getElementById('taskremarkModal');
	locModal.style.display = "block";
	locModal.classList.add("in");
	locModal.style.paddingRight = "17px";
}*/

function parseDate(str) {
	//return new Date(str.replace(' ', 'T'));
    let [datePart, timePart] = str.split(' ');
    let [day, month, year] = datePart.split('/').map(Number);
    let [hour, minute, second] = timePart.split(':').map(Number);
    return new Date(year, month - 1, day, hour, minute, second);
}

function padZero(num) {
  return num.toString().padStart(2, '0');
}

$(document).on('xcrudafterrequest', function() {
    
	$('.xcrud-list tbody tr').each(function() {
		let xcrud_task_date="";
		let xcrud_task_status = $(this).find('td').eq(14).text().trim();
		
		if(xcrud_task_status=='Pending'){
			xcrud_task_date = $(this).find('td').eq(28).text().trim();
		}else if(xcrud_task_status=='Allotment'){
			xcrud_task_date = $(this).find('td').eq(29).text().trim();
		}else if(xcrud_task_status=='Proceed'){
			xcrud_task_date = $(this).find('td').eq(30).text().trim();
		}else if(xcrud_task_status=='Upload'){
			xcrud_task_date = $(this).find('td').eq(31).text().trim();
		}else if(xcrud_task_status=='Insp'){
			xcrud_task_date = $(this).find('td').eq(32).text().trim();
		}else if(xcrud_task_status=='Payment'){
			xcrud_task_date = $(this).find('td').eq(33).text().trim();
		}else if(xcrud_task_status=='SemiSuccessfull'){
			xcrud_task_date = $(this).find('td').eq(34).text().trim();
		}else if(xcrud_task_status=='hsrp'){
			xcrud_task_date = $(this).find('td').eq(35).text().trim();
		}else if(xcrud_task_status=='Fitment'){
			xcrud_task_date = $(this).find('td').eq(36).text().trim();
		}else if(xcrud_task_status=='Ready'){
			xcrud_task_date = $(this).find('td').eq(37).text().trim();
		}else if(xcrud_task_status=='RC'){
			xcrud_task_date = $(this).find('td').eq(38).text().trim();
		}else if(xcrud_task_status=='Register'){
			xcrud_task_date = $(this).find('td').eq(39).text().trim();
		}else if(xcrud_task_status=='IssueDocs'){
			xcrud_task_date = $(this).find('td').eq(40).text().trim();
		}
		
        
		
		let xcrud_cust_date = $(this).find('td').eq(13);
		
		//console.log('Status:'+xcrud_task_status+'Date:'+xcrud_task_date);
		
		if(xcrud_task_date!=""){
			let current_date_time = new Date();
			let task_date_time = parseDate(xcrud_task_date);
			
			//console.log('current Date'+current_date_time+' Task date: '+task_date_time);
			
			if(current_date_time>task_date_time){
				let late_by="";
				//let diffMs = current_date_time - task_date_time;
				//let diffMins = Math.floor(diffMs / (1000 * 60));
				
				let diffMs = current_date_time - task_date_time;

				if (diffMs < 0) {
				  diffMs = Math.abs(diffMs);
				}

				let totalSeconds = Math.floor(diffMs / 1000);
				let weeks = Math.floor(totalSeconds / (7 * 24 * 60 * 60));
				totalSeconds %= 7 * 24 * 60 * 60;

				let days = Math.floor(totalSeconds / (24 * 60 * 60));
				totalSeconds %= 24 * 60 * 60;

				let hours = padZero(Math.floor(totalSeconds / (60 * 60)));
				totalSeconds %= 60 * 60;

				let minutes = padZero(Math.floor(totalSeconds / 60));
				let seconds = padZero(totalSeconds % 60);

				if(weeks>0)
					late_by+=`${weeks} week, ${days} days, ${hours}:${minutes}:${seconds}`;
				else if(days>0)
					late_by+=`${days} days, ${hours}:${minutes}:${seconds}`;
				else if(hours>0)
					late_by+=`${hours}:${minutes}:${seconds}`;
				else if(minutes>0)
					late_by+=`${minutes}:${seconds}`;
				
				let date_value=xcrud_cust_date.text().trim();
				
				var $row = $(this);
				var $actionsTd = $row.find('td:last-child');
				var rowId = $actionsTd.find('a[data-primary]').first().data('primary');
				
				var link = $('<a></a>')
                .html(date_value+` <br>late by ${late_by} `)
                .attr('href', '#')
                .css({ color: 'red', 'font-weight': 'bold' })
                .on('click', function(e) {
                    e.preventDefault();
                    openTaskremarkModal(rowId,xcrud_task_status);
                });
				xcrud_cust_date.html(link);
			}
		}
    });
});
</script>