<?php
// download.php
include __DIR__ . '/user-ssinclude/user-init.php';
include __DIR__ . '/user-ssinclude/user-sessions.php';

try {

    /*----------------------------------------------------
      1) RÉCUPÉRATION & VALIDATION DU TOKEN (file_id chiffré)
    -----------------------------------------------------*/
    $encrypted_id = $_SERVER['QUERY_STRING'] ?? '';

    if (empty($encrypted_id)) {
        throw new Exception("Token manquant.");
    }

    $file_id = decrypt_data($encrypted_id);

    if (!is_numeric($file_id)) {
        throw new Exception("Token invalide.");
    }


    /*----------------------------------------------------
      2) CHARGER LE FICHIER EN DB
    -----------------------------------------------------*/
    $stmt = $db->prepare("
        SELECT file_id, name, name_hashed, file_path, visibility 
        FROM files 
        WHERE file_id = ?
    ");
    $stmt->execute([$file_id]);
    $file = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$file) {
        throw new Exception("Fichier introuvable.", 404);
    }


    /*----------------------------------------------------
      3) CONTRÔLE D'ACCÈS
         - Si visibility = public → OK
         - Si visibility = private → vérifier employee_files
    -----------------------------------------------------*/
    $currentEmployeeId = $sessionData['EMPLOYEE_ID'] ?? null;

    if (!$currentEmployeeId) {
        throw new Exception("Accès refusé (non connecté).", 403);
    }

    if ($file['visibility'] === 'private') {

        // Vérifier que ce fichier appartient à cet employé
        $aclStmt = $db->prepare("
            SELECT 1 
            FROM employee_files 
            WHERE file_id = ? AND employee_id = ?
            LIMIT 1
        ");
        $aclStmt->execute([$file_id, $currentEmployeeId]);
        $allowed = $aclStmt->fetchColumn();

        if (!$allowed) {
            throw new Exception("Accès refusé : fichier non associé à votre dossier.", 403);
        }
    }


    /*----------------------------------------------------
      4) LOCALISATION DU FICHIER PHYSIQUE
    -----------------------------------------------------*/
    $physicalPath = __DIR__ . '/' . ltrim($file['file_path'], '/');
    $physicalPath = str_replace(['/', '\\'], DIRECTORY_SEPARATOR, $physicalPath);

    if (!file_exists($physicalPath)) {
        throw new Exception("Fichier physiquement introuvable.", 404);
    }


    /*----------------------------------------------------
      5) DÉTECTION MIME TYPE
    -----------------------------------------------------*/
    if (function_exists('finfo_open')) {
        $finfo = finfo_open(FILEINFO_MIME_TYPE);
        $mimeType = finfo_file($finfo, $physicalPath);
        finfo_close($finfo);
    } else {
        $mimeType = mime_content_type($physicalPath) ?: 'application/octet-stream';
    }

    $downloadName = basename($file['name']);
    $downloadNameHeader = rawurlencode($downloadName);


/*----------------------------------------------------
  6) ENVOI DU FICHIER
-----------------------------------------------------*/
header('Pragma: public');
header('Expires: 0');
header('Content-Type: ' . $mimeType);

$inlineTypes = [
    'application/pdf',
    'image/jpeg',
    'image/png',
    'image/gif',
    'text/plain',
    'text/html'
];

// Use inline for supported types, else attachment
if (in_array($mimeType, $inlineTypes)) {
    header('Content-Disposition: inline; filename="' . $downloadName . '"; filename*=UTF-8\'\'' . $downloadNameHeader);
} else {
    header('Content-Disposition: attachment; filename="' . $downloadName . '"; filename*=UTF-8\'\'' . $downloadNameHeader);
}

header('Content-Length: ' . filesize($physicalPath));

if (ob_get_level()) ob_end_clean();

$handle = fopen($physicalPath, 'rb');

while (!feof($handle)) {
    echo fread($handle, 8192);
    flush();
    if (connection_aborted()) break;
}

fclose($handle);
exit();



} catch (Exception $e) {
    http_response_code($e->getCode() ?: 500);
    header('Content-Type: text/plain; charset=utf-8');
    echo "Erreur: " . $e->getMessage();
    exit();
}
