<?php
date_default_timezone_set("Asia/Kolkata");

$config['displayErrorDetails'] = true;
$config['addContentLengthHeader'] = false;

$config['db']['host']   = 'localhost';
$config['db']['user']   = 'root';
$config['db']['pass']   = '';
$config['db']['dbname'] = 'TICL_Detail';

/*$config['db']['host']   = '182.50.133.85:3306';
$config['db']['user']   = 'bitplex_scanner';
$config['db']['pass']   = 'bitplex@189';
$config['db']['dbname'] = 'mastermandap_scanner';*/
class Database{

	private $pdo;

	public function __construct( PDO $pdo){
		$this->pdo=$pdo;
	}

	public function query($sql){
		$req=$this->pdo->prepare($sql);
		$req->execute();
		return $req->fetchAll();
	}

	public function insertQuery($sql){
		$this->pdo->exec($sql);
		$last_id = $this->pdo->lastInsertId();
		return $last_id;
	}


	public function uquery($sql){
		$req=$this->pdo->prepare($sql);
		$req->execute();
		
		$msg=array();
		if($req->rowCount()>0){
			$msg['status']="Success";
			return $msg;
		}
		else{
			$msg['status']="Fail";
			return $msg;
		}
	}
}

class PagesController{
	//private $ip="192.168.43.245:81";
	private $ip="192.168.0.245:81";
	private $container;
	public function __construct($container){
		$this->container=$container;
	}

	public function appUserLogin($request, $response, $args) {
		$response = array();
		$aul=$this->container->db->query("SELECT * FROM users WHERE (user_type='admin' || user_type='user') AND user_name='".$_POST['username']."' AND password='".$_POST['password']."'");
		if(!empty($aul)){
			$response['user']=$aul;
			$response['response'] = "success";
			$response['message'] = "Login Successfuly.";
		}else{
			$response['response'] = "fail";
			$response['message'] = "Invalid Usrname or Password.";
		}
		echo json_encode($response);
	}
	
	public function getPdiTruckList($request, $response, $args) {
		//sleep(2);
		$response = array();
		$where_query="";
		$date="";
		if($_POST['truckNo']!="null"){
			if($_POST['truckNo']!=""){
				$day=date('d',strtotime($_POST['date']));
				$month=date('m',strtotime($_POST['date']));
				$year=date('Y',strtotime($_POST['date']));
				/*if($day<10){
					$day="0".$day;
				}
				if($month<10){
					$month="0".$month;
				}*/
				//$date=$year."".$month."".$day;
				$date=$day."".$month."".$year;
				//$date=date('Y-m-d',strtotime($_POST['date']));
				$truck_id=$_POST['truckNo']."-".$date;
				//$truck_id = str_replace('-', '', $truck_id);
				$where_query=" AND TruckId='".$truck_id."'";
			}
		}
		$pending_truck=$this->container->db->query("SELECT TN.*,COUNT(TD.Id) AS total FROM TruckNo AS TN LEFT JOIN truckdetails AS TD ON TN.TruckId=TD.TruckNo WHERE TN.Status = 'pending' $where_query GROUP BY TN.TruckId");
		if(!empty($pending_truck)){
			$response['truck']=$pending_truck;
			$response['response'] = "success";
			$response['message'] = "Data found.";
			//$response['date']=$date;
			//$response['query']=$query;
		}else{
			$response['response'] = "fail";
			$response['message'] = "No recored found.";
			$response['date']=$date;
			//$response['query']=$query;
		}
		echo json_encode($response);
	}
	
	public function getTruckDetails($request, $response, $args) {
		//sleep(2);
		$response = array();
		$truck_details=$this->container->db->query("SELECT * FROM truckdetails WHERE TruckNo = '".$_POST['truckId']."' AND ChassisImg != ''");
		$total_record =$this->container->db->query("SELECT COUNT(Id) AS total_record FROM `truckdetails` WHERE TruckNo='".$_POST['truckId']."'");
		$total_pending_record =$this->container->db->query("SELECT COUNT(Id) AS total_pending_record FROM `truckdetails` WHERE TruckNo='".$_POST['truckId']."' AND ChassisImg = ''");
		//$total=(string) $total_record[0]['total_record'];
		$total_record=$total_record[0]['total_record'];
		$total_pending_record=$total_pending_record[0]['total_pending_record'];
		if(!empty($truck_details)){
			$response['truck']=$truck_details;
			$response['total_record']=$total_record;
			$response['total_pending_record']=$total_pending_record;
			$response['response'] = "success";
			$response['message'] = "Data found.";
			//$response['query']=$query;
		}else{
			$response['total_record']=$total_record;
			$response['total_pending_record']=$total_pending_record;
			$response['response'] = "fail";
			$response['message'] = "No recored found.";
			//$response['query']=$query;
		}
		echo json_encode($response);
	}
	
