<?php // formulaire.php

// Configure error reporting
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', 'error.log');

// Log the content of the $_FILES array
error_log("FILES array: " . print_r($_FILES, true));

require_once 'vendor/autoload.php';
use Symfony\Component\Yaml\Yaml;
use Behat\Transliterator\Transliterator;

// Define variables
$yamlFolder = "data/yaml/";
$date = date("Y-m-d");

// Sanitize input data
$auteurice = filter_var($_POST["auteurice"], FILTER_SANITIZE_STRING);
$annee = filter_var($_POST["année"], FILTER_SANITIZE_NUMBER_INT);
$mail = filter_var($_POST["mail"], FILTER_SANITIZE_EMAIL);
$titre = filter_var($_POST["titre"], FILTER_SANITIZE_STRING);
$tag = filter_var($_POST["tag"], FILTER_SANITIZE_STRING);
$promoteurice = filter_var($_POST["promoteurice"], FILTER_SANITIZE_STRING);
$problematique = filter_var($_POST["problématique"], FILTER_SANITIZE_STRING);
$description = filter_var($_POST["description"], FILTER_SANITIZE_STRING);
$orientation = filter_var($_POST["orientation"], FILTER_SANITIZE_STRING);
$ap = filter_var($_POST["ap"], FILTER_SANITIZE_STRING);
$lien = filter_var($_POST["lien"], FILTER_SANITIZE_STRING);
$couverture = $_FILES["couverture"];
$files = $_FILES["files"];

// Transformation du string de mot-clé en un array. 
$tagArray = explode(', ', $tag);


$coverFolder = $memoireFolder . "data/cover/";
if (!file_exists($coverFolder)) {
    mkdir($coverFolder, 0755, true);
}

$couverturePath = "";
if ($couverture["error"] === UPLOAD_ERR_OK) {
    $fileExtension = pathinfo($couverture["name"], PATHINFO_EXTENSION);
    $newCouvertureName = $auteurice . "_" . $annee . "_" . $uniqueId . "." . $fileExtension;
    $targetFile = $coverFolder . $newCouvertureName;
    if (move_uploaded_file($couverture["tmp_name"], $targetFile)) {
        chmod($targetFile, 0644);
        $couverturePath = $targetFile;
    } else {
        error_log("Failed to move uploaded couverture file: " . $couverture["name"]);
    }
}

$uploadedFiles = [];

// Create necessary directories
$memoireFolder = "data/content/{$annee}/{$auteurice}/";
if (!file_exists($yamlFolder)) {
    mkdir($yamlFolder, 0755, true);
}
if (!file_exists($memoireFolder)) {
    mkdir($memoireFolder, 0755, true);
}

$targetDir = $memoireFolder;

// Generate unique file name
$uniqueId = time() . "_" . rand(1000, 9999);
$sanitizedAuteurice = Transliterator::transliterate($auteurice);
$uniqueFileName = $sanitizedAuteurice . "_" . $date . "_" . $uniqueId;

// Define security constraints
$allowedMimeTypes = ['image/jpeg', 'image/png', 'application/pdf', 'video/mp4', 'application/zip'];
$allowedExtensions = ['jpg', 'jpeg', 'png', 'pdf', 'mp4', 'zip'];
$maxFileSize = 50 * 1024 * 1024; // 50 MB

// Process uploaded files
if (is_array($files["name"])) {
    for ($i = 0; $i < count($files["name"]); $i++) {
        // Log the file being processed
        error_log("Processing file: " . $files["name"][$i]);
        // Check for file upload errors
        if ($files["error"][$i] !== UPLOAD_ERR_OK) {
            error_log("File upload error: " . $files["name"][$i]);
            continue;
        }

        // Check MIME type and file extension
        $finfo = new finfo(FILEINFO_MIME_TYPE);
        $mimeType = $finfo->file($files["tmp_name"][$i]);
        $fileExtension = pathinfo($files["name"][$i], PATHINFO_EXTENSION);

        if (!in_array($mimeType, $allowedMimeTypes) || !in_array($fileExtension, $allowedExtensions)) {
            error_log("Invalid file type or extension: " . $files["name"][$i]);
            continue;
        }

        // Check file size
        if ($files["size"][$i] > $maxFileSize) {
            error_log("File is too large: " . $files["name"][$i]);
            continue;
        }
        // Move and set permissions for the uploaded file
        $targetFile = $targetDir . basename($files["name"][$i]);
        if (move_uploaded_file($files["tmp_name"][$i], $targetFile)) {
            // Log successful file move
            error_log("File successfully moved: " . $targetFile);
            chmod($targetFile, 0644);
            $uploadedFiles[] = $targetFile;
        } else {
            error_log("Failed to move uploaded file: " . $files["name"][$i]);
        }
    }

}


// Prepare form data for YAML
$formData = [
    'auteurice' => $auteurice,
    'année' => $annee,
    'email' => $mail,
    'titre' => $titre,
    'tag' => $tagArray,
    'promoteurice' => $promoteurice,
    'problématique' => $problematique,
    'description' => $resume,
    'orientation' => $orientation,
    'ap' => $ap,
    'lien' => $lien,
    'couverture' => $couverturePath,
    'files' => $uploadedFiles
];

// Convert form data to YAML
$yamlData = Yaml::dump($formData);

// Save YAML file
$yamlFilePath = $yamlFolder . $uniqueFileName . ".yaml";
file_put_contents($yamlFilePath, $yamlData);

// Redirect to the thank you page
header('Location: thanks.php?file=' . urlencode($yamlFilePath));

?>