<?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;
	$LOGINID		= $json->data->LOGINID;
	$folder			= $json->data->folder;
	$dvc_id			= $json->data->dvc_id;
	
	$uploaddir = "C:\\wamp64\\www\\".$folder."\\temp_".$dvc_id."\\";
	if (!is_dir($uploaddir)) {
		mkdir($uploaddir, 0777, true);
		mkdir($uploaddir."\\thumbnail\\", 0777, true);
	}
	
	
	
$sql = "select total = count(*) from wko_mst, wko_ref 
		where wko_mst.site_cd = wko_ref.site_cd
		and wko_mst.rowid= wko_ref.mst_rowid
		and wko_ref.type = 'P' 
		and wko_ref.mst_rowid = '".$rowid."'";	
		
$stmt = sqlsrv_query( $conn, $sql);	
		
if( !$stmt ) {
	$error_message = "Error update table (itm_mst)";
	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'];
		
		if (strpos($file_name, '.pdf') !== false) {
				
			$file_name = $file['name'];
			
		}else if (strpos($file_name, '.mp4') !== false) {
			
			 $file_name = $file['name'];
		}else{
			
			$file_name = generateUniqueName($file_name, $x);

			
		}
	
		$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 wko_ref (site_cd, audit_user, audit_date, status, column1, file_name, type, mst_rowid, attachment, mbl_audit_user, mbl_audit_date, column2) 
						VALUES (?, ?, GETDATE(), 'Saved', 'Native_Mobile', ?, ?, ?, 0x$data, ?, GETDATE(), ?); 
						SELECT SCOPE_IDENTITY() as rowid";
				$params = array($site_cd, $EMPID, $file_name, $type, $rowid, $LOGINID, $file_type);

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

				if (!$stmt) {
					returnError("Error inserting into table (wko_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 generateUniqueName($file_name, $image_count) {
	
    // Get current date in Ymd format (YearMonthDay);
	//$date = date("YmdHis");	
	
	$random_id = rand(100000, 999999);
	
	// Concatenate date and image count with file extension
    $unique_name = "WO_Ref_image_" . $random_id . ".jpeg"; 
    return $unique_name;
}
		
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
    );

    echo json_encode($returnData);

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

    exit();
}

?>