	public function getAllTruckDetails($request, $response, $args) {
		//sleep(2);
		$response = array();
		$truck_details=$this->container->db->query("SELECT * FROM truckdetails WHERE TruckNo = '".$_POST['truckId']."'");
		$total_record =$this->container->db->query("SELECT COUNT(Id) AS total_record FROM `truckdetails` WHERE TruckNo='".$_POST['truckId']."'");
		$total_pending_record =$this->container->db->query("SELECT COUNT(Id) AS total_pending_record FROM `truckdetails` WHERE TruckNo='".$_POST['truckId']."' AND ChassisImg = ''");
		//$total=(string) $total_record[0]['total_record'];
		$total_record=$total_record[0]['total_record'];
		$total_pending_record=$total_pending_record[0]['total_pending_record'];
		if(!empty($truck_details)){
			$response['truck']=$truck_details;
			$response['total_record']=$total_record;
			$response['total_pending_record']=$total_pending_record;
			$response['response'] = "success";
			$response['message'] = "Data found.";
			//$response['query']=$query;
		}else{
			$response['total_record']=$total_record;
			$response['total_pending_record']=$total_pending_record;
			$response['response'] = "fail";
			$response['message'] = "No recored found.";
			//$response['query']=$query;
		}
		echo json_encode($response);
	}
	
	public function getCylinderMfgList($request, $response, $args) {
		$response = array();
		$cylinder_mfg=$this->container->db->query("SELECT * FROM cyl_mfg");
		if(!empty($cylinder_mfg)){
			$response['cylinder_mfg']=$cylinder_mfg;
			$response['response'] = "success";
			$response['message'] = "Data found.";
		}else{
			$response['response'] = "fail";
			$response['message'] = "No cylinder manufacturer listed.";
		}
		echo json_encode($response);
	}
	
	public function getKitMfgList($request, $response, $args) {
		$response = array();
		$kit_mfg=$this->container->db->query("SELECT * FROM kit_mfg");
		if(!empty($kit_mfg)){
			$response['kit_mfg']=$kit_mfg;
			$response['response'] = "success";
			$response['message'] = "Data found.";
		}else{
			$response['response'] = "fail";
			$response['message'] = "No kit manufacturer listed.";
		}
		echo json_encode($response);
	}
	
	public function checkValidChassisNo($request, $response, $args) {
		$response = array();
		$result=$this->container->db->query("SELECT Id,EngineNo,CylNo,KitNo FROM truckdetails where TruckNo = '".$_POST['TruckNo']."' AND RIGHT(ChassisNo, 5) = '".$_POST['ChassisNo']."' AND ChassisImg = ''");
		if(!empty($result)){
			$response['result']=$result;
			$response['response'] = "success";
			$response['message'] = "Chassis No found.";
		}else{
			$response['response'] = "fail";
			$response['message'] = "No Chassis No found.";
		}
		echo json_encode($response);
	}
	
	public function checkValidEngineNo($request, $response, $args) {
		$response = array();
		$EngineNo=$this->container->db->query("SELECT Id,TruckNo,CylNo,KitNo FROM truckdetails where TruckNo = '".$_POST['TruckNo']."' AND RIGHT(EngineNo, 5) = '".$_POST['EngineNo']."' AND RIGHT(ChassisNo, 5) = '".$_POST['ChassisNo']."'");
		if(!empty($EngineNo)){
			$response['response'] = "success";
			$response['message'] = "Engine Number found.";
		}else{
			$response['response'] = "fail";
			$response['message'] = "No Engine Number. found.";
		}
		echo json_encode($response);
	}
	
