<?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'] = 'scanner';

/*$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.0.4:8080";

	private $container;
	
	public function __construct($container){
		$this->container=$container;
	}

	public function appUserLogin($request, $response, $args) {
		$aul=$this->container->db->query("SELECT * FROM user WHERE type='app_user' and username='".$_POST['username']."' and password='".$_POST['password']."'");
		$response = array();
		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 addCustomer($request, $response, $args) {		
		$year=date('Y');
		$date=date('Y-m-d');
		$response = array();

		$checkYear = '../uploads/'.$year;
		if(!file_exists($checkYear)) {
			mkdir('../uploads/'.$year);
		}

		$filename = '../uploads/'.$year.'/'.$_POST['name'].'-'.$_POST['contact_no'];
		if (file_exists($filename)) {
			$response['response'] = "fail";
			$response['message'] = "The Customer Alreay Exist.";
		} else {
			$ac=$this->container->db->query("SELECT customer_id FROM customer WHERE name='".$_POST['name']."' and contact_no='".$_POST['contact_no']."'");
			if(!empty($ac)){
				$response['response'] = "fail";
				$response['message'] = "The Customer Alreay Exist.";
			}else{
				$name = preg_replace('/\s+/', '_', $_POST['name']);
				mkdir('../uploads/'.$year.'/'.$name.'-'.$_POST['contact_no']);
				$name = preg_replace('/\s+/', '_', $_POST['name']);
				
				$req=$this->container->db->insertQuery("INSERT INTO `customer` (`name`, `contact_no`,`chassis_no`,`date`,`status`,`added_by`) VALUES ('".$name."', '".$_POST['contact_no']."', '".$_POST['chassis_no']."','".$date."','Pending','".$_POST['added_by']."')");
				if($req!=''){
					$response['id']=$req;
					$response['response'] = "success";
					$response['message'] = "Customer Added.";	
				}else{
					$response['response'] = "fail";
					$response['message'] = "Connection Error.";	
				}
			}
		}
		echo json_encode($response);
	}

	public function uploadDoc($request, $response, $args) {
		$mo_id=$_POST['menu_option_id'];
		$gy=$this->container->db->query("SELECT c.date,c.name,c.contact_no,m.menu_name,IF($mo_id!=0,(SELECT mo.name FROM menu_option as mo WHERE menu_option_id=".$_POST['menu_option_id']."),'') as menu_option_name FROM customer as c,menu as m WHERE c.customer_id=".$_POST['customer_id']." and m.menu_id=".$_POST['menu_id']);
	
		
		$response = array();
		if(empty($gy)){
			$response['response'] = "fail";
			$response['message'] = "Connection Error.";
		}else{
			$year=date('Y',strtotime($gy[0]['date']));
			$filename_path = '../uploads/'.$year.'/'.$gy[0]['name'].'-'.$gy[0]['contact_no'];
			if (!file_exists($filename_path)) {
				$response['response'] = "fail";
				$response['message'] = "Customer Not Found.";
			} else {
				//$filename=$_FILES['filename']['name'];
				$filename=$gy[0]['menu_name'].''.$gy[0]['menu_option_name'];
				$file_ext=strtolower(pathinfo($_FILES['filename']['name'], PATHINFO_EXTENSION));
				
				$fullfilename=$filename.'.'.$file_ext;
				if($file_ext!='pdf' && $file_ext!='jpg'){
					$response['response'] = "fail";
					$response['message'] = "File Formate must be pdf or jpg.";
				}/*else if($_FILES['filename']['size'] >=511999){
					$response['response'] = "fail";
					$response['message'] = "File must be less then 500KB.";
				}*/else{
						if($file_ext=='jpg'){
							$cf=$this->container->db->query("SELECT menu_id FROM customer_menu WHERE customer_id=".$_POST['customer_id']." and menu_id=".$_POST['menu_id']);

							if(!empty($cf)){
								$response['response'] = "fail";
								$response['message'] = "This Document is Alreay Exist. Delete old file and try again";
							}else{
								$req=$this->container->db->insertQuery("INSERT INTO `customer_menu` (`customer_id`, `menu_id`, `menu_option_id`, `filename`, `added_by`) VALUES (".$_POST['customer_id'].", ".$_POST['menu_id'].", ".$_POST['menu_option_id'].", '".$fullfilename."', ".$_POST['added_by'].")");
								if($req!=''){
									move_uploaded_file($_FILES["filename"]["tmp_name"], '../uploads/'.$year.'/'.$gy[0]['name'].'-'.$gy[0]['contact_no'] .'/'. $fullfilename);
									$response['id']=$req;
									$response['path']="http://".$this->ip."/scanner/uploads/".$year."/".$gy[0]['name'].'-'.$gy[0]['contact_no'] ."/". $fullfilename;
									$response['response'] = "success";
									$response['message'] = "File Uploaded.";
								}else{
									$response['response'] = "fail";
									$response['message'] = "Connection Error.";	
								}
							}
						}else{
							if($_FILES['filename']['size'] >=499999){
							$cf=$this->container->db->query("SELECT menu_id FROM customer_menu WHERE customer_id=".$_POST['customer_id']." and menu_id=".$_POST['menu_id']);

							if(!empty($cf)){
								$response['response'] = "fail";
								$response['message'] = "This Document is Alreay Exist. Delete old file and try again";
							}else{
								$req=$this->container->db->insertQuery("INSERT INTO `customer_menu` (`customer_id`, `menu_id`, `menu_option_id`, `filename`, `added_by`) VALUES (".$_POST['customer_id'].", ".$_POST['menu_id'].", ".$_POST['menu_option_id'].", '".$fullfilename."', ".$_POST['added_by'].")");
								if($req!=''){
									
									move_uploaded_file($_FILES["filename"]["tmp_name"], '..\\uploads\\'.$year.'\\'.$gy[0]['name'].'-'.$gy[0]['contact_no'] .'\\'."tem_".$fullfilename);
									
									$response['id']=$req;

									$response['path']="http://".$this->ip."/scanner/uploads/".$year."/".$gy[0]['name'].'-'.$gy[0]['contact_no'] ."/".$fullfilename;
									
									exec('ps2pdf -dPDFSETTINGS#/screen C:/xampp/htdocs/scanner/uploads/'.$year.'/'.$gy[0]['name'].'-'.$gy[0]['contact_no'] .'/'."tem_".$fullfilename .' C:/xampp/htdocs/scanner/uploads/'.$year.'/'.$gy[0]['name'].'-'.$gy[0]['contact_no'] .'/'. $fullfilename);
									
									exec('del C:\xampp\htdocs\scanner\uploads\\'.$year.'\\'.$gy[0]['name'].'-'.$gy[0]['contact_no'] .'\\'."tem_".$fullfilename);
									
									$response['response'] = "success";
									$response['message'] = "File Uploaded.";
								}else{
									$response['response'] = "fail";
									$response['message'] = "Connection Error.";	
								}
							}
						}else{
							$cf=$this->container->db->query("SELECT menu_id FROM customer_menu WHERE customer_id=".$_POST['customer_id']." and menu_id=".$_POST['menu_id']);

							if(!empty($cf)){
								$response['response'] = "fail";
								$response['message'] = "This Document is Alreay Exist. Delete old file and try again";
							}else{
								$req=$this->container->db->insertQuery("INSERT INTO `customer_menu` (`customer_id`, `menu_id`, `menu_option_id`, `filename`, `added_by`) VALUES (".$_POST['customer_id'].", ".$_POST['menu_id'].", ".$_POST['menu_option_id'].", '".$fullfilename."', ".$_POST['added_by'].")");
								if($req!=''){
									move_uploaded_file($_FILES["filename"]["tmp_name"], '../uploads/'.$year.'/'.$gy[0]['name'].'-'.$gy[0]['contact_no'] .'/'. $fullfilename);
									$response['id']=$req;
									$response['path']="http://".$this->ip."/scanner/uploads/".$year."/".$gy[0]['name'].'-'.$gy[0]['contact_no'] ."/". $fullfilename;
									$response['response'] = "success";
									$response['message'] = "File Uploaded.";	
								}else{
									$response['response'] = "fail";
									$response['message'] = "Connection Error.";	
								}
							}
						}
					}	
				}
			}
		}
		echo json_encode($response,JSON_UNESCAPED_SLASHES);
	}

	public function getDocumentsMenu($request, $response, $args) {
		$gdm=$this->container->db->query("SELECT * FROM menu");
		$response = array();
		$response['menu'] = array();
		if(!empty($gdm)){
			for($i=0;$i<sizeof($gdm);$i++){
				array_push($response['menu'],$gdm[$i]);
				$mo=$this->container->db->query("SELECT * FROM menu_option WHERE menu_id=".$gdm[$i]['menu_id']);
				array_push($response['menu'][$i],$mo);
			}
			$response['response'] = "success";
			$response['message'] = "Document List.";
		}else{
			$response['response'] = "fail";
			$response['message'] = "Connection Error.";
		}
		echo json_encode($response);
	}

	public function getUploadedDocumentList($request, $response, $args) {
		$gudl=$this->container->db->query("SELECT cm.*,CONCAT('http://".$this->ip."/scanner/uploads/',(SELECT YEAR(date) FROM customer WHERE customer_id=".$_POST['customer_id']."),'/',(SELECT name FROM customer WHERE customer_id=".$_POST['customer_id']."),'-',(SELECT contact_no FROM customer WHERE customer_id=".$_POST['customer_id']."),'/') as path FROM customer_menu cm WHERE cm.customer_id=".$_POST['customer_id']);
		$response = array();
		if(!empty($gudl)){
			$response['doc']=$gudl;
			$response['response'] = "success";
			$response['message'] = "Document List.";
		}else{
			$response['response'] = "fail";
			$response['message'] = "Connection Error.";
		}
		echo json_encode($response,JSON_UNESCAPED_SLASHES);
	}

	public function deleteDocument($request, $response, $args) {
		$gc=$this->container->db->query("SELECT c.date,c.name,c.contact_no,cm.filename FROM customer as c,customer_menu as cm WHERE  cm.customer_menu_id=".$_POST['customer_menu_id']." and c.customer_id=cm.customer_id");
		$response = array();
		if(!empty($gc)){
			$dd=$this->container->db->uquery("DELETE FROM customer_menu WHERE customer_menu_id=".$_POST['customer_menu_id']);
			if($dd['status']=='Success'){
				$year=date('Y',strtotime($gc[0]['date']));
					$filename_path = '../uploads/'.$year.'/'.$gc[0]['name'].'-'.$gc[0]['contact_no'].'/'.$gc[0]['filename'];
				unlink($filename_path);
				$response['response'] = "success";
				$response['message'] = "Document Deleted.";
			}else{
				$response['response'] = "fail";
				$response['message'] = "Connection Error.";
			}
		}else{
			$response['response'] = "fail";
			$response['message'] = "Connection Error.";
		}
		echo json_encode($response);
	}

	public function updateCustomerStatus($request, $response, $args) {
		$uc=$this->container->db->uquery("UPDATE customer SET status='".$_POST['status']."' WHERE customer_id=".$_POST['customer_id']);
		$response = array();
		if($uc['status']=='Success'){
				$response['response'] = "success";
				$response['message'] = "Status Successfuly Updated.";
			}else{
				$response['response'] = "fail";
				$response['message'] = "Connection Error.";
			}
		echo json_encode($response);
	}

	public function getPendingCustomerList($request, $response, $args) {
		$gpcl=$this->container->db->query("SELECT * FROM customer WHERE status='Pending'");
		$response = array();
		if(!empty($gpcl)){
				$response['customer']=$gpcl;
				$response['response'] = "success";
				$response['message'] = "Pending Customer List.";
			}else{
				$response['response'] = "fail";
				$response['message'] = "Connection Error.";
			}
		echo json_encode($response);	
	}

	public function getStatusCount($request, $response, $args) {
		$gpcl=$this->container->db->query("SELECT COUNT(CASE WHEN `status` = 'Pending' THEN 1 END) AS Pending, COUNT(CASE WHEN `status` = 'Completed' THEN 1 END) AS completed, COUNT(CASE WHEN `status` = 'Uploaded' THEN 1 END) AS Uploaded,COUNT(CASE WHEN `status` = 'SemiSuccessfull' THEN 1 END) AS SemiSuccessfull,COUNT(CASE WHEN `status` = 'FullSuccessfull' THEN 1 END) AS FullSuccessfull FROM customer");
		$response = array();
		if(!empty($gpcl)){
				$response['count']=$gpcl;
				$response['response'] = "success";
				$response['message'] = "Pending Customer List.";
			}else{
				$response['response'] = "fail";
				$response['message'] = "Connection Error.";
			}
		echo json_encode($response);	
	}
	
	public function getCompletedDocumentList($request, $response, $args) {
		$cq=$this->container->db->query("SELECT * FROM customer WHERE status='Completed'");
		$response = array();
		if(!empty($cq)){
			$response['customer']=$cq;
			$response['response'] = "success";
			$response['message'] = "Customer List.";
		}else{
			$response['response'] = "fail";
			$response['message'] = "No customer found";
		}
		echo json_encode($response,JSON_UNESCAPED_SLASHES);
	}

	public function uploadSemiSuccessfullDoc(){
		$gy=$this->container->db->query("SELECT c.date,c.name,c.contact_no FROM customer as c WHERE c.customer_id=".$_POST['customer_id']);

		$year=date('Y',strtotime($gy[0]['date']));
		$taxRecieptExt=strtolower(pathinfo($_FILES['taxReciept']['name'], PATHINFO_EXTENSION));
		$taxRecieptFilename='taxReciept.'.$taxRecieptExt;
		$crtmExt=strtolower(pathinfo($_FILES['crtm']['name'], PATHINFO_EXTENSION));
		$crtmFilename='crtm.'.$crtmExt;

		$uc=$this->container->db->uquery("UPDATE customer SET taxReceipt='".$taxRecieptFilename."',crtm='".$crtmFilename."',status='SemiSuccessfull' WHERE customer_id=".$_POST['customer_id']);
		$response = array();
		
		if($uc['status']=='Success'){
			move_uploaded_file($_FILES["taxReciept"]["tmp_name"], '../uploads/'.$year.'/'.$gy[0]['name'].'-'.$gy[0]['contact_no'] .'/'. $taxRecieptFilename);
			move_uploaded_file($_FILES["crtm"]["tmp_name"], '../uploads/'.$year.'/'.$gy[0]['name'].'-'.$gy[0]['contact_no'] .'/'. $crtmFilename);

			$response['response'] = "success";
			$response['message'] = "File Uploaded.";	
		}else{
			$response['response'] = "fail";
			$response['message'] = "Connection Error.";	
		}
		echo json_encode($response,JSON_UNESCAPED_SLASHES);
	}

	public function uploadFullSuccessfullDoc(){
		$gy=$this->container->db->query("SELECT c.date,c.name,c.contact_no FROM customer as c WHERE c.customer_id=".$_POST['customer_id']);

		$year=date('Y',strtotime($gy[0]['date']));
		$fitnessExt=strtolower(pathinfo($_FILES['fitness']['name'], PATHINFO_EXTENSION));
		$fitnessFilename='fitness.'.$fitnessExt;
		$permitExt=strtolower(pathinfo($_FILES['permit']['name'], PATHINFO_EXTENSION));
		$permitFilename='permit.'.$permitExt;
		$rcCopyExt=strtolower(pathinfo($_FILES['rcCopy']['name'], PATHINFO_EXTENSION));
		$rcCopyFilename='rcCopy.'.$rcCopyExt;

		$uc=$this->container->db->uquery("UPDATE customer SET fitness='".$fitnessFilename."',permit='".$permitFilename."',rcCopy='".$rcCopyFilename."',status='FullSuccessfull' WHERE customer_id=".$_POST['customer_id']);
		$response = array();
		
		if($uc['status']=='Success'){
			move_uploaded_file($_FILES["fitness"]["tmp_name"], '../uploads/'.$year.'/'.$gy[0]['name'].'-'.$gy[0]['contact_no'] .'/'. $fitnessFilename);
			move_uploaded_file($_FILES["permit"]["tmp_name"], '../uploads/'.$year.'/'.$gy[0]['name'].'-'.$gy[0]['contact_no'] .'/'. $permitFilename);
			move_uploaded_file($_FILES["rcCopy"]["tmp_name"], '../uploads/'.$year.'/'.$gy[0]['name'].'-'.$gy[0]['contact_no'] .'/'. $rcCopyFilename);

			$response['response'] = "success";
			$response['message'] = "File Uploaded.";	
		}else{
			$response['response'] = "fail";
			$response['message'] = "Connection Error.";	
		}
		echo json_encode($response,JSON_UNESCAPED_SLASHES);
	}

	public function getUploadedCustomerList($request, $response, $args) {
		$gpcl=$this->container->db->query("SELECT * FROM customer WHERE status='Uploaded'");
		
		$response = array();
		if(!empty($gpcl)){
				$response['customer']=$gpcl;
				$response['response'] = "success";
				$response['message'] = "Uploaded Customer List.";
			}else{
				$response['response'] = "fail";
				$response['message'] = "No Customer Found.";
			}
		echo json_encode($response);	
	}

	public function getSemiSuccessfullCustomerList($request, $response, $args) {
		$gpcl=$this->container->db->query("SELECT * FROM customer WHERE status='SemiSuccessfull'");
		$response = array();
		if(!empty($gpcl)){
				$response['customer']=$gpcl;
				$response['response'] = "success";
				$response['message'] = "SemiSuccessfull Customer List.";
			}else{
				$response['response'] = "fail";
				$response['message'] = "No Customer Found.";
			}
		echo json_encode($response);	
	}
	
	public function getFinalCustomerList($request, $response, $args) {
		$gpcl=$this->container->db->query("SELECT * FROM customer WHERE status='FullSuccessfull'");
		$response = array();
		if(!empty($gpcl)){
				$response['customer']=$gpcl;
				$response['response'] = "success";
				$response['message'] = "SemiSuccessfull Customer List.";
			}else{
				$response['response'] = "fail";
				$response['message'] = "No Customer Found.";
			}
		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('/addCustomer','PagesController:addCustomer');
$app->post('/uploadDoc','PagesController:uploadDoc');
$app->post('/getDocumentsMenu','PagesController:getDocumentsMenu');
$app->post('/getUploadedDocumentList','PagesController:getUploadedDocumentList');
$app->post('/deleteDocument','PagesController:deleteDocument');
$app->post('/updateCustomerStatus','PagesController:updateCustomerStatus');
$app->post('/getPendingCustomerList','PagesController:getPendingCustomerList');
$app->post('/getStatusCount','PagesController:getStatusCount');
$app->post('/getCompletedDocumentList','PagesController:getCompletedDocumentList');
$app->post('/uploadSemiSuccessfullDoc','PagesController:uploadSemiSuccessfullDoc');
$app->post('/uploadFullSuccessfullDoc','PagesController:uploadFullSuccessfullDoc');
$app->post('/getUploadedCustomerList','PagesController:getUploadedCustomerList');
$app->post('/getSemiSuccessfullCustomerList','PagesController:getSemiSuccessfullCustomerList');
$app->post('/getFinalCustomerList','PagesController:getFinalCustomerList');

//open customer path in admin panel on cusomer click

$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);
}*/
?>