<?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["mypresentation"]["name"];

$folder = "../UploadedPresentations/";


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

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

move_uploaded_file($_FILES["mypresentation"]["tmp_name"], "$folder".$myFileName);

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

$userId = $_SESSION['user_id'];

$folder = "UploadedPresentations/";

$sql = "INSERT  INTO `presentation_table` (`titre`,`description`,`folder`, `name` , `userId`) 
            VALUES ('{$titre}','{$description}','{$folder}', '{$myFileName}','{$userId}')";

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

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

?>



