<?php

    $countfiles = count($_FILES['files']['name']);
    //echo "Nombre de fichier qui seront traités : " .$countfiles ."<br>";

    //$upload_location = "/home/analogde/www/Fusion/File explorer/";

    //setcookie("cookie_upload", $pieces[1], time()+3600);
    $upload_location = $_COOKIE["cookie_upload"];


    //echo " Target " .$upload_location ."<br>";

    $arrFiles = scandir($upload_location);

    $retour_array = [];

    for($index = 0;$index < $countfiles;$index++)
    {
        $filename = $_FILES['files']['name'][$index];
        $basename = pathinfo($_FILES['files']['name'][$index], PATHINFO_FILENAME);
        $extension = pathinfo($_FILES['files']['name'][$index], PATHINFO_EXTENSION);
      
        $findFiles = [];
            
        for ($x = 0; $x < count($arrFiles); $x++)
        {
                    if(strpos( $arrFiles[$x], $basename) !== false)
                    {
                        $test_extension = pathinfo($arrFiles[$x], PATHINFO_EXTENSION);
                        //echo " +++++ " . $test_extension . " --- " .$extension ."<br><br>"; 

                        if( $test_extension == $extension)
                        {
                            $findFiles[] = $arrFiles[$x];
                        }
                    }
        }
            
        // 
        //echo "Liste des fichiers qui sont parents." ."<br><br>";
        //echo "<pre>";
        //print_r($findFiles);
        //echo "</pre>";

        if( count($findFiles) == 0)
        {
            //echo "Origine " ."<br>";
            $tmp_name = $_FILES['files']['tmp_name'][$index];
            $target = $upload_location .$_FILES['files']['name'][$index];

            //echo ">>>>>> " .$target ."<br><br>";

            $file_upload_status = move_uploaded_file($tmp_name, $target);
            if ($file_upload_status == true) 
            {
                $retour_array[] = message(true, $_FILES['files']['name'][$index], "origine");
                //$retour_array[] = "Bingo";

                $filename = $_FILES['files']['name'][$index];
                $filesize = $_FILES['files']['size'][$index];
                $filetype = $_FILES['files']['type'][$index];
                aaa($filename, $filename, $filesize, $filetype);
            } 
            else 
            {
                $retour_array[] = message(false, $_FILES['files']['name'][$index], $file_name_complete);
            }
        }
        else if( count($findFiles) == 1)
        {
            $datetime = date("d-m-Y_H:i:s");  
            $tmp_name = $_FILES['files']['tmp_name'][$index];
            $file_name_complete = $basename."_" .$datetime ."_" ."***rev_1***" ."." .$extension;
            $file_target_location = $upload_location . $file_name_complete;

            //echo ">>>>>> " .$file_target_location ."<br><br>";

            $file_upload_status = move_uploaded_file( $tmp_name, $file_target_location);
            if ($file_upload_status == true) 
            {
                $retour_array[] = message(true, $_FILES['files']['name'][$index], $file_name_complete);
                $filename = $_FILES['files']['name'][$index];
                $filesize = $_FILES['files']['size'][$index];
                $filetype = $_FILES['files']['type'][$index];
                aaa($_FILES['files']['name'][$index], $file_name_complete, $filesize, $filetype);

            } 
            else 
            {
                $retour_array[] = message(false, $_FILES['files']['name'][$index], $file_name_complete);
            }
        }
        else
        {
            for ($x = 0; $x < count($findFiles) ; $x++) 
            {
                $str = getBetween( $findFiles[$x], $start = "***", $end = "***");
                if( strlen($str) != 0)
                {
                    $array_version[] = str_replace("rev_","", $str);
                }
            }

            //echo "<pre>";
            //print_r($array_version);
            //echo "</pre>";
            $current_indice = max($array_version);
            $new_indice = $current_indice + 1;
            //echo " Nouvel indice " .$new_indice ."<br>";

            $datetime = date("d-m-Y_H:i:s");  
            $tmp_name = $_FILES['files']['tmp_name'][$index];
            $file_name_complete = $basename ."_" .$datetime ."_" ."***rev_" .$new_indice ."***" ."." .$extension;
            $file_target_location = $upload_location . $file_name_complete;

            //echo ">>>>>> " .$file_target_location ."<br><br>";

            $file_upload_status = move_uploaded_file( $tmp_name, $file_target_location);
            if ($file_upload_status == true) 
            {
                $retour_array[] = message(true, $_FILES['files']['name'][$index], $file_name_complete);
                $filename = $_FILES['files']['name'][$index];
                $filesize = $_FILES['files']['size'][$index];
                $filetype = $_FILES['files']['type'][$index];
                aaa($_FILES['files']['name'][$index], $file_name_complete, $filesize, $filetype);
            } 
            else 
            {
                $retour_array[] = message(false, $_FILES['files']['name'][$index], $file_name_complete);
            }
        }    
    }

   // unset($retour_array); 

    //$files_arr = array();


   /* $retour_array = array( 
        'geeks',   
        'for',  
        'geeks' 
    ); */

   
    //echo "<pre>";
    //print_r($retour_array);
    //echo "</pre>";

    //echo json_encode($files_arr);
    //die;

    echo json_encode($retour_array);
    die;
    

