<?php
/**
 * fichiers-fragment.php (partage & admin)
 *
 * Returns the combined Format(s) + Fichiers block.
 *
 * Architecture:
 *   - Formats checkboxes: static, never swapped. They trigger HTMX swaps
 *     on individual #slot-siteweb, #slot-video, #slot-audio elements.
 *   - File inputs (couverture, note d'intention, TFE, annexes): always
 *     static in the DOM — never destroyed by format toggling.
 *   - Format-specific extras: each is a standalone HTMX fragment slot.
 *     When unchecked → empty hidden placeholder. When checked → input
 *     fields rendered via HTMX. This preserves FilePond instances on
 *     the main file inputs across format changes.
 *
 * Expected POST:
 *   formats[]       — array of selected format_type IDs
 *   website_url     — current value (repopulation)
 *   website_label   — current value (repopulation)
 *   admin_mode      — '1' for admin context (removes required attrs)
 */

require_once APP_ROOT . '/src/PeerTubeService.php';
$_ptDb = Database::getInstance();
$peerTubeEnabled = PeerTubeService::isEnabled($_ptDb);

$db = $_ptDb->getConnection();

// Load all format types in display order
$allFormats = $db->query('SELECT id, name FROM format_types ORDER BY sort_order, id')
                 ->fetchAll(PDO::FETCH_ASSOC);

// Build name→id map for format logic
$formatIdByName = [];
foreach ($allFormats as $f) {
    $formatIdByName[$f['name']] = (int)$f['id'];
}

$siteWebId = $formatIdByName['Site web'] ?? null;
$videoId   = $formatIdByName['Vidéo']    ?? null;
$audioId   = $formatIdByName['Audio']    ?? null;
$imageId   = $formatIdByName['Image']    ?? null;

$selectedFormats = isset($_POST['formats']) && is_array($_POST['formats'])
    ? array_map('intval', $_POST['formats'])
    : [];

$adminMode = ($_POST['admin_mode'] ?? '0') === '1';
$editMode  = ($_POST['edit_mode'] ?? '0') === '1';

$hasSiteWeb = $siteWebId && in_array($siteWebId, $selectedFormats, true);
$hasVideo   = $videoId   && in_array($videoId,   $selectedFormats, true);
$hasAudio   = $audioId   && in_array($audioId,   $selectedFormats, true);
$hasImage   = $imageId   && in_array($imageId,   $selectedFormats, true);

$hasNonWebFormat = !empty(array_filter(
    $selectedFormats,
    fn($id) => $id !== $siteWebId
));
$showUploadBlock = $hasNonWebFormat || !$hasSiteWeb;

$websiteUrl   = htmlspecialchars($_POST['website_url']   ?? '');
$websiteLabel = htmlspecialchars($_POST['website_label'] ?? '');

$hxPost = $adminMode ? '/admin/fichiers-fragment.php' : '/partage/fichiers-fragment';

$hasAnnexesChecked = !empty($_POST['has_annexes']);
?>
<!-- ═══════════════════ Format(s) + Fichiers (static, never swapped) ═══════════════════ -->
<div id="format-fichiers-block">
<input type="hidden" name="admin_mode" value="<?= $adminMode ? '1' : '0' ?>">
<input type="hidden" name="edit_mode" value="<?= $editMode ? '1' : '0' ?>">
<?php if ($editMode && ($_POST['_cover'] ?? null)): ?>
<input type="hidden" name="_cover" value="<?= htmlspecialchars($_POST['_cover']) ?>">
<?php endif; ?>

<!-- ═══════════════════ Format(s) ═══════════════════ -->
<fieldset>
    <legend>Format(s)</legend>
    <div>
        <span class="admin-row-label">Format(s) du TFE :<?= !$adminMode ? ' <span class="asterisk">*</span>' : '' ?></span>
        <fieldset class="admin-checkbox-group"
                  <?= !$adminMode ? 'required aria-required="true"' : '' ?> >
            <legend class="sr-only">Format(s) du TFE</legend>
            <ul>
                <?php foreach ($allFormats as $opt): ?>
                <li>
                    <label class="admin-checkbox-label">
                        <input type="checkbox"
                               name="formats[]"
                               value="<?= htmlspecialchars((string)$opt['id']) ?>"
                               <?= in_array((int)$opt['id'], $selectedFormats, true) ? 'checked' : '' ?>
                               <?php if ((int)$opt['id'] === ($siteWebId ?? 0)): ?>
                               hx-post="<?= htmlspecialchars($hxPost) ?>"
                               hx-target="#slot-siteweb"
                               hx-select="#slot-siteweb"
                               hx-trigger="change"
                               hx-include="[name='formats[]'], [name='website_url'], [name='admin_mode'], [name='edit_mode'], [name='_cover']"
                               hx-swap="outerHTML"
                               <?php endif; ?>
