<?php
/**
 * format-website-fragment.php (admin)
 *
 * Admin-gated HTMX fragment: returns the Site web URL fieldset for the
 * admin edit form when "Site web" is among the selected format checkboxes.
 * Uses id="edit-website-url-fieldset" to avoid collision with the partage form.
 */
require_once __DIR__ . '/../../bootstrap.php';
require_once __DIR__ . '/../../src/AdminAuth.php';
App::boot();

AdminAuth::requireLogin();

$db = Database::getInstance()->getConnection();

$stmt = $db->prepare('SELECT id FROM format_types WHERE name = ? LIMIT 1');
$stmt->execute(['Site web']);
$websiteFormatId = $stmt->fetchColumn();

if (!$websiteFormatId) {
    echo '<fieldset id="edit-website-url-fieldset" style="display:none"></fieldset>';
    exit;
}

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

if (!in_array((int)$websiteFormatId, $selectedFormats, true)) {
    echo '<fieldset id="edit-website-url-fieldset" style="display:none"></fieldset>';
    exit;
}

$websiteUrl   = htmlspecialchars($_POST['website_url']   ?? '');
$websiteLabel = htmlspecialchars($_POST['website_label'] ?? '');
?>
<fieldset id="edit-website-url-fieldset">
    <legend>Site web</legend>
    <div class="admin-form-group">
        <label for="website_url">URL du site :</label>
        <div class="admin-file-input">
            <input type="url" id="website_url" name="website_url"
                   value="<?= $websiteUrl ?>"
                   placeholder="https://mon-tfe.erg.be">
            <small>Si le TFE est un site web, entrez son URL ici. Il sera affiché comme un site embarqué sur la page du TFE.</small>
        </div>
    </div>
    <div class="admin-form-group">
        <label for="website_label">Légende :</label>
        <input type="text" id="website_label" name="website_label"
               value="<?= $websiteLabel ?>"
               placeholder="Description du site (optionnel)"
               class="admin-file-label-input"
               style="max-width:400px;">
    </div>
</fieldset>