	public function updateTruckDetails($request, $response, $args) {
		$response = array();
		$chassis_filename="ChassisNo".$_POST['chassisNo'].$_POST['truckNo'].".png";
		//$engine_filename="EngineNo".$_POST['engineNo'].$_POST['truckNo'].".png";
		//$cylinder_filename="CylinderNo".$_POST['cylinderNo'].$_POST['truckNo'].".png";
		//$kit_filename="KitNo".$_POST['kitNo'].$_POST['truckNo'].".png";
		//$file_ext=strtolower(pathinfo($_FILES['chassisImg']['name'], PATHINFO_EXTENSION));
		//$fullfilename=$filename.'.'.$file_ext;
		//$uc=$this->container->db->uquery("UPDATE truckdetails SET ChassisImg='".$chassis_filename."', EngineImg='".$engine_filename."',CylImg='".$cylinder_filename."',KitImg='".$kit_filename."', CylNo = '".$_POST['cylinderNo']."', Cyl_Mfg = '".$_POST['cylinderMfg']."', KitNo = '".$_POST['kitNo']."', Kit_Mfg = '".$_POST['kitMfg']."' WHERE TruckNo = '".$_POST['truckNo']."' AND RIGHT(ChassisNo, 5) = '".$_POST['chassisNo']."' AND RIGHT(EngineNo, 5) = '".$_POST['engineNo']."'");
		$uc=$this->container->db->uquery("UPDATE truckdetails SET ChassisImg='".$chassis_filename."' WHERE TruckNo = '".$_POST['truckNo']."' AND RIGHT(ChassisNo, 5) = '".$_POST['chassisNo']."' AND EngineNo = '".$_POST['engineNo']."'");
		if($uc['status']=='Success'){
			//move_uploaded_file($_FILES["chassisImg"]["tmp_name"], '../upload/'.$fullfilename);
			$upload_dir="../upload/";
			file_put_contents($upload_dir.$chassis_filename,base64_decode($_POST['chassisImage']));
			/*file_put_contents($upload_dir.$engine_filename,base64_decode($_POST['engineImage']));
			file_put_contents($upload_dir.$cylinder_filename,base64_decode($_POST['cylinderImage']));
			file_put_contents($upload_dir.$kit_filename,base64_decode($_POST['kitImage']));*/
			$truck=$this->container->db->query("SELECT * FROM TruckNo WHERE TruckId='".$_POST['truckNo']."'");
			$response['truckNo'] = $truck[0]['TruckNo'];
			//$response['date'] = date('d-m-Y',strtotime($truck[0]['date']));;
			$response['response'] = "success";
			$response['message'] = "Truck detail updated successfuly.";
		}else{
			$response['response'] = "fail";
			$response['message'] = "Error while updateding detail. Try again.";
		}
		echo json_encode($response);
	}
	
	public function updateTruckStatus($request, $response, $args) {
		$response = array();
		$date=date('Y-m-d');
		$uc=$this->container->db->uquery("UPDATE truckno SET Status='completed',completed_date='$date' WHERE TruckId = '".$_POST['truckId']."'");
		if($uc['status']=='Success'){
			$response['response'] = "success";
			$response['message'] = "Truck status updated successfuly.";
		}else{
			$response['response'] = "fail";
			$response['message'] = "Error while updateding status. Try again.";
		}
		echo json_encode($response);
	}
	
	public function updateTruck($request, $response, $args) {
		$truckId=str_replace('-', '',$_POST['truckId']);
		$day=date('d',strtotime($_POST['date']));
		$month=date('m',strtotime($_POST['date']));
		$year=date('Y',strtotime($_POST['date']));
		$date=$year."".$month."".$day;
		//$date=$year."-".$month."-".$day;
		//$date=date('Y-m-d',strtotime($_POST['date']));
		//$date1=str_replace('-', '',$date);
		//$new_truck_id=str_replace('-', '',$temp_new_truck_id);
		$new_truck_id=$_POST['truckNo']."-".$date;
		$response = array();
		$uc=$this->container->db->uquery("UPDATE truckno SET TruckId = '$new_truck_id', TruckNo = '".$_POST['truckNo']."', Date = '$date' WHERE TruckId = '$truckId'");
		if($uc['status']=='Success'){
			$this->container->db->uquery("UPDATE truckdetails SET TruckNo = '$new_truck_id' WHERE TruckNo = '$truckId'");
			$response['response'] = "success";
			$response['message'] = "Truck detail updated successfuly.";
		}else{
			$response['response'] = "fail";
			$response['message'] = "Error while updateding detail. Try again.";
		}
		echo json_encode($response);
	}
	
