<?php
session_start();
include_once "../../../config.php";
include_once "../../database1.php";
include_once "../../../validation.php";
include_once "../../../Helper.php";
require_once '../../../check_edit_page_ajax.php';

class ProductFileUpload extends database{
	public function index($data)
	{
		return $this->insert('tb_files', $data);
	}

	 
}

if(!isset($_FILES) || empty($_FILES))
{
	http_response_code(400);
	echo json_encode(array('error_text' => 'Please Upload File'));
	exit;
}

//$ds          = DIRECTORY_SEPARATOR;  //1
 
//$storeFolder = 'uploads';   //2
 
     
$tempFile = $_FILES['file']['tmp_name'];          //3             
  
// $targetPath = dirname( __FILE__ ) . $ds. $storeFolder . $ds;  //4
 
// $targetFile =  $targetPath. $_FILES['file']['name'];  //5

//move_uploaded_file($tempFile,$targetFile); //6


$target_dir = "../../../zillo.lt/zillio/public/uploads/products/";
$randName = rand(1000000,9999999) . '_' . date("YdmsiH") . '_' . basename($_FILES["file"]["name"]);
$target_file = $target_dir . $randName;
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));

$res = array();
$res['error_text'] = '';
// Check if file already exists
if (file_exists($target_file)) {
	$res['error_text'].= 'Something Went Wrong. Please Upload the file again.<br/>';
} 


// Check file size
if ($_FILES["file"]["size"] > 50000000000) {
    $res['error_text'].= 'Sorry, you file is too large. Cannot upload file.<br/>';
}

// Allow certain file formats
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif"  && $imageFileType != "webp" ) {
    $message.="Sorry, only JPG, JPEG, PNG, WEBP & GIF files are allowed.";
}

/*$allowed_types = array ( 'image/jpeg', 'image/png', 'image/gif');
$fileInfo = finfo_open(FILEINFO_MIME_TYPE);
$detected_type = finfo_file( $fileInfo, $_FILES['file']['tmp_name'] );
if ( !in_array($detected_type, $allowed_types) ) {
   	$res['error_text'].= 'Only jpg, jpeg, png, gif<br/>';
}
finfo_close( $fileInfo );*/


if(trim($res['error_text']) != '')
{
	http_response_code(400);
	echo json_encode($res);
	exit;
}

if (!move_uploaded_file($_FILES["file"]["tmp_name"], $target_file)) {
    http_response_code(400);
	echo json_encode(array('error_text' => 'File Not Uploaded. Please try again'));
	exit;
}

$validation = new validation();

$data['cl_actual_name'] = basename($_FILES["file"]["name"]);
$data['cl_type'] = 'Product';
$data['cl_product_id'] = $id;
$data['cl_name'] = $randName;
$data['cl_extension'] = $imageFileType;
$data['cl_user_id'] = $_SESSION['id'];

$obj = new ProductFileUpload();
$res = $obj->index($data);
if(!$res)
{
	http_response_code(500);
	echo json_encode(array('error_text' => 'Something Went Wrong While Adding File User. Please try again'));
	exit;
}

http_response_code(200);
echo json_encode(array('message' => 'File Added Successfully'));
exit;