<?php
include_once('DB.php');
date_default_timezone_set("Asia/Kolkata");
$current_datetime=date("Y-m-d H:i:s");
require_once 'web_constant.php';

$api_key="6Ex633K1l0K0OiqKlnZcDcbHsUICoaXl";
$authorization_key="6GXYMuS9EvUQCfMM9G97sl539umoyJw6pWb6WHKxXDG4dC0m9N4O6Q4aZHBaKldu";
$patronID="64b945ac63936b00237f2c38";

function checkAllDocStatus($id,$Uname){
	$Uname = $_POST['Uname'];
	$bdd=new DB();
	$crow=$bdd->getOne("SELECT order_status,receive,fittment,fitness,permit,rcCopy,status FROM customer WHERE customer_id=".$_POST['id']);
	$bdd->disconnect();
	if($crow['order_status']=='1' && $crow['receive']=='1' && $crow['fittment']=='1' && $crow['fitness']!='' && $crow['permit']!='' && $crow['rcCopy']!='' && $crow['status']!='FullSuccessfull'){
		$bdd=new DB();
		$result=$bdd->execute("UPDATE customer SET status='FullSuccessfull' WHERE customer_id=".$_POST['id']);
		$bdd->disconnect();

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

if($_POST['action']=='getTaskRemarkReport'){
	$report_end_date="";
	$data=array();
	$bdd=new DB();
	
	$rows=$bdd->getAll("SELECT * FROM task_remark WHERE customer_id='{$_POST['id']}'  ORDER BY id ASC");
	
	
	if(!empty($rows)){
		foreach($rows as $row){
			$late_by="";
			if($row['status']=='Pending'){
				$report_end_date='created_date';
			}else if($row['status']=='Allotment'){
				$report_end_date='allotment_time';
			}else if($row['status']=='Proceed'){
				$report_end_date='proceed_time';
			}else if($row['status']=='Upload'){
				$report_end_date='upload_time';
			}else if($row['status']=='Insp'){
				$report_end_date='insp_time';
			}else if($row['status']=='Payment'){
				$report_end_date='payment_time';
			}else if($row['status']=='SemiSuccessfull'){
				$report_end_date='semi_successfull_time';
			}else if($row['status']=='hsrp'){
				$report_end_date='hsrp_time';
			}else if($row['status']=='Fitment'){
				$report_end_date='fitment_time';
			}else if($row['status']=='Ready'){
				$report_end_date='ready_time';
			}else if($row['status']=='RC'){
				$report_end_date='rc_time';
			}else if($row['status']=='Register'){
				$report_end_date='register_time';
			}else if($row['status']=='IssueDocs'){
				$report_end_date='issue_docs_time';
			}
			
			$date_row=$bdd->getOne("SELECT $report_end_date FROM customer WHERE customer_id='{$_POST['id']}'");
			
			$date1 = new DateTime($date_row[$report_end_date]);
			$date2 = new DateTime(date('Y-m-d H:i:s'));
			
			$diff = $date1->diff($date2);
			$totalDays = $diff->days;
			$weeks = floor($totalDays / 7);
			$days = $totalDays % 7;

			$late_by="{$weeks} week, {$days} days, {$diff->h}:{$diff->i}:{$diff->s}";
			
			/*$dateTimeObject1 = date_create($date_row[$report_end_date]); 
			$dateTimeObject2 = date_create(date('Y-m-d H:i:s'));
			$interval = date_diff($dateTimeObject2, $dateTimeObject1);
			$late_by=$interval->format('%a Days %H:%I:%S');*/
			
			/*if($row['status']=='Allotment'){
				$date_row=$bdd->getOne("SELECT timediff(allotment_time,created_date) as late_by FROM customer WHERE customer_id='{$_POST['id']}'");
				$late_by=$date_row['late_by'];
			}*/
			
			
			echo "<tr><td>{$row['status']}</td><td>$late_by</td><td>{$row['remark']}</td></tr>";
		}
	}else{
		echo "<tr><td>No remark found</td></tr>";
	}
	$bdd->disconnect();
}

if($_POST['action']=='getTaskRemark'){
	$data=array();
	$bdd=new DB();
	$row=$bdd->getOne("SELECT remark FROM task_remark WHERE customer_id='{$_POST['id']}' AND status='{$_POST['status']}'");
	$bdd->disconnect();
	
	if(!empty($row)){
		$data['status']='success';
		$data['remark']=$row['remark'];
	}else{
		$data['status']='fail';
	}
	
	echo json_encode($data);
}

if($_POST['action']=='updateTaskRemark'){
	
	$date_time=date('Y-m-d H:i:s');
	$data=array();
	$bdd=new DB();
	
	$task_row=$bdd->getOne("SELECT remark FROM task_remark WHERE customer_id='{$_POST['id']}' AND status='{$_POST['status']}'");
	
	if(!empty($task_row)){
		$bdd->execute("UPDATE task_remark SET remark='{$_POST['remark']}',date_time='$date_time' WHERE customer_id='{$_POST['id']}' AND status='{$_POST['status']}'");
	}else{
		$bdd->execute("INSERT INTO task_remark (`customer_id`, `status`, `remark`, `date_time`) VALUES ('{$_POST['id']}', '{$_POST['status']}', '{$_POST['remark']}', '$date_time');");
	}
	
	$bdd->disconnect();
	
	$data['status']='success';
	
	echo json_encode($data);
}
if($_POST['action']=='getCompareData'){
	$myObj = new stdClass();
	$myObj->inv_img = $_POST['inv_img'];
	$myObj->dis_img = $_POST['dis_img'];
	$myJSON = json_encode($myObj);
	
	$base64_str=base64_encode($myJSON);
	$output=shell_exec("python compare.py " .$base64_str);
	echo $output;
}

if($_POST['action']=='checkSmcStatus'){
	$data=array();
	$bdd=new DB();
	$row=$bdd->getOne('SELECT smc,SMCtaxReceipt FROM customer WHERE customer_id='.$_POST['id']);
	$bdd->disconnect();
	
	if($row['smc']=='Yes' && $row['SMCtaxReceipt']=="SMCtaxReceipt.pdf"){
		$data['status']='success';
	}else{
		$data['status']='error';
	}
	echo json_encode($data);
}

if($_POST['action']=='getCustomerCompareData'){
	$bdd=new DB();
	$crow=$bdd->getOne('SELECT compare_data FROM customer WHERE customer_id='.$_POST['id']);
	$bdd->disconnect();
	echo $crow['compare_data'];
}

if($_POST['action']=='updateCustomerStatus'){
	$bdd=new DB();
	
	if($_POST['status']=="Accept"){
		$crow=$bdd->getOne('SELECT name,contact_no,date,chassis_no FROM customer WHERE customer_id='.$_POST['customer_id']);
		$chassis_no=$crow['chassis_no'];
		$result=$bdd->execute("UPDATE customer SET salesman='".$_POST['salesman_id']."',status='Pending',chassis_no='".$_POST['chassis_no']."' WHERE customer_id=".$_POST['customer_id']);
		$year=date('Y',strtotime($crow['date']));
		$month=date('m',strtotime($crow['date']));
		$directory_path = 'uploads/'.$year.'/'.$month.'/';
		
		try{
			rename($directory_path.$crow['name'].'-'.$crow['contact_no'].'-'.$crow['chassis_no'],$directory_path.$crow['name'].'-'.$crow['contact_no'].'-'.$_POST['chassis_no']);
		}catch(Exception $e) {
			echo 'Message: ' .$e->getMessage();
		}
	}else{
		$result=$bdd->execute("UPDATE customer SET status='Reject' WHERE customer_id=".$_POST['customer_id']);
	}
	
	$bdd->disconnect(); 
}

if($_POST['action']=='verificationApi'){
	
	if($_POST['doc_type']=="AadharCard"){
		/*$url = 'https://api.apiclub.in/uat/v1/aadhaar_v2/send_otp';
		$headers = array(
			'API-KEY: '.$api_key,
			'Referer: docs.apiclub.in',
			'accept: application/json',
			'content-type: application/json',
		);
		$data = array(
			'aadhaar_no' => $_POST['doc_value']
		);*/
		
		$url = 'https://api-preproduction.signzy.app/api/v3/getOkycOtp';
		$headers = array(
			'Authorization:'.$api_key,
			'Content-Type: application/json',
		);
		$data = array(
			'aadhaarNumber' => $_POST['doc_value']
		);

		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		$response = curl_exec($ch);
		$err = curl_error($ch);
		curl_close($ch);
		echo $response;
		//echo '{"code":200,"status":"success","response":{"ref_id":"aclb65a7-130e-4aec-acec-bfcba28099a3","message":"OTP has been sent"}}';
		//echo '{"data":{"requestId":"650c172c3734fd55d2301194","otpSentStatus":true,"if_number":true,"isValidAadhaar":true,"status":"generate_otp_success"},"statusCode":200,"message":"OTP Sent."}';
		//echo '{"error":{"name":"error","message":"Aadhaar is not valid","status":400,"reason":"BadRequest","type":"OK","statusCode":200}}';
	} else if($_POST['doc_type']=="ElectionCard"){ 
		/*$url = 'https://api.apiclub.in/uat/v1/verify_votercard';
		$headers = array(
			'API-KEY: '.$api_key,
			'Referer: docs.apiclub.in',
			'accept: application/json',
			'content-type: application/json',
		);
		$data = array(
			'voter_id' => $_POST['doc_value']
		);*/
		
		$url = 'https://preproduction.signzy.tech/api/v2/patrons/'.$patronID.'/voterIdV2';
		//$url = 'https://signzy.tech/api/v2/patrons/'.$user_id.'/voterIdV2';
		$headers = array(
			'Authorization: '.$authorization_key,
			'Content-Type: application/json',
		);
		$data = array(
			'task' => "epicNumberSearch",
			'essentials' => array(
				'epicNumber' => $_POST['doc_value'],
				'state' => $_POST['voter_state']
			)
		);

		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		$response = curl_exec($ch);
		$err = curl_error($ch);
		curl_close($ch);
		echo $response;
		
		//echo '{"essentials":{"epicNumber":"YMC5429469","state":"gujarat"},"id":"650e78989669a400226cb6f2","patronId":"64b945ac63936b00237f2c38","task":"epicNumberSearch","result":{"name":"CHHAGANBHAI PARMAR","dob":"","district":"Surat","state":"GUJARAT","fatherName":"NAROTTAMBHAI PARMAR","gender":"Male"}}';
		//echo "";
	}else if($_POST['doc_type']=="PanCard"){
		$url = 'https://preproduction.signzy.tech/api/v2/patrons/'.$patronID.'/panv2';
		//$url = 'https://signzy.tech/api/v2/patrons/...patronID.../panv2';
		$headers = array(
			'Authorization: '.$authorization_key,
			'Content-Type: application/json',
		);
		$data = array(
			'task' => "fetch",
			'essentials' => array(
				'number' => $_POST['doc_value']
			)
		);

		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
		curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		$response = curl_exec($ch);
		$err = curl_error($ch);
		curl_close($ch);
		echo $response;
		//echo '{"essentials":{"number":"CLZPP4628P"},"id":"650d714f9669a400226cac19","patronId":"64b945ac63936b00237f2c38","task":"fetch","result":{"name":"MACHHI CHAGANBHAI NAROTAMBHAI","number":"CLZPP4628P","typeOfHolder":"Individual or Person","isIndividual":true,"isValid":true,"firstName":"MACHHI","middleName":"CHAGANBHAI","lastName":"NAROTAMBHAI","title":"Shri","panStatus":"VALID","panStatusCode":"E","aadhaarSeedingStatus":"Successful","aadhaarSeedingStatusCode":"Y","lastUpdatedOn":"27/07/2019"}}';
		//echo '{"error":{"statusCode":400,"name":"error","message":"PAN number is not valid","status":400}}';
	}
	
}

if($_POST['action']=='verifyAadhaarOtp'){
	/*$url = 'https://api.apiclub.in/uat/v1/aadhaar_v2/submit_otp';
		
	$headers = array(
		'API-KEY: '.$api_key,
		'Referer: docs.apiclub.in',
		'accept: application/json',
		'content-type: application/json',
	);
	$data = array(
		'ref_id' => $_POST['ref_id'],
		'otp'=> $_POST['aadhaar_otp']
	);*/
	$url = 'https://api-preproduction.signzy.app/api/v3/fetchOkycData';
	$headers = array(
		'Authorization:'.$api_key,
		'Content-Type: application/json',
	);
	$data = array(
		'requestId' => $_POST['ref_id'],
		'otp' => $_POST['aadhaar_otp'],
	);

	$ch = curl_init($url);
	curl_setopt($ch, CURLOPT_POST, 1);
	curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
	curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

	$response = curl_exec($ch);
	$err = curl_error($ch);
	curl_close($ch);
	echo $response;
	//echo '{"code":200,"status":"success","response":{"request_id":"aclb65a7-130e-4aec-acec-bfcba28099a3","aadhar":"XXXXXXXX0791","name":"Dummy Name","care":"dummy care of","dob":"1601-05-16","gender":"M","address":{"country":"India","dist":"Delhi-dist","state":"Delhi-state","po":"Pitampura","loc":"","vtc":"","subdist":"","street":"Pitampura","house":"121","landmark":"Near Pitampura"},"image":"{{base64 image}}","share_code":"9999","zip_file":"{{zip file url}}"}}';
	//echo '{"data":{"client_id":null,"full_name":null,"aadhaar_number":null,"dob":null,"gender":null,"address":{"country":null,"dist":null,"state":null,"po":null,"loc":null,"vtc":null,"subdist":null,"street":null,"house":null,"landmark":null},"face_status":false,"face_score":-1,"zip":null,"profile_image":null,"has_image":null,"email_hash":null,"mobile_hash":null,"raw_xml":null,"zip_data":null,"care_of":null,"share_code":null,"mobile_verified":null,"reference_id":null,"aadhaar_pdf":null,"status":null,"uniqueness_id":null},"statusCode":422,"message":"OTP Already Submitted."}';
}	

if($_POST['action']=='openOption')
{
	$id=$_POST['id'];
	include('xcrud/xcrud.php');
	echo Xcrud::load_css();
	$xcrud_op=Xcrud::get_instance();
	$xcrud_op->table('menu_option');
	$xcrud_op->where('menu_id',$id);
	$xcrud_op->relation('menu_id','menu','menu_id','menu_name');
	$xcrud_op->pass_default('menu_id',$id);
	$xcrud_op->columns('menu_id', true);
	$xcrud_op->unset_title();
	$xcrud_op->unset_print();
	$xcrud_op->unset_csv();
	$xcrud_op->unset_search();
	$xcrud_op->unset_limitlist();
	$xcrud_op->label('menu_id','Menu');
	$xcrud_op->readonly('menu_id');
	$xcrud_op->after_insert('update_menu_option_after_insert', 'functions.php');
	$xcrud_op->after_update('update_menu_option_after_update','functions.php');
	echo $xcrud_op->render();
	echo Xcrud::load_js();
}
if($_POST['action']=='openLocation')
{
	$IP = $_SERVER['SERVER_ADDR'];
	$id=$_POST['id'];
	$bdd=new DB();
	$row=$bdd->getOne('SELECT name,contact_no,date,chassis_no FROM customer WHERE customer_id='.$id);
	$bdd->disconnect();
	$year=date('Y',strtotime($row['date']));
	$month=date('m',strtotime($row['date']));
	//$path ='scanner\uploads\\'.$year.'\\'.$row['name'].'-'.$row['contact_no'];
	//exec('start \\\\192.168.31.145\\'.$path);
	$path ='http://'.web_constant::$ip_port.'/scanner/uploads/'.$year.'\\'.$month.'\\'.$row['name'].'-'.$row['contact_no'].'-'.$row['chassis_no'];
	//$path ='http://'.$IP.':8080/scanner/uploads/'.$year.'\\'.$month.'\\'.$row['name'].'-'.$row['contact_no'].'-'.$row['chassis_no'];
	echo $path;
}

if($_POST['action']=='openLocationPath')
{
	$id=$_POST['id'];
	$bdd=new DB();
	$row=$bdd->getOne('SELECT name,contact_no,date,chassis_no FROM customer WHERE customer_id='.$id);
	$bdd->disconnect();
	$year=date('Y',strtotime($row['date']));
	$month=date('m',strtotime($row['date']));
	$path="\\\\".web_constant::$only_ip."\scanner\uploads\\".$year."\\".$month."\\".$row['name']."-".$row['contact_no'].'-'.$row['chassis_no'];
	echo $path;
}

if($_POST['action']=='search_customer_record')
{
	include ('xcrud/xcrud.php');
	echo Xcrud::load_css();
	$customer_name=$_POST['customer_name'];

	$xcrud_sc=Xcrud::get_instance();
	$xcrud_sc->table('customer');
	$xcrud_sc->relation('added_by','user','user_id','name');
	$xcrud_sc->where('',"`customer`.`name` LIKE '$customer_name%'");
	$xcrud_sc->unset_add();
	$xcrud_sc->unset_edit();
	$xcrud_sc->unset_remove();
	$xcrud_sc->unset_print();
	$xcrud_sc->unset_csv();
	$xcrud_sc->unset_title();
	$xcrud_sc->unset_search();
	//$xcrud_sc->unset_view();
	$xcrud_sc->unset_limitlist();
	echo $xcrud_sc->render();
	echo Xcrud::load_js();
}
if($_POST['action']=='search_customer_contactNO_record')
{
	include ('xcrud/xcrud.php');
	echo Xcrud::load_css();
	$contact_no=$_POST['contact_no'];

	$xcrud_sc=Xcrud::get_instance();
	$xcrud_sc->table('customer');
	$xcrud_sc->relation('added_by','user','user_id','name');
	$xcrud_sc->where('',"`customer`.`contact_no` LIKE '$contact_no%'");
	$xcrud_sc->unset_add();
	$xcrud_sc->unset_edit();
	$xcrud_sc->unset_remove();
	$xcrud_sc->unset_print();
	$xcrud_sc->unset_csv();
	$xcrud_sc->unset_title();
	$xcrud_sc->unset_search();
	//$xcrud_sc->unset_view();
	$xcrud_sc->unset_limitlist();
	echo $xcrud_sc->render();
	echo Xcrud::load_js();
}

if($_POST['action']=='search_customer_chassisNo_record')
{
	include ('xcrud/xcrud.php');
	echo Xcrud::load_css();
	$chassis_no=$_POST['chassis_no'];

	$xcrud_sc=Xcrud::get_instance();
	$xcrud_sc->table('customer');
	$xcrud_sc->relation('added_by','user','user_id','name');
	$xcrud_sc->where('',"`customer`.`chassis_no` LIKE '$chassis_no%'");
	$xcrud_sc->unset_add();
	$xcrud_sc->unset_edit();
	$xcrud_sc->unset_remove();
	$xcrud_sc->unset_print();
	$xcrud_sc->unset_csv();
	$xcrud_sc->unset_title();
	$xcrud_sc->unset_search();
	//$xcrud_sc->unset_view();
	$xcrud_sc->unset_limitlist();
	echo $xcrud_sc->render();
	echo Xcrud::load_js();
}

if($_POST['action']=='search_customer_registerNo_record')
{
	include ('xcrud/xcrud.php');
	echo Xcrud::load_css();
	$registration_no=$_POST['registration_no'];

	$xcrud_sc1=Xcrud::get_instance();
	$xcrud_sc1->table('customer');
	$xcrud_sc1->relation('added_by','user','user_id','name');
	$xcrud_sc1->where('',"`customer`.`registration_no` LIKE '$registration_no%'");
	$xcrud_sc1->unset_add();
	$xcrud_sc1->unset_edit();
	$xcrud_sc1->unset_remove();
	$xcrud_sc1->unset_print();
	$xcrud_sc1->unset_csv();
	$xcrud_sc1->unset_title();
	$xcrud_sc1->unset_search();
	//$xcrud_sc->unset_view();
	$xcrud_sc1->unset_limitlist();
	echo $xcrud_sc1->render();
	echo Xcrud::load_js();
}

if($_POST['action']=='checkStatus'){
	$id=$_POST['id'];
	$bdd=new DB();
	$mrow=$bdd->getOne("SELECT count(menu_id) as m FROM menu WHERE visibility='Yes' and compulsory='yes'");
	$bdd->disconnect();
	$bdd=new DB();
	$cmrow=$bdd->getOne("SELECT count(customer_menu_id) as cm FROM customer_menu WHERE customer_id=".$id);
	$bdd->disconnect();
	if($mrow['m']>$cmrow['cm']){
		echo 0;
	}else{
		echo 1;
	}
}

if($_POST['action']=='updateCustInfo'){
	$bdd=new DB();
	$crow=$bdd->getOne("SELECT name,contact_no,chassis_no,AllotmentNo,product,make,meter_no FROM customer WHERE customer_id=".$_POST['id']);
	$bdd->disconnect();
	echo json_encode($crow);	
}


if ($_POST['action'] == 'updateRegistrationNo') {
    $bdd = new DB();
    $crow = $bdd->getOne("SELECT name FROM customer WHERE customer_id=" . $_POST['id']);
    $bdd->disconnect();

    $bdd = new DB();
    $row = $bdd->getOne('SELECT name, contact_no, date, chassis_no FROM customer WHERE customer_id=' . $_POST['id']);
    $bdd->disconnect();
    $year = date('Y', strtotime($row['date']));
    $month = date('m', strtotime($row['date']));
    $path = 'uploads/' . $year . '/' . $month . '/' . $row['name'] . '-' . $row['contact_no'] . '-' . $row['chassis_no'];

    $data = array();
	
	$data['permitpdf'] = 'nothing';
	$data['permitjpg'] = 'nothing';
	
	$data['fitnesspdf'] = 'nothing';
	$data['fitnessjpg'] = 'nothing';

    if (file_exists($path . '/Permit.pdf')) {
        $data['permitpdf'] = $path . '/Permit.pdf';
    }
	elseif (file_exists($path . '/Permit.jpg')) {
        $data['permitjpg'] = $path . '/Permit.jpg';
    } 

    if (file_exists($path . '/Fitness.pdf')) {
        $data['fitnesspdf'] = $path . '/Fitness.pdf';
    } 
	elseif (file_exists($path . '/Fitness.jpg')) {
        $data['fitnessjpg'] = $path . '/Fitness.jpg';
    }

    $data['name'] = $crow['name'];
	$data['id'] = $_POST['id'];

    echo json_encode($data);
}


if($_POST['action']=='changeOrderStatus'){
	$Uname = $_POST['Uname'];
	$data=array();
	$bdd=new DB();
	$crow=$bdd->getOne("SELECT order_status FROM customer WHERE customer_id=".$_POST['id']);
	$bdd->disconnect();

	if($crow['order_status']=='0'){
		$td=date('Y-m-d');
		$bdd=new DB();
		$result=$bdd->execute("UPDATE customer SET order_status='1', order_date='$td' WHERE customer_id=".$_POST['id']);
		$bdd->disconnect();
		if($result){
			checkAllDocStatus($_POST['id'],$Uname);
			$data['status']='ok';
			$data['message']='Order Updated';
		}else{
			$data['status']='error';
			$data['message']='Error. Try Again';
		}
	}else{
		$data['status']='error';
		$data['message']='Order is Already Updated';
	}
	
	echo json_encode($data);
}

if($_POST['action']=='changeProceedStatus'){
	$Uname = $_POST['Uname'];
	$bdd=new DB();
	$td=date('Y-m-d');
	$current_upload_time=date('Y-m-d H:i:s',strtotime('2 hour'));
	
	$result=$bdd->execute("UPDATE customer SET upload_time='$current_upload_time',sale_date='$td',status='Upload',rto='".$_POST['rto']."',smc='".$_POST['smc']."' WHERE customer_id=".$_POST['id']);
	
	/*$customer_row=$bdd->getOne("SELECT date,name,contact_no,chassis_no FROM customer WHERE customer_id=".$_POST['id']);
	$year=date('Y',strtotime($customer_row['date']));
	$month=date('m',strtotime($customer_row['date']));
	$filename_path = 'uploads/'.$year.'/'.$month.'/'.$customer_row['name'].'-'.$customer_row['contact_no'].'-'.$customer_row['chassis_no'];
	
	if (file_exists($filename_path)) {
		copy('uploads/sample_file/MFG_Invoice.pdf',$filename_path.'/MFG_Invoice.pdf');
	}*/

	$existingEntries = $bdd->getOne("SELECT * FROM modification WHERE CId =". $_POST['id']);

	if ($existingEntries > 0) {
		$resu=$bdd->execute("UPDATE modification SET Proceed = '$Uname',Proceed_date='$current_datetime' WHERE CId=".$_POST['id']);
	} else {
		$user_id = $_POST['id'];
		$insertResult = $bdd->execute("INSERT INTO modification (Proceed, Proceed_date, CId) VALUES ('$Uname','$current_datetime',$user_id)");
	}

	if($result){
		checkAllDocStatus($_POST['id'],$Uname);
		$data['status']='ok';
		$data['message']='Proceed Updated';
	}else{
		$data['status']='error';
		$data['message']='Error. Try Again';
	}
	
	$bdd->disconnect();
	
	echo json_encode($data);
}

if($_POST['action']=='changeReceiveStatus'){
	$Uname = $_POST['Uname'];
	$data=array();
	$bdd=new DB();
	$crow=$bdd->getOne("SELECT receive FROM customer WHERE customer_id=".$_POST['id']);
	$bdd->disconnect();

	if($crow['receive']=='0'){
		$current_fitment_time=date('Y-m-d H:i:s',strtotime('18 hour'));
		$td=date('Y-m-d');
		$bdd=new DB();
		$result=$bdd->execute("UPDATE customer SET fitment_time='$current_fitment_time',receive='1', receive_date='$td', status='Fitment' WHERE customer_id=".$_POST['id']);
		$bdd->disconnect();

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


		if($result){
			checkAllDocStatus($_POST['id'],$Uname);
			$data['status']='ok';
			$data['message']='Receive Updated';
		}else{
			$data['status']='error';
			$data['message']='Error. Try Again';
		}
	}else{
		$data['status']='error';
		$data['message']='Receive is Already Updated';
	}
	
	echo json_encode($data);
}

if($_POST['action']=='changeFittmentStatus'){
	$Uname = $_POST['Uname'];
	$data=array();
	$bdd=new DB();
	$crow=$bdd->getOne("SELECT fittment FROM customer WHERE customer_id=".$_POST['id']);
	$bdd->disconnect();

	if($crow['fittment']=='0'){
		$td=date('Y-m-d');
		$bdd=new DB();
		$result=$bdd->execute("UPDATE customer SET fittment='1', fittment_date='$td', status='Ready' WHERE customer_id=".$_POST['id']);
		$bdd->disconnect();

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

		if($result){
			checkAllDocStatus($_POST['id'],$Uname);
			$data['status']='ok';
			$data['message']='Fittment Updated';
		}else{
			$data['status']='error';
			$data['message']='Error. Try Again';
		}
	}else{
		$data['status']='error';
		$data['message']='Fittment is Already Updated';
	}
	
	echo json_encode($data);
}

if($_POST['action']=='CustomerInfo'){

require_once('xcrud/xcrud.php');

$custInfoXcrud = Xcrud::get_instance();

$custInfoXcrud->table('modification');

$custInfoXcrud->columns('Pending,Pending_date,Allotment,Allotment_date,Proceed,Proceed_date,Upload,Upload_date,Insp,Insp_date,Payment,Payment_date,Semi,Semi_date,Hsrp,Hsrp_date,Fitment,Fitment_date,Ready,Ready_date,Register,Register_date,Rc,Rc_date,IssueDocs,IssueDocs_date',false);
$custInfoXcrud->fields('Pending,Pending_date,Allotment,Allotment_date,Proceed,Proceed_date,Upload,Upload_date,Insp,Insp_date,Payment,Payment_date,Semi,Semi_date,Hsrp,Hsrp_date,Fitment,Fitment_date,Ready,Ready_date,Register,Register_date,Rc,Rc_date,IssueDocs,IssueDocs_date',false);

$customer_id = $_POST['id']; 
$custInfoXcrud->where('CId',  $customer_id);

$custInfoXcrud->unset_title();
$custInfoXcrud->unset_add();
$custInfoXcrud->unset_print();
$custInfoXcrud->unset_csv();
$custInfoXcrud->unset_remove();
$custInfoXcrud->unset_search();

echo $custInfoXcrud->render();

}

if($_POST['action']=='changeStatus'){
	$current_payment_time=date('Y-m-d H:i:s',strtotime('4 hour'));
	
	$Uname = $_POST['Uname'];
	$bdd=new DB();
	$result=$bdd->execute("UPDATE customer SET payment_time='$current_payment_time',status='Payment' WHERE customer_id=".$_POST['id']);
	$bdd->disconnect();

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

	if($result){
		
		$data['status']='ok';
		$data['message']='Status Updated';
	}else{
		$data['status']='error';
		$data['message']='Error. Try Again';
	}	
	echo json_encode($data);
}

if($_POST['action']=='changeRegister'){
	$date=date('Y-m-d');
	$current_issue_docs_time=date('Y-m-d H:i:s',strtotime('+1 week'));
	
	$Uname = $_POST['Uname'];
	$bdd=new DB();
	$result=$bdd->execute("UPDATE customer SET issue_docs_time='$current_issue_docs_time',status='IssueDocs',document_received_date='$date' WHERE customer_id=".$_POST['id']);
	$bdd->disconnect();

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

	//upload bahedhari
	/*error_reporting(E_ALL & ~E_STRICT);
	$bdd=new DB();

	$cust_row=$bdd->getOne("SELECT date,name,contact_no,chassis_no,registration_no FROM customer WHERE customer_id='{$_POST['id']}'");
	$address_row=$bdd->getOne("SELECT address FROM vehicle_registration_list WHERE chassis_no='{$cust_row['chassis_no']}'");

	$bdd->disconnect();
	$name=strtoupper(str_replace('_', ' ', $cust_row['name']));
	$contact_no=$cust_row['contact_no'];
	$registration_no=$cust_row['registration_no'];
	$chassis_no=$cust_row['chassis_no'];
	$address=$address_row['address'];
	$year=date('Y',strtotime($cust_row['date']));
	$month=date('m',strtotime($cust_row['date']));
	$filename_path = 'uploads/'.$year.'/'.$month.'/'.$cust_row['name'].'-'.$cust_row['contact_no'].'-'.$cust_row['chassis_no'];
	include_once './generate_pdf/mpdf60/mpdf.php';

	$mpdf = new mPDF('utf-8','A4');

	$mpdf->useSubstitutions = true;

	
	$mpdf->fontdata['english'] = array(
		'R' => 'DejaVuSans.ttf'
	);

	
	$mpdf->fontdata['gujarati'] = array(
		'R' => 'Lohit-Gujarati.ttf',
		'useOTL' => 0xFF
	);

	
	$mpdf->available_unifonts = array('english','gujarati');

	
	$mpdf->SetFont('english');


	$html = '
<style>
body {
    font-family: english;
    font-size: 9pt;
}
.gujarati {
    font-family: gujarati;
    font-size: 10pt;
}
</style>

<span class="gujarati">&nbsp;</span>

<table width="100%"><tr><td align="center"><span class="gujarati" style="font-size:16pt;">બાંહેધરી</span></td></tr></table>

<span class="gujarati">હું </span> <span>&nbsp;&nbsp;</span><b><u>'.$name.'</u></b><br><br>
<span class="gujarati">મોં નંબર</span><span>&nbsp;&nbsp;</span><b><u>'.$contact_no.'</u></b><br><br>

<span class="gujarati">નિવાસી </span> <b><u>'.$address.'</u></b><span class="gujarati"> શપથ લેવું છું કે <br><br>

૧.<span>&nbsp;&nbsp;</span>મેં / મારી કંપનીએ સિદ્ધાર્થ મોટર્સ પાસેથી એક થ્રી વ્હીલર વાહન ખરીદેલ છે .જેનો રજીસ્ટ્રેશન નંબર</span> <br><br>
<b><u>'.$registration_no.'</u></b>, <span class="gujarati">ચેસ્સીસ નંબર </span><b><u>'.$chassis_no.'</u></b> <span class="gujarati">છે.<br><br>

૨.<span>&nbsp;&nbsp;</span>મને વાહન નોંધણી સંબંધિત વાહન સોફ્ટવેર 4.0 પર અપલોડ કરાયેલા તમામ અસલ દસ્તાવેજો જેમ કે બિલ,વીમો,<br><br>
સિલિન્ડર પ્રમાણપત્ર, મીટર પ્રમાણપત્ર,સરનામું,આઈ.ડી. પ્રૂફ તથા અન્ય ફોર્મ વગેરે મને પરત કરવામાં આવ્યા છે.<br><br>


હવે આ તમામ દસ્તાવેજોને સુરક્ષિત રાખવાની અને ભવિષ્યમાં જરૂર પડે તો વાહન વ્યવહાર વિભાગ / પોલીસ /અન્ય<br><br>
કોઈપણ વિભાગને અસલ નોંદણી દસ્તાવેજ પ્રદાન કરવાની જવાબદારી મારી રહેશે.<br><br>


પ્રાપ્તકર્તાનું  નામઃ </span><span>&nbsp;&nbsp;</span>____________________________________________________________________<br><br>

<span class="gujarati">સહી:<span>&nbsp;&nbsp;</span></span>__________________________________ <span class="gujarati">તારીખ:<span>&nbsp;&nbsp;</span></span>_____________________________________________<br><br>

_______________________________________________________________________________________________________________</span><br><br>

<table width="100%"><tr><td align="center"><span class="gujarati" style="font-size:16pt;">પરમિટ મેળવ્યાની વિગત</span></td></tr></table> <br><br>
<span class="gujarati">
હું<span>&nbsp;&nbsp;</span></span>_____________________________________________________________<span>&nbsp;&nbsp;</span><span class="gujarati">મોં.ન.<span>&nbsp;&nbsp;</span></span>___________________________<br><br>

<span class="gujarati">અને મારી ગાડી નં.</span>__________________________<span class="gujarati">ની અસલ પરમિટ આજ રોજ મળી ગયેલ  છે .<br><br>


સહી</span> __________________________________________<span class="gujarati">તારીખ</span> ______________________________';

	$mpdf->WriteHTML($html);
	//$mpdf->Output();
	if (file_exists($filename_path)) {
		$filepath = $filename_path.'/BAHENDHARI.pdf';
		$mpdf->Output($filepath, 'F');
	}*/
	
	if($result){
		
		$data['status']='ok';
		$data['message']='Status Updated';
	}else{
		$data['status']='error';
		$data['message']='Error. Try Again';
	}	
	echo json_encode($data);
}

if($_POST['action']=='changeIssueDocs'){
		
	$Uname = $_POST['Uname'];
	$bdd=new DB();
	$result=$bdd->execute("UPDATE customer SET status='FullSuccessfull' WHERE customer_id=".$_POST['id']);
	$bdd->disconnect();

	if($result){
		
		$data['status']='ok';
		$data['message']='Status Updated';
	}else{
		$data['status']='error';
		$data['message']='Error. Try Again';
	}	
	echo json_encode($data);
}

if($_POST['action']=='changeCompletedStatus'){
	$Uname = $_POST['Uname'];
	$data=array();
	$bdd=new DB();
	$crow=$bdd->getOne("SELECT Documents,Remark FROM customer WHERE customer_id=".$_POST['id']);
	$bdd->disconnect();
	$Remark = $crow['Remark'];

	if($crow['Documents']=='All-Done'){
		$current_upload_time=date('Y-m-d H:i:s',strtotime('1 hour'));
		$bdd=new DB();
		$result=$bdd->execute("UPDATE customer SET insp_time='$current_upload_time',Remark=NULL, status='Insp' WHERE customer_id=".$_POST['id']);
		$bdd->disconnect();

		$bdd=new DB();
		$existingEntries = $bdd->getOne("SELECT * FROM modification WHERE CId =". $_POST['id']);
		$bdd->disconnect();
		if ($existingEntries > 0) {

			if($Remark!=NULL)
			{
				$bdd=new DB();
				$res=$bdd->execute("UPDATE modification SET Upload = NULL WHERE CId=".$_POST['id']);
				$bdd->disconnect();
			}
			$bdd=new DB();
			$resu=$bdd->execute("UPDATE modification SET Upload = '$Uname',Upload_date='$current_datetime' WHERE CId=".$_POST['id']);
			$bdd->disconnect();
		} else {
			$user_id = $_POST['id'];
			$bdd=new DB();
			$insertResult = $bdd->execute("INSERT INTO modification (Upload, Upload_date, CId) VALUES ('$Uname','$current_datetime',$user_id)");
			$bdd->disconnect();
		}

		if($result){
			checkAllDocStatus($_POST['id'],$Uname);
			$data['status']='ok';
			$data['message']='Customer Updated';
		}else{
			$data['status']='error';
			$data['message']='Error. Try Again';
		}
	}else{
		$data['status']='error';
		$data['message']='Upload all the documents';
	}
	
	echo json_encode($data);
}


if($_POST['action']=='userPasswordConfrm'){
	$data=array();
	
	$bdd=new DB();
	$crow=$bdd->getOne("SELECT password FROM password WHERE password='".$_POST['password']."'");
	$bdd->disconnect();
	
	if(!empty($crow)){
		$data['status']='ok';
	}else{
		$data['status']='error';
	}
	
	echo json_encode($data);
}

if($_POST['action']=='updateCustRemarkInfo'){
	$bdd=new DB();
	$data=array();
	$customer_remark_data="";
	$customer=$bdd->getOne("SELECT name,customer_id,contact_no FROM customer WHERE customer_id=".$_POST['id']);
	$remarks=$bdd->getAll("SELECT * FROM customer_remark WHERE customer_id=".$_POST['id']." ORDER BY datetime");
	$bdd->disconnect();
	if(!empty($remarks)){
		$customer_remark_data.="<tr><th>Date</th><th>Remark</th></tr>";
		foreach($remarks as $value){
			$customer_remark_data.="<tr><td>".date('d-m-Y H:i:s',strtotime($value['datetime']))."</td><td>".$value['remark']."</td></tr>";
		}
	}
	$data['customer']=$customer;
	$data['remark']=$customer_remark_data;
	echo json_encode($data);	
}

/*if($_POST['action']=='cvs_password')
{
	$csv_pass=$_POST['csv_pass'];
	$bdd=new DB();
	$prow=$bdd->getOne("select export from password");
	$bdd->disconnect();
	if($csv_pass==$prow['export']){
		echo 1;
	}
	else{
		echo 0;
	}
}*/
?>