	public function saveTruckDetails($request, $response, $args) {
		$response = array();
		$chassis_query="";
		$engine_query="";
		$cylinder_query="";
		$kit_query="";
		$is_comma=false;
		$is_first="";
		$chassis_filename="";
		$engine_filename="";
		$cylinder_filename="";
		$kit_filename="";
		if($_POST['isChassisImgUpdate']=="Yes"){
			$chassis_filename="ChassisNo".date('YmdHiS').".png";
			$chassis_query="ChassisImg='$chassis_filename'";
			$is_comma=true;
		}
		if($_POST['isEngineImgUpdate']=="Yes"){
			$engine_filename="EngineNo".date('YmdHiS').".png";
			if($is_comma){
				$engine_query=",";
			}
			$engine_query.="EngineImg='$engine_filename'";
			$is_comma=true;
		}
		if($_POST['isCylinderImgUpdate']=="Yes"){
			$cylinder_filename="CylinderNo".date('YmdHiS').".png";
			if($is_comma){
				$cylinder_query=",";
			}
			$cylinder_query.="CylImg='$cylinder_filename'";
			$is_comma=true;
		}
		if($_POST['isKitImgUpdate']=="Yes"){
			$kit_filename="KitNo".date('YmdHiS').".png";
			if($is_comma){
				$kit_query=",";
			}
			$kit_query.="KitImg='$kit_filename'";
			$is_comma=true;
		}
		if($is_comma){
			$is_first=",";
		}

		$uquery="UPDATE truckdetails SET $chassis_query $engine_query $cylinder_query $kit_query $is_first CylNo = '".$_POST['cylinderNo']."', Cyl_Mfg = '".$_POST['cylinderMfg']."', KitNo = '".$_POST['kitNo']."', Kit_Mfg = '".$_POST['kitMfg']."' WHERE Id = '".$_POST['Id']."'";
		
		$image_list=$this->container->db->query("SELECT ChassisImg,EngineImg,CylImg,KitImg FROM truckdetails WHERE Id = '".$_POST['Id']."'");
		
		$uc=$this->container->db->uquery($uquery);
		if($uc['status']=='Success'){
			
	
			$upload_dir="../upload/";
			if($_POST['isChassisImgUpdate']=="Yes"){
				if($image_list[0]['ChassisImg']!="")
					unlink($upload_dir.$image_list[0]['ChassisImg']);
				file_put_contents($upload_dir.$chassis_filename,base64_decode($_POST['chassisImage']));
			}
			if($_POST['isEngineImgUpdate']=="Yes"){
				if($image_list[0]['EngineImg']!="")
					unlink($upload_dir.$image_list[0]['EngineImg']);
				file_put_contents($upload_dir.$engine_filename,base64_decode($_POST['engineImage']));
			}
			if($_POST['isCylinderImgUpdate']=="Yes"){
				if($image_list[0]['CylImg']!="")
					unlink($upload_dir.$image_list[0]['CylImg']);
				file_put_contents($upload_dir.$cylinder_filename,base64_decode($_POST['cylinderImage']));
			}
			if($_POST['isKitImgUpdate']=="Yes"){
				if($image_list[0]['KitImg']!="")
					unlink($upload_dir.$image_list[0]['KitImg']);
				file_put_contents($upload_dir.$kit_filename,base64_decode($_POST['kitImage']));
			}
			$response['response'] = "success";
			$response['message'] = "Truck detail updated successfuly.";
		}else{
			$response['response'] = "fail";
			$response['message'] = "Error while updateding detail. Try again.";
		}
		
		echo json_encode($response);
	}
	
