<?php

require_once("functions.php");
require_once("db-const.php");
session_start();

$mysqli = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
# check connection
if ($mysqli->connect_errno) {
    echo "<p>MySQL error no {$mysqli->connect_errno} : {$mysqli->connect_error}</p>";
    exit();
}


$upload_image = $_FILES["myimage"]["name"];

$folder = "../UploadedImages/";

/*move_uploaded_file($_FILES["myimage"]["tmp_name"], "$folder".$_FILES["myimage"]["name"]);*/

$file = new SplFileInfo($_FILES["myimage"]["name"]);
$ext = $file->getExtension();
$generated = generateRandomString(7);

$myFileName = strtoupper($generated) . "." . $ext;


$typeRadioPrive = $_POST['radioPrive'];

if ("prive" != $typeRadioPrive){
    watermark_image($_FILES["myimage"]["tmp_name"], '../assets/img/watermark.png', "$folder" . $myFileName);
}else{
    watermark_image($_FILES["myimage"]["tmp_name"], '../assets/img/empty.png', "$folder" . $myFileName);
}

$titre = $mysqli->real_escape_string($_POST['titre']);
$description = $mysqli->real_escape_string($_POST['description']);

$typeRadioPhototheque = $_POST['radioPhototheque'];
if ($typeRadioPhototheque == "Organe")
    $idTypeImage = $_POST['typeOrgane'];
else
    $idTypeImage = $_POST['typePathologie'];


$userId = $_SESSION['user_id'];

$sql = "INSERT  INTO `image_table` (`titre`,`description`,`folder`, `name` ,`audience`, `userId`, `typePhototheque`, `idTypeImage`) 
            VALUES ('{$titre}','{$description}','{$folder}', '{$myFileName}','{$typeRadioPrive}', '{$userId}', '{$typeRadioPhototheque}', '{$idTypeImage}')";

if ($mysqli->query($sql)) {
    redirect_to("../images.php?type=$typeRadioPhototheque&id=$idTypeImage&msg=1");
} else {
    echo "<p>MySQL error no {$mysqli->errno} : {$mysqli->error}</p>";
    exit();
}


function watermark_image($target, $wtrmrk_file, $newcopy)
{
    $watermark = imagecreatefrompng($wtrmrk_file);
    imagealphablending($watermark, false);
    imagesavealpha($watermark, true);
    $img = imageCreateFromAny($target);
    $img_w = imagesx($img);
    $img_h = imagesy($img);
    $wtrmrk_w = imagesx($watermark);
    $wtrmrk_h = imagesy($watermark);
    $dst_x = ($img_w / 2) - ($wtrmrk_w / 2); // For centering the watermark on any image
    $dst_y = ($img_h / 2) - ($wtrmrk_h / 2); // For centering the watermark on any image
    imagecopy($img, $watermark, $dst_x, $dst_y, 0, 0, $wtrmrk_w, $wtrmrk_h);
    imagejpeg($img, $newcopy, 1000);
    imagedestroy($img);
    imagedestroy($watermark);

}

function imageCreateFromAny($filepath)
{
    $type = exif_imagetype($filepath); // [] if you don't have exif you could use getImageSize()
    $allowedTypes = array(
        1,  // [] gif
        2,  // [] jpg
        3,  // [] png
        6   // [] bmp
    );
    if (!in_array($type, $allowedTypes)) {
        return false;
    }
    switch ($type) {
        case 1 :
            $im = imageCreateFromGif($filepath);
            break;
        case 2 :
            $im = imageCreateFromJpeg($filepath);
            break;
        case 3 :
            $im = imageCreateFromPng($filepath);
            break;
        case 6 :
            $im = imageCreateFromBmp($filepath);
            break;
    }
    return $im;
}

function generateRandomString($length = 10)
{
    return substr(str_shuffle(str_repeat($x = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ', ceil($length / strlen($x)))), 1, $length);
}

?>



