<?php
require_once('config.php');


$json_return = array();


if ($_SERVER["REQUEST_METHOD"] == "POST") { 

	$count    	   	= $_REQUEST["count"];
	$json 			= $_REQUEST["json"];	
	$json 			= json_decode($json);	
	$rowid			= $json->data->rowid;
	$site_cd		= $json->data->site_cd;
	$EMPID			= $json->data->EMPID;
	$folder			= $json->data->folder;
	$LOGINID		= $json->data->LOGINID;	
	$dvc_id			= $json->data->dvc_id;
	
	$uploaddir = "C:\\wamp64\\www\\".$folder."\\mobile_image_temp\\temp_".$LOGINID."_".$dvc_id."\\";
	
	if (!is_dir($uploaddir)) {
		mkdir($uploaddir, 0777, true);
		mkdir($uploaddir."\\thumbnail\\", 0777, true);
	}
	
	
		
$sql = "select total = count(*) from ast_mst (NOLOCK), ast_ref (NOLOCK) where ast_mst.site_cd = ast_ref.site_cd
		and ast_mst.rowid= ast_ref.mst_rowid and ast_ref.type = 'P' and ast_mst.RowID = '".$rowid."'";	
		
	$stmt = sqlsrv_query( $conn, $sql);	
			
	if( !$stmt ) {
		$error_message = "Error selecting table (ast_mst, ast_ref)";
		returnError($error_message);
		die( print_r( sqlsrv_errors(), true));
	}
	do {
		 while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
		  $total = $row['total'];	 	 
	   }
	} while ( sqlsrv_next_result($stmt));
	
	for ($x = 1; $x <= $count; $x++) {
		
		$file = $_FILES['file_' . $x];
		$file_name = $file['name'];	
		$file_type = $file['type'];
		$imageObject = $file['tmp_name'];
		
		if ($x == 1) {
			if (strpos($file_name, '.pdf') !== false) {
				
				 $type = "A";
				 
			}else if (strpos($file_name, '.mp4') !== false) {

				 $type = "A";
				 
			}else{
				
				if($total == 0){
		
					$type = "P";
					
				}else{
					
					$type = "A";
				}

			}
		} else {
			$type = "A";
			
		}
		
		if (move_uploaded_file($imageObject, $uploaddir . $file_name)) {
			if (file_exists($uploaddir . $file_name)) {
				$data = bin2hex(file_get_contents($uploaddir . $file_name));
				$sql = "INSERT INTO ast_ref (site_cd, audit_user, audit_date, status, column1, file_name, type, mst_rowid, attachment, mbl_audit_user, mbl_audit_date, column2,category) 
						VALUES (?, ?, GETDATE(), 'Saved', 'Native_Mobile', ?, ?, ?, 0x$data, ?, GETDATE(), ?,'Asset Image'); 
						SELECT SCOPE_IDENTITY() as rowid";
				$params = array($site_cd, $LOGINID, $file_name, $type, $rowid, $LOGINID, $file_type);

				$stmt = sqlsrv_query($conn, $sql, $params);

				if (!$stmt) {
					returnError("Error inserting into table (ast_ref)");
				} else {
					unlink($uploaddir . $file_name);
				}

				while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
					$json_wko_ref = array('rowid' => $row['rowid'], 'action' => "INSERT");
					array_push($json_return, $json_wko_ref);
				}
			}
		} else {
			$json_wko_ref = array('rowid' => 0, 'action' => "move_uploaded_file failed for file ($file_name)");
			array_push($json_return, $json_wko_ref);
		}	
	}
	
	 returnData($json_return, $rowid);

}
		

function returnData($json_return, $rowid)
{
    $returnData = array(
        'status' => 'SUCCESS',
        'message' => 'Attachment inserted successfully',
        'rowid' => $rowid,
        'data' => $json_return
    );

    echo json_encode($returnData);
    exit();
}

function returnError($error_message)
{
    global $stmt, $conn;

    $json = array();
    $returnData = array(
        'status' => 'ERROR',
        'message' => $error_message,
        'data' => $json
    );

    echo json_encode($returnData);

    if (isset($stmt)) {
        sqlsrv_free_stmt($stmt);
    }
    if (isset($conn)) {
        sqlsrv_close($conn);
    }

    exit();
}

?>