<?php
function document_setting_value(
    array $settings,
    string $key,
    string $default = ''
): string {
    return htmlspecialchars(
        (string)($settings[$key] ?? $default),
        ENT_QUOTES,
        'UTF-8'
    );
}

$raisonSociale = (string)($settings['raison_sociale'] ?? 'Darlink ERP');
$nomCommercial = (string)($settings['nom_commercial'] ?? '');
$ville = (string)($settings['ville'] ?? '');
$logoInformation = null;
$logoPath = (string)($settings['logo_path'] ?? '');

if ($logoPath !== '') {
    $logoRelativePath = (string)(parse_url($logoPath, PHP_URL_PATH) ?? '');
    $logoRelativePath = ltrim($logoRelativePath, '/\\');

    $logoPhysicalPath = dirname(__DIR__, 3)
        . DIRECTORY_SEPARATOR
        . 'public'
        . DIRECTORY_SEPARATOR
        . str_replace(
            ['/', '\\'],
            DIRECTORY_SEPARATOR,
            $logoRelativePath
        );

    if (is_file($logoPhysicalPath)) {
        $fileSize = filesize($logoPhysicalPath);
        $dimensions = @getimagesize($logoPhysicalPath);

        $logoInformation = [
            'name' => basename($logoRelativePath),
            'format' => strtoupper(pathinfo($logoRelativePath, PATHINFO_EXTENSION)),
            'size' => $fileSize !== false ? $fileSize : 0,
            'width' => is_array($dimensions) ? (int)($dimensions[0] ?? 0) : 0,
            'height' => is_array($dimensions) ? (int)($dimensions[1] ?? 0) : 0,
        ];
    }
}

$previewFooterText = trim((string)($settings['pied_de_page'] ?? ''));
if ($previewFooterText === '') {
    $previewFooterText = 'Informations de la société générées automatiquement';
}
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div>
        <h1 class="darlink-title mb-1">
            <i class="bi bi-palette me-2"></i>
            Configuration des documents PDF
        </h1>
        <p class="text-muted mb-0">
            Configurer l’identité visuelle, les conditions, les mentions et le pied de page des documents PDF.
        </p>
    </div>

    <a href="index.php?page=parametres" class="btn btn-outline-secondary">
        <i class="bi bi-arrow-left me-1"></i>
        Retour aux paramètres
    </a>
</div>

<?php if (!empty($errors['general'])): ?>
    <div class="alert alert-danger">
        <?= htmlspecialchars($errors['general']) ?>
    </div>
<?php endif; ?>

<form
    method="post"
    action="index.php?page=parametres_documents_save"
    enctype="multipart/form-data"
