<?php
include "script.php";

$refresh_rate = 15; //refresh rate en seconde (en gros on refresh la page toute les 15sec)

if($user['perm'] < 1) {
    header('Location: deco.php');
}


    // Compress image
function compressImage($source, $destination, $quality) {

    $info = getimagesize($source);

    if ($info['mime'] == 'image/jpeg') 
    $image = imagecreatefromjpeg($source);

    elseif ($info['mime'] == 'image/gif') 
    $image = imagecreatefromgif($source);

    elseif ($info['mime'] == 'image/png') 
    $image = imagecreatefrompng($source);
    
    imagejpeg($image, $destination, $quality);
  
  }

// ajout d'une epreuve
if(isset($_POST['add_photo'])){

    //$upload_state prend plusieurs valeurs :
    // 1 si tout est valide et l'image n'existe pas déjà
    // 0 si une verification a invalidé le fichier


    $EXT_WHITELIST = array("gif","jpg","jpeg","png");

    /* gestion des uploads d'images indices */
    $target_dir = "../assets/img/com_photo/full_q/";
    $target_file = $target_dir . basename($_FILES["photo"]["name"]);
    $upload_state = 1;
    $imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
    // Check if image file is a actual image or fake image
    $check = $_FILES["photo"]["size"] > pow(2,6);;
    if($check !== false) {
        $upload_state = 1;
    } else {
        $upload_state = 0;
    }

    if (file_exists($target_file)) {
        $upload_state = 0;
    }

    // limite de taille
    if ($_FILES["photo"]["size"] > pow(2,40)) {
        $upload_state = 0;
    }

    // check le type de fichier
    if (!in_array($imageFileType,$EXT_WHITELIST)){
        $upload_state = 0;
    }

    switch($upload_state){
        case 1:
            compressImage($_FILES["photo"]["tmp_name"],"../assets/img/com_photo/thumbs/".$_FILES["photo"]["name"],10);
            move_uploaded_file($_FILES["photo"]["tmp_name"],$target_file);
            break;
        case 0:
            ?> <script>
                alert("L'image envoyée n'a pas passées tout les tests de vérifications.");
                </script>
            <?php
            break;
    }




}









?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Admin / Com'Photo</title>
    <link rel="stylesheet" type="text/css" href="com_ville.css" />
</head>
<body>
    <main>

    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="photo" placeholder="image.png" id="photo" class="input_inline" accept=".png,.jpg,.jpeg,.gif">
        <label for="photo">Seulement les images au format gif, png, jpeg et jpg sont acceptées.</label>
        <input type="submit" name="add_photo" value="Ajouter la photo" class="submit_inline">
    </form>

    <h3>Difficultés pour convertir vos images au bon format ? Essayez <a href="https://image.online-convert.com/convert-to-jpg">Ce site</a></h3>

    </main>
</body>
</html>