>
                        <?= htmlspecialchars($opt['name']) ?>
                    </label>
                </li>
                <?php endforeach; ?>
            </ul>
        </fieldset>
    </div>
</fieldset>

<!-- ═══════════════════ Fichiers ═══════════════════ -->
<fieldset>
    <legend>Fichiers</legend>

    <?php
    // Existing files + cover preview (edit mode only, initial render — not re-sent on HTMX swaps)
    $_efiles = $currentFiles ?? [];
    $_cover  = $_POST['_cover'] ?? null;
    if ($editMode && (!empty($_efiles) || $_cover)):
    ?>
    <div class="admin-form-group">
        <ul id="existing-files-sortable" class="admin-file-list">
            <?php
            // ── Couverture preview ──
            if ($_cover): ?>
            <li class="admin-file-list-item">
                <span class="admin-file-icon-col">🖼️</span>
                <span class="admin-file-info">
                    <span class="admin-file-name">Couverture</span>
                    <span class="admin-file-meta-row">
                        <img src="/media?path=<?= urlencode($_cover) ?>"
                             alt="Couverture actuelle" style="max-height:120px;border-radius:var(--radius);margin-top:var(--space-3xs);">
                    </span>
                    <label class="admin-checkbox-label" style="margin-top:var(--space-3xs);">
                        <input type="checkbox" name="remove_cover" value="1"> Supprimer
                    </label>
                </span>
            </li>
            <?php endif; ?>
            <?php
            // ── Existing files ──
            $_thesisFilesList = array_values(array_filter($_efiles, fn($f) => $f["file_type"] !== "cover"));
            foreach ($_thesisFilesList as $_f):
                $_fExt = strtolower(pathinfo($_f["file_path"] ?? "", PATHINFO_EXTENSION));
                $_fType = $_f["file_type"] ?? "other";
                $_fIcon = match (true) {
                    $_fType === "main" || $_fExt === "pdf" => "📄",
                    in_array($_fExt, ["jpg","jpeg","png","gif","webp"]) => "🖼️",
                    $_fType === "video" || in_array($_fExt, ["mp4","webm","mov","ogv"]) => "🎬",
                    $_fType === "audio" || in_array($_fExt, ["mp3","ogg","wav","flac","aac","m4a"]) => "🔊",
                    $_fType === "caption" || $_fExt === "vtt" => "💬",
                    $_fType === "website" => "🌐",
                    default => "📎",
                };
                $_fIsExternal = str_starts_with($_f["file_path"] ?? "", "http://") || str_starts_with($_f["file_path"] ?? "", "https://");
                $_fLinkHref = $_fIsExternal ? htmlspecialchars($_f["file_path"]) : "/media?path=" . urlencode($_f["file_path"]);
            ?>
            <li class="admin-file-list-item" data-file-id="<?= (int)$_f["id"] ?>">
                <input type="hidden" name="file_sort_order[]" value="<?= (int)$_f["id"] ?>">
                <span class="admin-file-icon-col"><?= $_fIcon ?></span>
                <span class="admin-file-info">
                    <a href="<?= $_fLinkHref ?>" target="_blank" rel="noopener" class="admin-file-name">
                        <?= htmlspecialchars($_f["file_name"] ?? basename($_f["file_path"])) ?>
                    </a>
                    <span class="admin-file-meta-row">
                        <span class="admin-file-type-badge"><?= htmlspecialchars($_fType) ?></span>
                        <?php if (!empty($_f["file_size"]) && $_f["file_size"] > 0): ?>
                        <span class="admin-file-size"><?= number_format($_f["file_size"] / 1024 / 1024, 2) ?> MB</span>
                        <?php endif; ?>
                    </span>
                    <input type="text" name="file_label[<?= (int)$_f["id"] ?>]"
                           value="<?= htmlspecialchars($_f["display_label"] ?? "") ?>"
                           placeholder="Légende / description (optionnel)"
                           class="admin-file-label-input">
                </span>
                <input type="hidden" name="delete_files[]" value="<?= (int)$_f["id"] ?>" disabled>
                <button type="button"
                        class="admin-btn-remove fq-remove"
                        onclick="this.previousElementSibling.disabled=false;this.closest('li').style.opacity='0.4';this.disabled=true;"
                        aria-label="Supprimer <?= htmlspecialchars($_f["file_name"] ?? basename($_f["file_path"])) ?>">&#x2715;</button>
            </li>
            <?php endforeach; ?>
        </ul>
    </div>
    <?php endif; ?>

    <!-- ── 1. Couverture (always, FilePond single-file) ── -->
    <?php
    $_cover = $_POST['_cover'] ?? null;
    if (!$editMode || !$_cover): ?>
    <div class="admin-form-group">
        <label for="couverture">Image de couverture (optionnel)</label>
        <div class="admin-file-input">
            <input type="file" id="couverture"
                   name="couverture"
                   class="tfe-file-picker tfe-file-picker--single"
                   data-queue-type="cover">
            <small>JPG, PNG ou WEBP. Format 4:3 recommandé. Max 20 MB.</small>
        </div>
    </div>
    <?php endif; unset($_cover); ?>

    <!-- ── 2. Note d'intention (always, FilePond single-file) ── -->
    <div class="admin-form-group">
        <label for="note_intention">Note d'intention<?= !$adminMode ? ' <span class="asterisk">*</span>' : '' ?></label>
        <div class="admin-file-input">
            <input type="file" id="note_intention"
                   name="note_intention"
                   class="tfe-file-picker tfe-file-picker--single"
                   data-queue-type="note_intention"
                   <?= !$adminMode ? 'required' : '' ?>>
            <small>PDF uniquement. Max 100 MB. Si votre fichier est trop lourd, compressez-le avec <a href="https://www.bentopdf.com" target="_blank" rel="noopener">bentopdf.com</a>.</small>
        </div>
    </div>

    <!-- ── 3. TFE — multi-file upload (FilePond) ── -->
    <div class="admin-form-group admin-files-fieldgroup">
        <label for="tfe-files-input">TFE<?= !$adminMode ? ' <span class="asterisk">*</span>' : '' ?></label>
        <div class="admin-file-input">
            <input type="file" id="tfe-files-input"
                   name="queue_file[tfe][]"
                   multiple
                   class="tfe-file-picker"
                   <?= !$adminMode ? 'required' : '' ?>>
            <small class="admin-file-hint">
                PDF (max 100 MB) · Images (max 500 MB) · Vidéo & Audio (max 2 GB) · VTT · Archives (max 500 MB).
                Glissez pour réordonner.
                PDFs trop lourds ? <a href="https://www.bentopdf.com" target="_blank" rel="noopener">https://bentopdf.com/</a>
            </small>
        </div>
    </div>

    <!-- ── 4. Annexes — multi-file upload (FilePond), always visible ── -->
    <div id="annexes-input-block">
        <!-- has_annexes checkbox disabled — annexe pool always on -->
        <input type="hidden" name="has_annexes" value="0">
        <div class="admin-form-group admin-files-fieldgroup">
            <label for="annexe-files-input">Annexes (optionnel)</label>
            <div class="admin-file-input">
                <input type="file" id="annexe-files-input"
                       name="queue_file[annexe][]"
                       multiple
                       class="tfe-file-picker">
                <small class="admin-file-hint">PDF ou archives ZIP/TAR. Max 500 MB. Glissez pour réordonner.</small>
            </div>
        </div>
    </div>

    <!-- ── Format-specific extras (individual swappable slots) ── -->
    <div id="format-extras-block" style="display:flex;flex-direction:column;gap:var(--space-s);">
        <!-- Slot: Site web -->
        <?php if ($hasSiteWeb): ?>
        <div id="slot-siteweb" class="admin-form-group">
            <label for="website_url">URL du site<?= !$adminMode ? ' <span class="asterisk">*</span>' : '' ?></label>
            <div class="admin-file-input">
                <input type="url" id="website_url" name="website_url"
                       value="<?= $websiteUrl ?>"
                       placeholder="https://mon-tfe.erg.be"
                       <?= !$adminMode ? 'required' : '' ?>>
                <small>Le TFE sera affiché comme un site embarqué sur sa page publique.</small>
            </div>
        </div>
        <?php else: ?>
        <div id="slot-siteweb" hidden></div>
        <?php endif; ?>

        <!-- Slot: Video (disabled — video files are now uploaded via the TFE input) -->
        <!--
        <?php if ($hasVideo): ?>
        <?php if ($peerTubeEnabled): ?>
        <div id="slot-video" class="admin-form-group">
            <label for="peertube_video">Vidéo PeerTube<?= !$adminMode ? ' <span class="asterisk">*</span>' : '' ?></label>
            <div class="admin-file-input">
                <input type="file" id="peertube_video" name="peertube_video"
                       accept="video/mp4,video/webm,video/ogg,video/quicktime,.mp4,.webm,.ogv,.mov"
                       <?= !$adminMode ? 'required' : '' ?>>
                <small>MP4, WebM ou MOV. La vidéo sera hébergée sur PeerTube. Max 500 MB.</small>
            </div>
        </div>
        <?php else: ?>
        <div id="slot-video" class="admin-form-group admin-files-fieldgroup">
            <label for="video-files-input">Vidéo<?= !$adminMode ? ' <span class="asterisk">*</span>' : '' ?></label>
            <div class="admin-file-input">
                <input type="file" id="video-files-input"
                       name="queue_file[video][]"
                       multiple
                       accept="video/mp4,video/webm,video/ogg,video/quicktime,.mp4,.webm,.ogv,.mov"
                       class="tfe-file-picker"
                       <?= !$adminMode ? 'required' : '' ?>>
                <small class="admin-file-hint">MP4, WebM ou MOV. Max 500 MB. Glissez pour réordonner.</small>
            </div>
        </div>
        <?php endif; ?>
        <?php else: ?>
        <div id="slot-video" hidden></div>
        <?php endif; ?>
        -->
        <div id="slot-video" hidden></div>

        <!-- Slot: Audio (disabled — audio files are now uploaded via the TFE input) -->
        <!--
        <?php if ($hasAudio): ?>
        <?php if ($peerTubeEnabled): ?>
        <div id="slot-audio" class="admin-form-group">
            <label for="peertube_audio">Audio PeerTube<?= !$adminMode ? ' <span class="asterisk">*</span>' : '' ?></label>
            <div class="admin-file-input">
                <input type="file" id="peertube_audio" name="peertube_audio"
                       accept="audio/mpeg,audio/ogg,audio/wav,audio/flac,audio/aac,audio/mp4,.mp3,.ogg,.oga,.wav,.flac,.aac,.m4a"
                       <?= !$adminMode ? 'required' : '' ?>>
                <small>MP3, OGG, WAV, FLAC ou AAC. Le fichier sera hébergé sur PeerTube. Max 500 MB.</small>
            </div>
        </div>
        <?php else: ?>
        <div id="slot-audio" class="admin-form-group admin-files-fieldgroup">
            <label for="audio-files-input">Audio<?= !$adminMode ? ' <span class="asterisk">*</span>' : '' ?></label>
            <div class="admin-file-input">
                <input type="file" id="audio-files-input"
                       name="queue_file[audio][]"
                       multiple
                       accept="audio/mpeg,audio/ogg,audio/wav,audio/flac,audio/aac,audio/mp4,.mp3,.ogg,.oga,.wav,.flac,.aac,.m4a"
                       class="tfe-file-picker"
                       <?= !$adminMode ? 'required' : '' ?>>
                <small class="admin-file-hint">MP3, OGG, WAV, FLAC ou AAC. Max 500 MB. Glissez pour réordonner.</small>
            </div>
        </div>
        <?php endif; ?>
        <?php else: ?>
        <div id="slot-audio" hidden></div>
        <?php endif; ?>
        -->
        <div id="slot-audio" hidden></div>

    </div>

</fieldset><!-- /Fichiers -->
</div><!-- #format-fichiers-block -->