>
    <div class="row g-4">
        <div class="col-xl-7">
            <ul
                class="nav nav-pills darlink-settings-tabs mb-4"
                id="documentSettingsTabs"
                role="tablist"
            >
                <li class="nav-item" role="presentation">
                    <button
                        class="nav-link active"
                        id="appearance-tab"
                        data-bs-toggle="pill"
                        data-bs-target="#appearance-pane"
                        type="button"
                        role="tab"
                        aria-controls="appearance-pane"
                        aria-selected="true"
                    >
                        <i class="bi bi-palette me-2"></i>
                        Apparence
                    </button>
                </li>

                <li class="nav-item" role="presentation">
                    <button
                        class="nav-link"
                        id="quotation-tab"
                        data-bs-toggle="pill"
                        data-bs-target="#quotation-pane"
                        type="button"
                        role="tab"
                        aria-controls="quotation-pane"
                        aria-selected="false"
                    >
                        <i class="bi bi-file-earmark-text me-2"></i>
                        Devis et livraison
                    </button>
                </li>

                <li class="nav-item" role="presentation">
                    <button
                        class="nav-link"
                        id="billing-tab"
                        data-bs-toggle="pill"
                        data-bs-target="#billing-pane"
                        type="button"
                        role="tab"
                        aria-controls="billing-pane"
                        aria-selected="false"
                    >
                        <i class="bi bi-receipt me-2"></i>
                        Facturation
                    </button>
                </li>

                <li class="nav-item" role="presentation">
                    <button
                        class="nav-link"
                        id="legal-tab"
                        data-bs-toggle="pill"
                        data-bs-target="#legal-pane"
                        type="button"
                        role="tab"
                        aria-controls="legal-pane"
                        aria-selected="false"
                    >
                        <i class="bi bi-shield-check me-2"></i>
                        Informations légales
                    </button>
                </li>
            </ul>

            <div class="tab-content" id="documentSettingsTabsContent">
                <div
                    class="tab-pane fade show active"
                    id="appearance-pane"
                    role="tabpanel"
                    aria-labelledby="appearance-tab"
                    tabindex="0"
                >
                    <div class="darlink-card overflow-hidden mb-4">
                        <div class="darlink-admin-block-header">
                            <i class="bi bi-image me-2"></i>
                            Identité visuelle
                        </div>

                        <div class="darlink-card-body">
                            <div class="row g-3">
                                <div class="col-md-12 darlink-form-group">
                                    <label class="darlink-label">
                                        Logo de l’entreprise
                                    </label>

                                    <input
                                        type="hidden"
                                        name="logo_path"
                                        value="<?= document_setting_value($settings, 'logo_path') ?>"
                                    >

                                    <input
                                        type="file"
                                        name="logo_file"
                                        id="documentLogoFile"
                                        accept=".png,.jpg,.jpeg,image/png,image/jpeg"
                                        hidden
                                    >

                                    <div class="darlink-logo-manager">
                                        <div
                                            class="darlink-logo-current"
                                            id="documentLogoCurrent"
                                        >
                                            <?php if (!empty($settings['logo_path'])): ?>
                                                <img
                                                    src="<?= htmlspecialchars($settings['logo_path']) ?>"
                                                    alt="Logo actuel"
                                                    id="documentLogoManagerImage"
                                                >
                                            <?php else: ?>
                                                <div
                                                    class="darlink-logo-placeholder"
                                                    id="documentLogoManagerPlaceholder"
                                                >
                                                    <i class="bi bi-image"></i>
                                                    <span>Aucun logo sélectionné</span>
                                                </div>
                                            <?php endif; ?>
                                        </div>

                                        <div>
                                            <label
                                                for="documentLogoFile"
                                                class="btn darlink-btn-primary"
                                            >
                                                <i class="bi bi-upload me-1"></i>
                                                Choisir un logo
                                            </label>

                                            <?php if (!empty($settings['logo_path'])): ?>
                                                <button
                                                    type="submit"
                                                    formaction="index.php?page=parametres_documents_logo_delete"
                                                    formmethod="post"
                                                    class="btn btn-outline-danger ms-2"
                                                    onclick="return confirm('Supprimer définitivement le logo actuel ?');"
                                                >
                                                    <i class="bi bi-trash me-1"></i>
                                                    Supprimer le logo
                                                </button>
                                            <?php endif; ?>

                                            <div class="form-text mt-2" id="documentLogoFileName">
                                                PNG ou JPG — 2 Mo maximum
                                            </div>

                                            <?php if ($logoInformation !== null): ?>
                                                <div class="darlink-logo-information mt-3">
                                                    <div class="darlink-logo-information-title">
                                                        <i class="bi bi-check-circle-fill text-success me-1"></i>
                                                        Logo actuel
                                                    </div>

                                                    <div class="darlink-logo-information-grid">
                                                        <span>Nom</span>
                                                        <strong><?= htmlspecialchars($logoInformation['name']) ?></strong>

                                                        <span>Format</span>
                                                        <strong><?= htmlspecialchars($logoInformation['format']) ?></strong>

                                                        <span>Dimensions</span>
                                                        <strong>
                                                            <?= (int)$logoInformation['width'] ?>
                                                            ×
                                                            <?= (int)$logoInformation['height'] ?>
                                                            px
                                                        </strong>

                                                        <span>Poids</span>
                                                        <strong>
                                                            <?= number_format(
                                                                (float)$logoInformation['size'] / 1024,
                                                                0,
                                                                ',',
                                                                ' '
                                                            ) ?>
                                                            Ko
                                                        </strong>
                                                    </div>
                                                </div>
                                            <?php endif; ?>
                                        </div>
                                    </div>
                                </div>

                                <div class="col-md-6 darlink-form-group">
                                    <label class="darlink-label">
                                        Couleur principale
                                    </label>

                                    <div class="d-flex gap-2 align-items-center">
                                        <input
                                            type="color"
                                            name="couleur_principale"
                                            id="documentPrimaryColor"
                                            class="form-control form-control-color"
                                            value="<?= document_setting_value(
                                                $settings,
                                                'couleur_principale',
                                                '#123A5A'
                                            ) ?>"
                                        >

                                        <input
                                            type="text"
                                            id="documentPrimaryColorText"
                                            class="darlink-input"
                                            value="<?= document_setting_value(
                                                $settings,
                                                'couleur_principale',
                                                '#123A5A'
                                            ) ?>"
                                            maxlength="7"
                                        >
                                    </div>
                                </div>

                                <div class="col-md-6 darlink-form-group">
                                    <label class="darlink-label">
                                        Couleur secondaire
                                    </label>

                                    <div class="d-flex gap-2 align-items-center">
                                        <input
                                            type="color"
                                            name="couleur_secondaire"
                                            id="documentSecondaryColor"
                                            class="form-control form-control-color"
                                            value="<?= document_setting_value(
                                                $settings,
                                                'couleur_secondaire',
                                                '#6C757D'
                                            ) ?>"
                                        >

                                        <input
                                            type="text"
                                            id="documentSecondaryColorText"
                                            class="darlink-input"
                                            value="<?= document_setting_value(
                                                $settings,
                                                'couleur_secondaire',
                                                '#6C757D'
                                            ) ?>"
                                            maxlength="7"
                                        >
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="darlink-card overflow-hidden">
                        <div class="darlink-admin-block-header">
                            <i class="bi bi-pen me-2"></i>
                            Signature des documents
                        </div>

                        <div class="darlink-card-body">
                            <div class="darlink-form-group mb-0">
                                <label class="darlink-label">
                                    Signature document
                                </label>

                                <input
                                    type="text"
                                    name="signature_document"
                                    id="documentSignature"
                                    class="darlink-input"
                                    value="<?= document_setting_value(
                                        $settings,
                                        'signature_document'
                                    ) ?>"
                                    placeholder="Ex. La Direction"
                                >
                            </div>
                        </div>
                    </div>
                </div>

                <div
                    class="tab-pane fade"
                    id="quotation-pane"
                    role="tabpanel"
                    aria-labelledby="quotation-tab"
                    tabindex="0"
                >
                    <div class="darlink-card overflow-hidden">
                        <div class="darlink-admin-block-header">
                            <i class="bi bi-file-earmark-text me-2"></i>
                            Devis et bons de livraison
                        </div>

                        <div class="darlink-card-body">
                            <div class="row g-3">
                                <div class="col-md-12 darlink-form-group">
                                    <label class="darlink-label">
                                        Conditions du devis
                                    </label>

                                    <textarea
                                        name="conditions_devis"
                                        id="documentConditionsDevis"
                                        class="darlink-textarea"
                                        rows="5"
                                        placeholder="Ex. Offre valable 30 jours."
                                    ><?= document_setting_value(
                                        $settings,
                                        'conditions_devis'
                                    ) ?></textarea>
                                </div>

                                <div class="col-md-12 darlink-form-group mb-0">
                                    <label class="darlink-label">
                                        Mentions du bon de livraison
                                    </label>

                                    <textarea
                                        name="conditions_bl"
                                        id="documentConditionsBl"
                                        class="darlink-textarea"
                                        rows="5"
                                        placeholder="Ex. Marchandises reçues en bon état."
                                    ><?= document_setting_value(
                                        $settings,
                                        'conditions_bl'
                                    ) ?></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div
                    class="tab-pane fade"
                    id="billing-pane"
                    role="tabpanel"
                    aria-labelledby="billing-tab"
                    tabindex="0"
                >
                    <div class="darlink-card overflow-hidden">
                        <div class="darlink-admin-block-header">
                            <i class="bi bi-receipt me-2"></i>
                            Factures et avoirs
                        </div>

                        <div class="darlink-card-body">
                            <div class="row g-3">
                                <div class="col-md-12 darlink-form-group">
                                    <label class="darlink-label">
                                        Conditions de règlement des factures
                                    </label>

                                    <textarea
                                        name="conditions_facture"
                                        id="documentConditionsFacture"
                                        class="darlink-textarea"
                                        rows="4"
                                        placeholder="Ex. Paiement à 30 jours par virement."
                                    ><?= document_setting_value(
                                        $settings,
                                        'conditions_facture'
                                    ) ?></textarea>
                                </div>

                                <div class="col-md-12 darlink-form-group">
                                    <label class="darlink-label">
                                        Mentions des avoirs
                                    </label>

                                    <textarea
                                        name="conditions_avoir"
                                        id="documentConditionsAvoir"
                                        class="darlink-textarea"
                                        rows="4"
                                        placeholder="Ex. Avoir déductible de la prochaine facture."
                                    ><?= document_setting_value(
                                        $settings,
                                        'conditions_avoir'
                                    ) ?></textarea>
                                </div>

                                <div class="col-md-12 darlink-form-group">
                                    <label class="darlink-label">
                                        Pénalités de retard
                                    </label>

                                    <textarea
                                        name="penalites_retard"
                                        id="documentPenalties"
                                        class="darlink-textarea"
                                        rows="4"
                                    ><?= document_setting_value(
                                        $settings,
                                        'penalites_retard'
                                    ) ?></textarea>
                                </div>

                                <div class="col-md-12 darlink-form-group mb-0">
                                    <label class="darlink-label">
                                        Clause de réserve de propriété
                                    </label>

                                    <textarea
                                        name="reserve_propriete"
                                        id="documentOwnership"
                                        class="darlink-textarea"
                                        rows="4"
                                    ><?= document_setting_value(
                                        $settings,
                                        'reserve_propriete'
                                    ) ?></textarea>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div
                    class="tab-pane fade"
                    id="legal-pane"
                    role="tabpanel"
                    aria-labelledby="legal-tab"
                    tabindex="0"
                >
                    <div class="darlink-card overflow-hidden mb-4">
                        <div class="darlink-admin-block-header">
                            <i class="bi bi-shield-check me-2"></i>
                            Mentions légales
                        </div>

                        <div class="darlink-card-body">
                            <div class="darlink-form-group mb-0">
                                <label class="darlink-label">
                                    Mentions légales des documents
                                </label>

                                <textarea
                                    name="mentions_legales"
                                    id="documentLegal"
                                    class="darlink-textarea"
                                    rows="5"
                                ><?= document_setting_value(
                                    $settings,
                                    'mentions_legales'
                                ) ?></textarea>
                            </div>
                        </div>
                    </div>

                    <div class="darlink-card overflow-hidden mb-4">
                        <div class="darlink-admin-block-header">
                            <i class="bi bi-bank me-2"></i>
                            Coordonnées bancaires
                        </div>

                        <div class="darlink-card-body">
                            <div class="row g-3">
                                <div class="col-md-6 darlink-form-group">
                                    <label class="darlink-label">Banque</label>
                                    <input
                                        type="text"
                                        name="banque"
                                        id="documentBank"
                                        class="darlink-input"
                                        value="<?= document_setting_value($settings, 'banque') ?>"
                                    >
                                </div>

                                <div class="col-md-6 darlink-form-group">
                                    <label class="darlink-label">RIB</label>
                                    <input
                                        type="text"
                                        name="rib"
                                        id="documentRib"
                                        class="darlink-input"
                                        value="<?= document_setting_value($settings, 'rib') ?>"
                                    >
                                </div>

                                <div class="col-md-6 darlink-form-group">
                                    <label class="darlink-label">IBAN</label>
                                    <input
                                        type="text"
                                        name="iban"
                                        id="documentIban"
                                        class="darlink-input"
                                        value="<?= document_setting_value($settings, 'iban') ?>"
                                    >
                                </div>

                                <div class="col-md-6 darlink-form-group">
                                    <label class="darlink-label">SWIFT / BIC</label>
                                    <input
                                        type="text"
                                        name="swift"
                                        id="documentSwift"
                                        class="darlink-input"
                                        value="<?= document_setting_value($settings, 'swift') ?>"
                                    >
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="darlink-card overflow-hidden">
                        <div class="darlink-admin-block-header">
                            <i class="bi bi-layout-text-window-reverse me-2"></i>
                            Pied de page
                        </div>

                        <div class="darlink-card-body">
                            <div class="darlink-form-group mb-0">
                                <label class="darlink-label">
                                    Texte du pied de page PDF
                                </label>

                                <textarea
                                    name="pied_de_page"
                                    id="documentFooter"
                                    class="darlink-textarea"
                                    rows="4"
                                ><?= document_setting_value(
                                    $settings,
                                    'pied_de_page'
                                ) ?></textarea>

                                <div class="form-text">
                                    Laissez vide pour utiliser automatiquement les informations de la société.
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-5">
            <div class="darlink-document-preview-wrapper">
                <div class="darlink-card overflow-hidden">
                    <div class="darlink-admin-block-header">
                        <i class="bi bi-eye me-2"></i>
                        Aperçu du document
                    </div>

                    <div class="p-4">
                        <div class="darlink-document-preview" id="documentPreview">
                            <div
                                class="darlink-document-preview-header"
                                id="previewHeader"
                            >
                                <div>
                                    <div
                                        class="darlink-document-preview-logo"
                                        id="previewLogoWrapper"
                                    >
                                        <?php if (!empty($settings['logo_path'])): ?>
                                            <img
                                                src="<?= htmlspecialchars($settings['logo_path']) ?>"
                                                alt="Logo société"
                                                id="previewLogoImage"
                                                class="darlink-document-preview-logo-image"
                                            >
                                        <?php else: ?>
                                            <span id="previewLogoPlaceholder">LOGO</span>
                                        <?php endif; ?>
                                    </div>

                                    <div class="fw-bold fs-5 mt-2">
                                        <?= htmlspecialchars(
                                            $nomCommercial !== ''
                                                ? $nomCommercial
                                                : $raisonSociale
                                        ) ?>
                                    </div>

                                    <div class="small opacity-75">
                                        <?= htmlspecialchars($ville) ?>
                                    </div>
                                </div>

                                <div class="text-end">
                                    <div class="small text-uppercase">
                                        Document
                                    </div>
                                    <div class="fs-4 fw-bold">
                                        FACTURE
                                    </div>
                                    <div class="small">
                                        FA<?= date('Y') ?>-000001
                                    </div>
                                </div>
                            </div>

                            <div class="darlink-document-preview-body">
                                <div class="darlink-document-preview-section">
                                    <div class="darlink-document-preview-label">Client</div>
                                    <div class="fw-semibold">Client exemple</div>
                                    <div class="small text-muted">Adresse du client</div>
                                </div>

                                <div class="darlink-document-preview-lines">
                                    <div class="d-flex justify-content-between">
                                        <span>Produit exemple</span>
                                        <span>100,00 MAD</span>
                                    </div>
                                    <div class="d-flex justify-content-between">
                                        <span>Total HT</span>
                                        <strong>100,00 MAD</strong>
                                    </div>
                                    <div class="d-flex justify-content-between">
                                        <span>TVA</span>
                                        <span>20,00 MAD</span>
                                    </div>
                                    <div class="d-flex justify-content-between fs-6">
                                        <strong>Total TTC</strong>
                                        <strong>120,00 MAD</strong>
                                    </div>
                                </div>

                                <div class="darlink-document-preview-section">
                                    <div class="darlink-document-preview-label">
                                        Conditions de règlement
                                    </div>
                                    <div class="small" id="previewConditions">
                                        <?= nl2br(
                                            document_setting_value(
                                                $settings,
                                                'conditions_facture',
                                                'Non renseignées'
                                            )
                                        ) ?>
                                    </div>
                                </div>

                                <div class="darlink-document-preview-section">
                                    <div class="darlink-document-preview-label">
                                        Mentions
                                    </div>
                                    <div class="small" id="previewLegal">
                                        <?= nl2br(
                                            document_setting_value(
                                                $settings,
                                                'mentions_legales',
                                                'Non renseignées'
                                            )
                                        ) ?>
                                    </div>
                                </div>

                                <div class="darlink-document-preview-section">
                                    <div class="darlink-document-preview-label">
                                        Banque
                                    </div>
                                    <div class="small" id="previewBank">
                                        <?= htmlspecialchars(
                                            trim(
                                                implode(
                                                    ' — ',
                                                    array_filter([
                                                        $settings['banque'] ?? '',
                                                        $settings['rib'] ?? '',
                                                    ])
                                                )
                                            ) ?: 'Non renseignée'
                                        ) ?>
                                    </div>
                                </div>

                                <div
                                    class="darlink-document-preview-footer"
                                    id="previewFooter"
                                >
                                    <?= htmlspecialchars($previewFooterText) ?>
                                </div>

                                <div
                                    class="darlink-document-preview-signature"
                                    id="previewSignature"
                                >
                                    <?= htmlspecialchars(
                                        $settings['signature_document'] ?? ''
                                    ) ?>
                                </div>
                            </div>
                        </div>

                        <div class="alert alert-info mt-3 mb-0 small">
                            <i class="bi bi-info-circle me-1"></i>
                            Cet aperçu représente une facture et se met à jour automatiquement.
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="darlink-form-actions mt-4">
        <a href="index.php?page=parametres" class="btn btn-outline-secondary">
            Annuler
        </a>

        <button type="submit" class="btn darlink-btn-primary">
            <i class="bi bi-check-lg me-1"></i>
            Enregistrer les paramètres
        </button>
    </div>
