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


$json_return = array();

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

	$count    	= $_REQUEST["count"];
	$json 		= json_decode($_REQUEST["json"]);
	$rowid		= $json->data->rowid;
	$site_cd	= $json->data->site_cd;
	$EMPID		= $json->data->EMPID;	
	$EMPNAME 	= $json->data->EmpName;	
	$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'];
		 $chart_id = uniqid();
		
		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{
				
				$type = "P";
			}
        } 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_ls11 (site_cd, 	mst_RowID, 	wko_ls11_name, 	wko_ls11_sts_upd, 	wko_ls11_category, 	status, 	type, 	file_name, 	attachment, 	audit_user, 	audit_date, 	column1, 	column2, 	column3, 	column4, 	column5, 	chatID) 
                        VALUES 				 (?, 		?, 			?, 				NULL, 				'Image', 			'Mobile', 	NULL, 	?, 			0x$data, 		?, 				GETDATE(),		NULL, 		NULL,		NULL, 		NULL, 		NULL, 		?); 
                        SELECT SCOPE_IDENTITY() as rowid";
                $params = array($site_cd, $rowid, $EMPNAME, $file_name, $EMPID, $chart_id);

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

                if (!$stmt) {
                    returnError("Error inserting into table (wko_ls11)");
                } 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);
        }
				
	}

		sqlsrv_free_stmt( $stmt);
				sqlsrv_close( $conn);	
	 returnData($json_return, $rowid);
	
}


function generateUniqueName($file_name, $image_count) {
	
    // Get current date in Ymd format (YearMonthDay)
	$date = date("Ymd"); 
	$random_id = rand(1000, 9999);
	// Concatenate date and image count with file extension
    $unique_name = $date . "_Chat_Ref_image_" . $image_count . ".jpeg"; 
    //$unique_name = "Asset_Ref_image_" . $image_count . ".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,
        'data' => $json
    );

    echo json_encode($returnData);

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

    exit();
}
		


?>	