<?php

$live = 1; // 0 for test and 1 for prod

//echo "started";

//print_r($_FILES);



header('Content-Type: application/json');

//require_once './vendor/autoload.php';



	if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }
  
	include("../php/configi.php");


  $theValue = function_exists("mysqli_real_escape_string") ? mysqli_real_escape_string($conn, $theValue) : mysqli_escape_string($conn, $theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

function ak_img_resize($target, $newcopy, $webpfile, $w, $h, $ext) {
	

    list($w_orig, $h_orig) = getimagesize($target);
    $scale_ratio = $w_orig / $h_orig;
    if (($w / $h) > $scale_ratio) {
           $w = $h * $scale_ratio;
    } else {
           $h = $w / $scale_ratio;
    }
    $img = "";
    $ext = strtolower($ext);
    if ($ext == "gif"){ 
      $img = imagecreatefromgif($target);
    } else if($ext =="png"){ 
      $img = imagecreatefrompng($target);
    } else { 
      $img = imagecreatefromjpeg($target);
    }
    $tci = imagecreatetruecolor($w, $h);
    // imagecopyresampled(dst_img, src_img, dst_x, dst_y, src_x, src_y, dst_w, dst_h, src_w, src_h)
    imagecopyresampled($tci, $img, 0, 0, 0, 0, $w, $h, $w_orig, $h_orig);
    imagejpeg($tci, $newcopy, 80);
	
	$quality = 100;
	
//	if ($ext == "jpg"){
		imagewebp($tci, $webpfile, $quality);
		
//	}
	
	
	//create webp
	
	

	
	

}
// Turn off vanilla PHP error reporting - not needed

function encrypt_decrypt($action, $string,$secret_key = "supersecret_key") {
    $output = false;
    $encrypt_method = "AES-256-CBC";
    $secret_iv = '~Z3$#SvEN83%6@n'; // change this to one more secure
    $key = hash('sha256', $secret_key);

    // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
    $iv = substr(hash('sha256', $secret_iv), 0, 16);
    if ( $action == 'encrypt' ) {
        $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
        $output = base64_encode($output);
    } else if( $action == 'decrypt' ) {
        $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
    }
    return $output;
}

error_reporting(0);

	require 'PHPMailer-master/PHPMailerAutoload.php';


// Location of temporary folder
$uploaddir = './tmp/';

//echo "post is".$_SERVER['REQUEST_METHOD'].basename($_FILES['file']['name']);

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
	
	$sel_uid = $_POST['sel_uid'];
	$image_no = $_POST['image_no'];	
	
	
//	echo "seluid is ".$sel_uid;
	
    $response = new \stdClass();

    $localUploadFile = $uploaddir . basename($_FILES['file']['name']);

    // Save it temporarly to server
    if (move_uploaded_file($_FILES['file']['tmp_name'], $localUploadFile)) {
        try {
            //Rename file
            $name = $_POST["name"];
            $documentName = $_POST["documentName"];
            $path_parts = pathinfo($localUploadFile);
            $newFileName = $uploaddir . $name . "-" . $documentName . "." . $path_parts['extension'];
			
			$file_name_raw = $name . "-" . $documentName . "." . $path_parts['extension'];
			

			$full_folder = "/home/phoegovg/app.phoenixcrm.co.nz/images/productsfull/";
			$thumb_folder = "/home/phoegovg/app.phoenixcrm.co.nz/images/productsthumb/";
			$webp_folder = "/home/phoegovg/app.phoenixcrm.co.nz/images/productswebp/";

			$file_name = $_COOKIE['phxcrmclient_id'] ."_".$sel_uid."_".$image_no.".".$path_parts['extension'];
			$file_name_webp = $_COOKIE['phxcrmclient_id'] ."_".$sel_uid."_".$image_no.".webp";
			
			$file_to_full = $full_folder . $file_name;
			$file_to_thumb = $thumb_folder . $file_name;
			$file_to_webp = $webp_folder . $file_name_webp;

	
	if(!copy($localUploadFile,$file_to_full)){
		echo "failed to copy $file";
	}else{
	//	echo "copied $file into $file_to\n";
	}
	
	$wmax = 400;
	$hmax = 500;
	
	$ext_resize = $path_parts['extension'];
	
	if ($ext_resize == "jpg" OR $ext_resize == "jpeg" OR $ext_resize == "png"){

		$result = ak_img_resize($file_to_full, $file_to_thumb, $file_to_webp, $wmax, $hmax, $path_parts['extension']);

	}
            // Delete tmp file
            unlink($localUploadFile);
			
			//update client_contacts to say that file uploaded

			$response->isSuccess = true;
    //        $response->fileType = $_POST["fileType"];
            $response->message = "Thank you. File has been uploaded!";
			
//			echo "dave123";
			
			include("../php/configi.php");
			
		//	$umessage = "File {$uploadFile->getServerRelativeUrl()} has been uploaded!";
						
			$u_file_to = GetSQLValueString($file_name, "text");
						

			$queryupdate2 = "update " . $_COOKIE['phxcrmclient_id'] . "_prod_search set prod_image_url".$image_no." = ".$u_file_to.", prod_image_qid = prod_image_qid + 1 where sel_uid = ".$sel_uid;


		//		echo $queryupdate2;
	
			$result2=mysqli_query($conn, $queryupdate2);


			
			if(!$result2){
				$phx_result = $phx_result."error has occurred while creating job details are " . mysqli_error() . $queryadd;
			}else{
				$phx_result = $phx_result."";
			}
			
		
			
			
		$response->message = "File has been uploaded!";			
			
        } catch (Exception $e) {
            $response->isSuccess = false;
            $response->message = "Error uploading file to server. Please ensure you selected a file.";
        }
    } else {
        $response->isSuccess = false;
        $response->message = "Error uploading file to server. Please ensure you selected a file.";
    };

    echo json_encode($response);
}


