<?php
	require_once("db.php");
	
	$respond = array();
	$respond["status"]="failed";
	

	if(isset($_POST["username"]) && isset($_POST["token"]))
	{
		$username=$_POST["username"];
		$token=$_POST["token"];
		$fotostr = $_POST["fotostr"];
		$nophoto = $_POST["nophoto"];
		$NO_ID = $_POST["NO_ID"];
		
		$query = "select * from users where Username='$username' and token11='$token'";
		$result = mysqli_query($link,$query);
		if($row = mysqli_fetch_array($result))
		{
			
			$query = "select * from dm where USERNA='$username'";
			$result2 = mysqli_query($link,$query);
			if($row2 = mysqli_fetch_array($result2))
			{
				$ACPT = $row2["ACPT"];
				
			}
			if($ACPT == 1){
				$TRNAMA = "";
				$query = "select * from dmd where NO_ID='$NO_ID'";
				$result3 = mysqli_query($link,$query);
				if($row3 = mysqli_fetch_array($result3)){
					$TRNAMA = $row3["TRNAMA"];
				}
				$NO_BUKTI = $row2["NO_BUKTI"];
				$nama_file = $NO_BUKTI."-".$TRNAMA."_".$NO_ID;
				if($nophoto == 1){
					$nama_file .= "-A.jpg";
				}
				if($nophoto == 2){
					$nama_file .= "-B.jpg";
				}
				if($nophoto == 3){
					$nama_file .= "-C.jpg";
				}
				$angle = 0;
				
				//cek folder
				if (!file_exists('photo/'.$NO_BUKTI)) {
					mkdir('photo/'.$NO_BUKTI, 0777, true);
				}
				
				$imageName = "photo/".$NO_BUKTI."/".$nama_file;
			//    $imageName = "photo/".$nama_file;
				$imageData = base64_decode($fotostr);
				$source = imagecreatefromstring($imageData);
				$rotate = imagerotate($source, $angle, 0); // if want to rotate the image
				$imageSave = imagejpeg($rotate,$imageName,100);
				imagedestroy($source);
				
				$imageName = "SERVICES/".$imageName;
				
				if($nophoto == 1){
						$query = "update dmd set PIC1='$imageName' where NO_ID='$NO_ID'";
				            mysqli_query($link,$query);
				
				}
				if($nophoto == 2){
					$query = "update dmd set PIC2='$imageName' where NO_ID='$NO_ID'";
				            mysqli_query($link,$query);
				            
				}
				if($nophoto == 3){
							$query = "update dmd set PIC3='$imageName' where NO_ID='$NO_ID'";
				            mysqli_query($link,$query);
				            
				}
			

			
				
				$respond["status"] = "success";
			}
			
			
			
		}
	}
	
	echo json_encode($respond);
	
?>