<?php
require_once(__DIR__.'/../ssinclude/app-init.php');
require_once(__DIR__.'/../ssinclude/app-session.php');

header('Content-Type: application/json');

try {
    // --- Récupération et décryptage des données POST ---
    $employee_id = decrypt_data($_POST['employee_id'] ?? '');
    $folder_id   = decrypt_data($_POST['folder_id'] ?? '');
    $sms_confirm = isset($_POST['sms_confirm']) && $_POST['sms_confirm'] == 1;

    if (!$employee_id || !$folder_id) {
        throw new Exception("Données manquantes pour l'upload.");
    }

    if (!isset($_FILES['file']) || $_FILES['file']['error'] !== UPLOAD_ERR_OK) {
        throw new Exception("Aucun fichier reçu ou erreur lors de l'upload.");
    }

    // --- Chemin absolu du dossier d'upload ---
    $baseUploadDir = __DIR__ . '/../' . files_upload_path;
    $baseUploadDir = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $baseUploadDir);

    // --- Créer sous-dossiers année/mois ---
    $year  = date('Y');
    $month = date('m');
    $targetDir = $baseUploadDir . $year . '/' . $month . '/';
    if (!is_dir($targetDir) && !mkdir($targetDir, 0775, true)) {
        throw new Exception("Impossible de créer le dossier d'upload : $targetDir");
    }

    // --- Nom haché pour éviter collisions ---
    $originalName = basename($_FILES['file']['name']);
    $fileExt = pathinfo($originalName, PATHINFO_EXTENSION);
    $hashedName = hash('sha256', uniqid('', true) . $originalName) . '.' . $fileExt;
    $filePath = $targetDir . $hashedName;

    // --- Déplacer le fichier uploadé ---
    if (!move_uploaded_file($_FILES['file']['tmp_name'], $filePath)) {
        throw new Exception("Erreur lors de l'enregistrement du fichier ($filePath).");
    }

    // --- Chemin relatif pour la DB ---
    $relativePath = 'medias/files/' . $year . '/' . $month . '/' . $hashedName;

    // --- URL publique pour le front ---
    $publicUrl = rtrim(app_domain_hostname, '/') . rtrim(files_base, '/') . '/' . $relativePath;

    // --- Récupération de la visibilité du dossier ---
    $visibilityStmt = $db->prepare("SELECT visibility, name FROM folders WHERE folder_id = ?");
    $visibilityStmt->execute([$folder_id]);
    $folderData = $visibilityStmt->fetch(PDO::FETCH_ASSOC);
    $visibility = $folderData['visibility'] ?? 'public';
    $folderName = $folderData['name'] ?? 'Racine';

    // --- Insertion dans la table `files` ---
    $stmt = $db->prepare("
        INSERT INTO files (folder_id, name, name_hashed, file_path, file_type, file_size, visibility)
        VALUES (?, ?, ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $folder_id,
        $originalName,
        $hashedName,
        $relativePath,
        $_FILES['file']['type'],
        $_FILES['file']['size'],
        $visibility
    ]);

    $file_id = $db->lastInsertId();

    // --- Lier le fichier à l'employé si le dossier est privé ---
    if ($visibility === 'private') {
        $stmt = $db->prepare("INSERT INTO employee_files (employee_id, file_id) VALUES (?, ?)");
        $stmt->execute([$employee_id, $file_id]);
    }

   // --- Notification SMS si demandée ---
if ($sms_confirm) {
    $folderPath = $folderName; // you can build full path if needed
    $notifStmt = $db->prepare("
        INSERT INTO notifications 
        (employee_id, title, message, use_sms, sms_sent)
        VALUES (?, ?, ?, 1, 0)
    ");
    $notifStmt->execute([
        $employee_id,
        "Nouveau document disponible",
        "Un nouveau fichier ($originalName) vient d’être ajouté à votre dossier [$folderPath] via " . strip_tags($soft_name)
    ]);

}
    // --- Retour JSON ---
    echo json_encode([
        "success" => true,
        "message" => "Fichier uploadé avec succès.",
        "file_id" => $file_id,
        "public_url" => $publicUrl
    ]);

} catch (Exception $e) {
    echo json_encode([
        "success" => false,
        "error" => $e->getMessage()
    ]);
}

require_once(__DIR__.'/../ssinclude/app-close.php');
