 <?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header(
    "Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With"
);

require_once('config.php');

$json_return = array();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
	
    $count 				= $_REQUEST["count"];
    $json 				= json_decode($_REQUEST["json"]);
    $rowid 				= $json->data->rowid;
    $wko_isp_stp_rowid 	= $json->data->wko_isp_stp_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."\\mobile_image_temp\\temp_".$LOGINID."_".$dvc_id."\\";
	
	if (!is_dir($uploaddir)) {
			mkdir($uploaddir, 0777, true);
			mkdir($uploaddir."\\thumbnail\\", 0777, true);
	}

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

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

                if (!$stmt) {
                    returnError("Error inserting into table (wko_isp_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);
        }
		
		
		
		
		$sql = "SELECT Img = count(*) FROM wko_isp_ref (NOLOCK) WHERE site_cd = '".$site_cd."' AND wko_isp_ref_stp_RowID = '".$wko_isp_stp_rowid."'  and mst_RowID = '".$rowid."'";
			
		$stp_ref = sqlsrv_query( $conn, $sql);

		if( !$stp_ref ) {
			 $error_message = "Error selecting table (wko_isp_ref List)";
			 returnError($error_message);
			 die( print_r( sqlsrv_errors(), true));
		}

		$Img_count;

		do {
			 while ($row = sqlsrv_fetch_array($stp_ref, SQLSRV_FETCH_ASSOC)) {
				//$json_list[] = $row;
				
				$Img_count = $row['Img'];
				
			 }
		} while ( sqlsrv_next_result($stp_ref) );
				
    }

    returnData($json_return, $rowid,$Img_count);
}


function returnData($json_return, $rowid,$Img_count)
{
    $returnData = array(
        'status' => 'SUCCESS',
        'message' => 'Attachment uploaded successfully.',
        'rowid' => $rowid,
        'Img_count' => $Img_count,
        '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();
}
?>