function message($value, $file_name, $revision)
{
        if($value)
        {
            if( $revision == "origine")
            {
                //$msg = "Le fichier " .$file_name ." vient d'être insérer dans le systéme de management des fichiers" ."<br>";
                $msg = "Insertion du fichier " .$file_name .".";
            }
            else
            {
                //$msg = "La version du fichier " .$file_name ." dispose d'une nouvelle version : " .$revision ."<img src='check.png' alt='Image' width='32' height='32'>" ."<br>";
                $msg = "Le fichier " .$file_name ." dispose d'une nouvelle version : " .$revision .".";
            }
        }
        else
        {
            $msg = "Erreur de transfert du fichier " .$file_name .".";
        }

        return $msg;
}

function getBetween($string, $start = "", $end = "")
{
    if (strpos($string, $start)) 
    { 
        $startCharCount = strpos($string, $start) + strlen($start);
        $firstSubStr = substr($string, $startCharCount, strlen($string));
        $endCharCount = strpos($firstSubStr, $end);
        if ($endCharCount == 0) {
            $endCharCount = strlen($firstSubStr);
        }
        return substr($firstSubStr, 0, $endCharCount);
    } 
    else 
    {
        return '';
    }
}  

function aaa($source, $version, $filesize, $filetype)
{

    $db_host = "analogdepat.mysql.db";
    $db_user = "analogdepat";
    $db_pass = "Un92pac007";
    $db_name = "analogdepat";

    $conn = new mysqli($db_host, $db_user, $db_pass, $db_name);

    /*if ($conn->connect_error) 
    {
       die("Connection failed: " . $conn->connect_error);
    }*/

      // Insert the file information into the database
      $sql = "INSERT INTO files (source, revision, filesize, filetype) VALUES ('$source', '$version', '$filesize', '$filetype')";

      $conn->query($sql);
      $conn->close();

/*
      CREATE TABLE `files` (
        `id` int(11) NOT NULL AUTO_INCREMENT,
        `source` varchar(200) NOT NULL,
        `revision` varchar(200) NOT NULL,
        `filesize` int(11) NOT NULL,
        `filetype` varchar(100) NOT NULL,
        `upload_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP
        PRIMARY KEY (id)
      ) 
   */   

     /*
      CREATE TABLE Persons (
        Personid int NOT NULL AUTO_INCREMENT,
        LastName varchar(255) NOT NULL,
        FirstName varchar(255),
        Age int,
        PRIMARY KEY (Personid)
    );
    */

}

?>