</form>

<div class="text-center text-muted small mt-4 mb-2">
    Configuration des documents PDF
    <span class="mx-1">•</span>
    Darlink ERP Phoenix 2026.1 LTS
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const logoFile = document.getElementById('documentLogoFile');
    const logoCurrent = document.getElementById('documentLogoCurrent');
    const logoFileName = document.getElementById('documentLogoFileName');
    const previewLogoWrapper = document.getElementById('previewLogoWrapper');

    const primaryColor = document.getElementById('documentPrimaryColor');
    const primaryColorText = document.getElementById('documentPrimaryColorText');
    const secondaryColor = document.getElementById('documentSecondaryColor');
    const secondaryColorText = document.getElementById('documentSecondaryColorText');

    const previewHeader = document.getElementById('previewHeader');
    const previewConditions = document.getElementById('previewConditions');
    const previewLegal = document.getElementById('previewLegal');
    const previewBank = document.getElementById('previewBank');
    const previewFooter = document.getElementById('previewFooter');
    const previewSignature = document.getElementById('previewSignature');

    const conditions = document.getElementById('documentConditionsFacture');
    const legal = document.getElementById('documentLegal');
    const bank = document.getElementById('documentBank');
    const rib = document.getElementById('documentRib');
    const footer = document.getElementById('documentFooter');
    const signature = document.getElementById('documentSignature');

    function isHexColor(value) {
        return /^#[0-9A-F]{6}$/i.test(value);
    }

    function syncPrimaryColor(value) {
        if (!isHexColor(value) || !primaryColor || !primaryColorText || !previewHeader) {
            return;
        }

        primaryColor.value = value;
        primaryColorText.value = value.toUpperCase();
        previewHeader.style.background = value;
    }

    function syncSecondaryColor(value) {
        if (!isHexColor(value) || !secondaryColor || !secondaryColorText) {
            return;
        }

        secondaryColor.value = value;
        secondaryColorText.value = value.toUpperCase();

        document
            .querySelectorAll('.darlink-document-preview-label')
            .forEach(function (element) {
                element.style.color = value;
            });
    }

    function textOrDefault(input, defaultValue) {
        const value = input
            ? String(input.value || '').trim()
            : '';

        return value !== '' ? value : defaultValue;
    }

    function updateBankPreview() {
        const values = [];

        if (bank && bank.value.trim() !== '') {
            values.push(bank.value.trim());
        }

        if (rib && rib.value.trim() !== '') {
            values.push(rib.value.trim());
        }

        if (previewBank) {
            previewBank.textContent =
                values.length > 0
                    ? values.join(' — ')
                    : 'Non renseignée';
        }
    }

    if (primaryColor && primaryColorText && previewHeader) {
        syncPrimaryColor(primaryColor.value);

        primaryColor.addEventListener('input', function () {
            syncPrimaryColor(primaryColor.value);
        });

        primaryColorText.addEventListener('input', function () {
            syncPrimaryColor(primaryColorText.value);
        });
    }

    if (secondaryColor && secondaryColorText) {
        syncSecondaryColor(secondaryColor.value);

        secondaryColor.addEventListener('input', function () {
            syncSecondaryColor(secondaryColor.value);
        });

        secondaryColorText.addEventListener('input', function () {
            syncSecondaryColor(secondaryColorText.value);
        });
    }

    if (conditions && previewConditions) {
        conditions.addEventListener('input', function () {
            previewConditions.textContent =
                textOrDefault(conditions, 'Non renseignées');
        });
    }

    if (legal && previewLegal) {
        legal.addEventListener('input', function () {
            previewLegal.textContent =
                textOrDefault(legal, 'Non renseignées');
        });
    }

    if (bank) {
        bank.addEventListener('input', updateBankPreview);
    }

    if (rib) {
        rib.addEventListener('input', updateBankPreview);
    }

    if (footer && previewFooter) {
        footer.addEventListener('input', function () {
            previewFooter.textContent =
                textOrDefault(
                    footer,
                    'Informations de la société générées automatiquement'
                );
        });
    }

    if (signature && previewSignature) {
        signature.addEventListener('input', function () {
            previewSignature.textContent =
                textOrDefault(signature, '');
        });
    }

    if (logoFile) {
        logoFile.addEventListener('change', function () {
            const file = logoFile.files && logoFile.files[0]
                ? logoFile.files[0]
                : null;

            if (!file) {
                return;
            }

            if (!['image/png', 'image/jpeg'].includes(file.type)) {
                alert('Le logo doit être au format PNG, JPG ou JPEG.');
                logoFile.value = '';
                return;
            }

            if (file.size > 2 * 1024 * 1024) {
                alert('Le logo ne doit pas dépasser 2 Mo.');
                logoFile.value = '';
                return;
            }

            const imageUrl = URL.createObjectURL(file);

            if (logoCurrent) {
                logoCurrent.innerHTML = '';

                const managerImage = document.createElement('img');
                managerImage.src = imageUrl;
                managerImage.alt = 'Nouveau logo';
                managerImage.className = 'darlink-logo-manager-image';
                logoCurrent.appendChild(managerImage);
            }

            if (previewLogoWrapper) {
                previewLogoWrapper.innerHTML = '';

                const previewImage = document.createElement('img');
                previewImage.src = imageUrl;
                previewImage.alt = 'Nouveau logo';
                previewImage.className =
                    'darlink-document-preview-logo-image';
                previewLogoWrapper.appendChild(previewImage);
            }

            if (logoFileName) {
                logoFileName.textContent =
                    file.name +
                    ' — ' +
                    Math.round(file.size / 1024) +
                    ' Ko';
            }
        });
    }
});
</script>
