<?php
/**
 * Confirmation / recap page for share-link submissions.
 * Displays the submitted thesis details and uploaded files.
 */
if (!defined('APP_ROOT')) {
    require_once __DIR__ . '/../../bootstrap.php';
    App::boot();
}

require_once APP_ROOT . '/src/EmailObfuscator.php';

$thesisId = isset($_GET['id']) ? (int)$_GET['id'] : 0;

if ($thesisId <= 0) {
    http_response_code(400);
    die('ID de TFE invalide.');
}

$db     = Database::getInstance();
$thesis = $db->getThesis($thesisId);
if (!$thesis) {
    http_response_code(404);
    die('TFE introuvable.');
}

$files = $db->getThesisFiles($thesisId);

// Was the confirmation e-mail sent?
$emailSent = !empty($_SESSION['share_email_sent']);
unset($_SESSION['share_email_sent']);

// Derive share-link slug from the URI so we can build the "submit another" link.
$pathParts = explode('/', trim(parse_url($_SERVER['REQUEST_URI'] ?? '', PHP_URL_PATH), '/'));
// URI is /partage/recapitulatif?id=N  → parts[0]=partage, parts[1]=recapitulatif
// We have no slug here, so just link back to /partage/ root.
$slug = null;

function partageFormatFileSize(int $bytes): string {
    if ($bytes >= 1073741824) return number_format($bytes / 1073741824, 2) . ' GB';
    if ($bytes >= 1048576)   return number_format($bytes / 1048576, 2) . ' MB';
    if ($bytes >= 1024)      return number_format($bytes / 1024, 2) . ' KB';
    return $bytes . ' B';
}

$pageTitle = 'Merci — TFE enregistré';
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= htmlspecialchars($pageTitle) ?></title>
    <link rel="apple-touch-icon" sizes="152x152" href="/assets/favicon/apple-touch-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="167x167" href="/assets/favicon/apple-touch-icon-167x167.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/assets/favicon/apple-touch-icon-180x180.png">
    <link rel="icon" type="image/png" sizes="32x32" href="/assets/favicon/favicon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="/assets/favicon/favicon-16x16.png">
    <link rel="shortcut icon" href="/assets/favicon/favicon.ico">
    <link rel="stylesheet" href="<?= App::assetV('/assets/css/common.css') ?>">
    <link rel="stylesheet" href="<?= App::assetV('/assets/css/form.css') ?>">
