<?php
if($_COOKIE['sejahtera_role'] == 10)
{
	include_once ("includes/setup_pemohon.inc.php");
}
else
{
	include_once ("includes/setup.inc.php");
}

$ds          = DIRECTORY_SEPARATOR;  //1
$uploadId = fetch_postget_val('uploadId',$_POST, $_GET);
$program = fetch_postget_val('program',$_POST, $_GET);
$uploadFolder = fetch_postget_val('uploadFolder',$_POST, $_GET);
$generalName = fetch_postget_val('generalName',$_POST, $_GET);
$storeFolder = $uploadFolder. $ds .$uploadId;

if (!empty($_FILES)) 
{
    //only allow these format
	//.jpg, .jpeg, .png, .bmp
	$allowedFormat = array('image/jpeg','image/jpg','image/png','image/bmp', 'application/pdf');
	$file_type=$_FILES['uploadfile']['type'];
	if(!in_array($file_type, $allowedFormat)){
		echo "Hanya format .jpg, .jpeg, .png, .bmp, .pdf dibenarkan.";
		exit(-1);
	}
	
    $tempFile = $_FILES['uploadfile']['tmp_name']; 
	
	//Check if the directory already exists.
    $targetPath = dirname( __FILE__ ) . $ds. $storeFolder; 
    if(!is_dir($targetPath)){
		mkdir($targetPath, 0755, true);
	}
    $targetFile =  $targetPath . $ds . $_FILES['uploadfile']['name'];  
	
	//array_map('unlink', glob($targetPath."/"));
	if($generalName == '')
	{
		if( $file_type == 'application/pdf')
		{
			$generalName = 'dokumen_'.date('YmdHis').".pdf"; //YmdHis if dont have generalName
		}
		else
		{
			$generalName = 'dokumen_'.date('YmdHis').".jpg"; //YmdHis if dont have generalName
		}
	}
	$targetFile =  $targetPath . $ds . $generalName;
	move_uploaded_file($tempFile,$targetFile); //it will auto replace
	
	//save into dokumenupload log
	try
	{
		if($program == 5)
		{
			$indicator_Query = "SELECT *
								FROM m_anakemas
								WHERE id_anakemas = ?";
			$PDO_stmt = $PDO->prepare($indicator_Query); 
			$PDO_stmt->bindValue(1, $uploadId, PDO::PARAM_INT);
			$PDO_stmt->execute();
			$info_List = $PDO_stmt->fetch(PDO::FETCH_ASSOC);

			$uploadId = $info_List['id_pemohon'];
			$uploadanakId = $info_List['id_anakemas'];
		}
	
		$PASS_COUNTER = 0; //COUNTER FOR DOUBLE CONFIRM
		$PASS_VALUE = 1; //NUMBER OF QUERY TO EXECUTE. IMPORTANT FOR CHECKING!!

		//PDO INIT
		$PDO->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
		$PDO->beginTransaction();

		$dokumen_Array = array();
		$dokumen_Array[] = array('path_dokumenupload', $targetFile, PDO::PARAM_STR, 1);
		$dokumen_Array[] = array('id_pemohon', $uploadId, PDO::PARAM_INT);
		$dokumen_Array[] = array('id_anakemas', $uploadanakId, PDO::PARAM_INT);
		$dokumen_Array[] = array('id_pelajaremas', '', PDO::PARAM_INT);
		$dokumen_Array[] = array('id_program', $program, PDO::PARAM_INT);
		$dokumen_Array[] = array('id_upload', $my_details->usr_id, PDO::PARAM_INT);
		$dokumen_Array[] = array('id_peranan', $my_details->user_level, PDO::PARAM_INT);
		$dokumen_Array[] = array('tindakan', 'U', PDO::PARAM_INT);
		$dokumen_Array[] = array('tkh_tindakan', dateTimeNow(), PDO::PARAM_STR);

		$PASS_COUNTER += PDO_INSERT($PDO, 'm_dokumenupload', $dokumen_Array);

		//*****************************************
		//COMMIT if PASS_COUNTER == PASS_VALUE
		//*****************************************
		if ($PASS_COUNTER == $PASS_VALUE)
		{
			$PDO->commit();
		}
		else
		{
			$PDO->rollBack();
		}
	}
	catch (Exception $e) 
	{
		$PDO->rollBack();
		echo "Failed: " . $e->getMessage();
	}
	
	//echo $storeFolder . $ds . $generalName;
	echo $generalName;
}
else {
    $result  = array();
	
	$targetPath = dirname( __FILE__ ) . $ds. $storeFolder; 
	//echo "storeFolder = $storeFolder <br>";
	//echo "targetPath = $targetPath";
    $files = scandir($storeFolder);                 //1
    if ( false!==$files ) {
        foreach ( $files as $file ) {
			//echo $file.'<br>';
            if ( '.'!=$file && '..'!=$file && 'pdf.jpg'!=$file && is_file($storeFolder.$ds.$file)) {       //2
                //echo $main.' & preg_match ('.$file.', main_'.$br_id.'_ori) = '.preg_match ( '/^main\_'.$br_id.'\_ori/', $file).'<br>';
				//if($main == 0 || ($main == 1 && preg_match ( '/^main\_'.$br_id.'\_ori/', $file) == 1))
				{
					$obj['name'] = $file;
					$obj['size'] = filesize($storeFolder.$ds.$file);
					$result[] = $obj;
				}
            }
        }
    }
     
    header('Content-type: text/json');              //3
    header('Content-type: application/json');
    echo json_encode($result);
}

?>  