	public function removeImage($request, $response, $args) {
		$response = array();
		$query="";
		if($_POST['type']=="Chassis"){
			$query="UPDATE truckdetails SET ChassisImg='' WHERE Id = '".$_POST['Id']."'";
		}else if($_POST['type']=="Engine"){
			$query="UPDATE truckdetails SET EngineImg='' WHERE Id = '".$_POST['Id']."'";
		}else if($_POST['type']=="Cylinder"){
			$query="UPDATE truckdetails SET CylImg='' WHERE Id = '".$_POST['Id']."'";
		}else if($_POST['type']=="Kit"){
			$query="UPDATE truckdetails SET KitImg='' WHERE Id = '".$_POST['Id']."'";
		}
		$uc=$this->container->db->uquery($query);
		if($uc['status']=='Success'){
			$response['response'] = "success";
			$response['message'] = "Updated successfuly.";
		}else{
			$response['response'] = "fail";
			$response['message'] = "Error while updateding detail. Try again.";
		}
		echo json_encode($response);
	}
	
	public function getCompleteTruckList($request, $response, $args) {
		//sleep(2);
		$response = array();
		$where_query="";
		$date="";
		if($_POST['truckNo']!="null"){
			if($_POST['truckNo']!=""){
				$day=date('d',strtotime($_POST['date']));
				$month=date('m',strtotime($_POST['date']));
				$year=date('Y',strtotime($_POST['date']));
				/*if($day<10){
					$day="0".$day;
				}
				if($month<10){
					$month="0".$month;
				}*/
				//$date=$year."".$month."".$day;
				$date=$day."".$month."".$year;
				//$date=date('Y-m-d',strtotime($_POST['date']));
				$truck_id=$_POST['truckNo']."-".$date;
				//$truck_id = str_replace('-', '', $truck_id);
				$where_query=" AND TruckId='".$truck_id."'";
			}
		}
		$pending_truck=$this->container->db->query("SELECT TN.*,COUNT(TD.Id) AS total FROM TruckNo AS TN LEFT JOIN truckdetails AS TD ON TN.TruckId=TD.TruckNo WHERE TN.Status = 'completed' $where_query GROUP BY TN.TruckId");
		if(!empty($pending_truck)){
			$response['truck']=$pending_truck;
			$response['response'] = "success";
			$response['message'] = "Data found.";
			//$response['date']=$date;
			//$response['query']=$query;
		}else{
			$response['response'] = "fail";
			$response['message'] = "No recored found.";
			$response['date']=$date;
			//$response['query']=$query;
		}
		echo json_encode($response);
	}
	
}

require 'vendor/autoload.php';

$app = new Slim\App(['settings' => $config]);

$container=$app->getContainer();

$container['pdo'] = function ($c) {
    $db = $c['settings']['db'];
    $pdo = new PDO('mysql:host=' . $db['host'] . ';dbname=' . $db['dbname'],
        $db['user'], $db['pass']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
    return $pdo;
};

$container['db'] = function ($container) {
	return new Database($container->pdo);
};

$app->post('/appUserLogin','PagesController:appUserLogin');
$app->post('/getPdiTruckList','PagesController:getPdiTruckList');
$app->post('/getTruckDetails','PagesController:getTruckDetails');
$app->post('/getAllTruckDetails','PagesController:getAllTruckDetails');
$app->post('/getCylinderMfgList','PagesController:getCylinderMfgList');
$app->post('/getKitMfgList','PagesController:getKitMfgList');
$app->post('/checkValidChassisNo','PagesController:checkValidChassisNo');
$app->post('/checkValidEngineNo','PagesController:checkValidEngineNo');
$app->post('/updateTruckDetails','PagesController:updateTruckDetails');
$app->post('/updateTruckStatus','PagesController:updateTruckStatus');
$app->post('/updateTruck','PagesController:updateTruck');
$app->post('/saveTruckDetails','PagesController:saveTruckDetails');
$app->post('/removeImage','PagesController:removeImage');
$app->post('/getCompleteTruckList','PagesController:getCompleteTruckList');

$app->run();

/*$app->post('/test','PagesController:test');
$app->get('/updateName/{uName}/{username}','PagesController:updateName');

public function test($request, $response, $args) {
	$team=$this->container->db->query("SELECT * FROM team");
	echo 	($team);
}

public function updateName($request, $response, $args) {
	$uname=$this->container->db->uquery("UPDATE admin SET name="."'".$args['uName']."'"." WHERE username="."'".$args['username']."'");
	echo json_encode($uname);
}*/
?>