</head>
<body class="student-body">
    <main id="main-content" class="partage-recap">

        <div class="thanks-success">
            <h1>✅ Merci !</h1>
            <p class="thanks-message">Votre TFE a bien été enregistré sur la plateforme.</p>
            <?php if ($emailSent): ?>
            <p class="flash-success">📧 Un e-mail de confirmation a été envoyé avec un récapitulatif de votre soumission.</p>
            <?php endif; ?>
        </div>

        <div class="recap-validate-notice">
            <p>Veuillez vérifier les informations ci-dessous. Si vous constatez une erreur, contactez-nous à <a href="<?= EmailObfuscator::mailto('xamxam@erg.be') ?>"><?= EmailObfuscator::email('xamxam@erg.be') ?></a>.</p>
        </div>

        <section class="recap-section">
            <h2>Récapitulatif de votre soumission</h2>
            <dl class="recap-dl">
                <?php if (!empty($thesis['identifier'])): ?>
                <dt>Identifiant</dt>
                <dd><?= htmlspecialchars($thesis['identifier']) ?></dd>
                <?php endif; ?>

                <dt>Titre</dt>
                <dd><?= htmlspecialchars($thesis['title']) ?></dd>

                <?php if (!empty($thesis['subtitle'])): ?>
                <dt>Sous-titre</dt>
                <dd><?= htmlspecialchars($thesis['subtitle']) ?></dd>
                <?php endif; ?>

                <?php if (!empty($thesis['authors'])): ?>
                <dt>Auteur·ice(s)</dt>
                <dd><?= htmlspecialchars($thesis['authors']) ?></dd>
                <?php endif; ?>

                <?php if (!empty($thesis['year'])): ?>
                <dt>Année</dt>
                <dd><?= htmlspecialchars((string)$thesis['year']) ?></dd>
                <?php endif; ?>

                <?php if (!empty($thesis['orientation'])): ?>
                <dt>Orientation</dt>
                <dd><?= htmlspecialchars($thesis['orientation']) ?></dd>
                <?php endif; ?>

                <?php if (!empty($thesis['ap_program'])): ?>
                <dt>Atelier pluridisciplinaire</dt>
                <dd><?= htmlspecialchars($thesis['ap_program']) ?></dd>
                <?php endif; ?>

                <?php if (!empty($thesis['finality_type'])): ?>
                <dt>Finalité</dt>
                <dd><?= htmlspecialchars($thesis['finality_type']) ?></dd>
                <?php endif; ?>

                <?php if (!empty($thesis['synopsis'])): ?>
                <dt>Synopsis</dt>
                <dd><?= nl2br(htmlspecialchars($thesis['synopsis'])) ?></dd>
                <?php endif; ?>

                <?php if (!empty($thesis['languages'])): ?>
                <dt>Langue(s)</dt>
                <dd><?= htmlspecialchars($thesis['languages']) ?></dd>
                <?php endif; ?>

                <?php if (!empty($thesis['formats'])): ?>
                <dt>Format(s)</dt>
                <dd><?= htmlspecialchars($thesis['formats']) ?></dd>
                <?php endif; ?>

                <?php if (!empty($thesis['keywords'])): ?>
                <dt>Mots-clés</dt>
                <dd><?= htmlspecialchars($thesis['keywords']) ?></dd>
                <?php endif; ?>

                <?php if (!empty($thesis['jury_promoteurs'])): ?>
                <dt>Promoteur·ice(s) interne</dt>
                <dd><?= htmlspecialchars($thesis['jury_promoteurs']) ?></dd>
                <?php endif; ?>

                <?php if (!empty($thesis['jury_promoteurs_ulb'])): ?>
                <dt>Promoteur·ice(s) ULB</dt>
                <dd><?= htmlspecialchars($thesis['jury_promoteurs_ulb']) ?></dd>
                <?php endif; ?>

                <?php if (!empty($thesis['jury_lecteurs_internes'])): ?>
                <dt>Lecteur·ice(s) interne</dt>
                <dd><?= htmlspecialchars($thesis['jury_lecteurs_internes']) ?></dd>
                <?php endif; ?>

                <?php if (!empty($thesis['jury_lecteurs_externes'])): ?>
                <dt>Lecteur·ice(s) externe</dt>
                <dd><?= htmlspecialchars($thesis['jury_lecteurs_externes']) ?></dd>
                <?php endif; ?>

                <?php if (!empty($thesis['baiu_link'])): ?>
                <dt>Lien</dt>
                <dd><a href="<?= htmlspecialchars($thesis['baiu_link']) ?>" target="_blank" rel="noopener"><?= htmlspecialchars($thesis['baiu_link']) ?></a></dd>
                <?php endif; ?>

                <?php if (!empty($thesis['license_type'])): ?>
                <dt>Licence</dt>
                <dd><?= htmlspecialchars($thesis['license_type']) ?><?= !empty($thesis['license_custom']) ? ' — ' . htmlspecialchars($thesis['license_custom']) : '' ?></dd>
                <?php endif; ?>

                <?php if (!empty($thesis['access_type'])): ?>
                <dt>Type d'accès</dt>
                <dd><?= htmlspecialchars($thesis['access_type']) ?></dd>
                <?php endif; ?>
            </dl>

            <?php if (!empty($files)): ?>
            <h2>Fichiers soumis</h2>
            <ul class="recap-file-list">
                <?php foreach ($files as $f): ?>
                <?php
                    $mime     = $f['mime_type'] ?? '';
                    $isImage  = str_starts_with($mime, 'image/');
                    $mediaUrl = '/media.php?path=' . urlencode($f['file_path']);
                    $fileName = htmlspecialchars($f['file_name'] ?? basename($f['file_path']));
                    $fileType = htmlspecialchars($f['file_type']);
                ?>
                <li class="recap-file-item">
                    <?php if ($isImage): ?>
                    <a href="<?= $mediaUrl ?>" target="_blank" rel="noopener" class="recap-file-thumb-link">
                        <img src="<?= $mediaUrl ?>" alt="<?= $fileName ?>" class="recap-file-thumb" loading="lazy">
                    </a>
                    <?php else: ?>
                    <span class="recap-file-icon">
                        <?php
                        if ($mime === 'application/pdf')   echo '📄';
                        elseif (str_starts_with($mime, 'video/')) echo '🎬';
                        elseif (str_starts_with($mime, 'audio/')) echo '🎵';
                        elseif (in_array($mime, ['application/zip','application/x-zip-compressed'])) echo '🗜️';
                        elseif (str_ends_with($f['file_name'] ?? '', '.vtt')) echo '💬';
                        else echo '📎';
                        ?>
                    </span>
                    <?php endif; ?>
                    <div class="recap-file-meta">
                        <span class="recap-file-name"><?= $fileName ?></span>
                        <span class="recap-file-type-badge"><?= $fileType ?></span>
                        <span class="recap-file-size"><?= partageFormatFileSize((int)$f['file_size']) ?></span>
                    </div>
                </li>
                <?php endforeach; ?>
            </ul>
            <?php endif; ?>
        </section>

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