<?php

include 'config/connexion.php';
include 'includes/simple_log.php';
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

$message = '';
$message_type = '';

// Traitement du formulaire
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $compagnie_name = $_POST['compagnie_name'] ?? '';
    $adresse = $_POST['adresse'] ?? '';
    $tel1 = $_POST['tel1'] ?? '';
    $tel2 = $_POST['tel2'] ?? '';
    $fax = $_POST['fax'] ?? '';
    $whatsapp = $_POST['whatsapp'] ?? '';    $mail_1 = $_POST['mail_1'] ?? '';
    $mail_2 = $_POST['mail_2'] ?? '';
    $mail_3 = $_POST['mail_3'] ?? '';
    $footer = $_POST['footer'] ?? '';
    $logo_format = $_POST['logo_format'] ?? 'wide';
    
    // Gestion du logo
    $logo_path = '';
    if (isset($_POST['cropped_logo']) && !empty($_POST['cropped_logo'])) {
        // Récupérer la référence de la compagnie pour créer le dossier
        $ref_sql = "SELECT compagnie_ref FROM compagnie_table LIMIT 1";
        $ref_result = $conn->query($ref_sql);
        $compagnie_ref = 'default';
        if ($ref_result && $row = $ref_result->fetch_assoc()) {
            $compagnie_ref = !empty($row['compagnie_ref']) ? $row['compagnie_ref'] : 'default';
        }
        
        // Créer le dossier s'il n'existe pas
        $logo_dir = "data/" . $compagnie_ref;
        if (!file_exists($logo_dir)) {
            mkdir($logo_dir, 0755, true);
        }
        
        // Décoder l'image base64 et sauvegarder
        $cropped_data = $_POST['cropped_logo'];
        $cropped_data = str_replace('data:image/png;base64,', '', $cropped_data);
        $cropped_data = str_replace(' ', '+', $cropped_data);
        $logo_binary = base64_decode($cropped_data);
        
        $logo_path = $logo_dir . "/logo.png";
        if (file_put_contents($logo_path, $logo_binary)) {
            $message = "Logo mis à jour avec succès !";
            $message_type = "success";
        } else {
            $message = "Erreur lors de la sauvegarde du logo.";
            $message_type = "danger";
        }
    }
    
    // Les paramètres de factures sont maintenant gérés dans config_facture.php
    $facture_ref = '';
    $facture_prefixe = '';
    $facture_suffixe = '';
    $use_year_prefix = 0;
    $use_monthyear_prefix = 0;
    $use_year_suffix = 0;
    $use_monthyear_suffix = 0;
    $reset_number_yearly = 0;
    
    try {
        // Vérifier si un enregistrement existe déjà
        $check_sql = "SELECT id FROM compagnie_table LIMIT 1";
        $result = $conn->query($check_sql);        if ($result && $result->num_rows > 0) {
            // Mise à jour seulement des informations de la compagnie (pas les factures)
            $sql = "UPDATE compagnie_table SET 
                    compagnie_name = ?, 
                    adresse = ?, 
                    tel1 = ?, 
                    tel2 = ?, 
                    fax = ?, 
                    whatsapp = ?, 
                    mail_1 = ?,
                    mail_2 = ?,
                    mail_3 = ?,
                    footer = ?," . 
                    "logo_format = ?" .
                    (!empty($logo_path) ? ", logo = ?" : "") . "
                    LIMIT 1";
            $stmt = $conn->prepare($sql);
            if (!empty($logo_path)) {
                $stmt->bind_param("ssssssssssss", 
                    $compagnie_name, $adresse, $tel1, $tel2, $fax, 
                    $whatsapp, $mail_1, $mail_2, $mail_3, $footer, $logo_format, $logo_path);
            } else {
                $stmt->bind_param("sssssssssss", 
                    $compagnie_name, $adresse, $tel1, $tel2, $fax, 
                    $whatsapp, $mail_1, $mail_2, $mail_3, $footer, $logo_format);
            }} else {            // Insertion d'un nouvel enregistrement (seulement infos compagnie)
            $sql = "INSERT INTO compagnie_table 
                    (compagnie_name, adresse, tel1, tel2, fax, whatsapp, mail_1, mail_2, mail_3, footer, logo_format" . 
                    (!empty($logo_path) ? ", logo" : "") . ") 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?" . 
                    (!empty($logo_path) ? ", ?" : "") . ")";
            $stmt = $conn->prepare($sql);
            if (!empty($logo_path)) {
                $stmt->bind_param("ssssssssssss",
                    $compagnie_name, $adresse, $tel1, $tel2, $fax, 
                    $whatsapp, $mail_1, $mail_2, $mail_3, $footer, $logo_format, $logo_path);
            } else {
                $stmt->bind_param("sssssssssss",
                    $compagnie_name, $adresse, $tel1, $tel2, $fax, 
                    $whatsapp, $mail_1, $mail_2, $mail_3, $footer, $logo_format);
            }
        }        if ($stmt->execute()) {
            $message = "Configuration de la compagnie mise à jour avec succès !";
            $message_type = "success";
        } else {
            $message = "Erreur lors de la mise à jour : " . $conn->error;
            $message_type = "danger";
        }
        $stmt->close();
        
    } catch (Exception $e) {
        $message = "Erreur : " . $e->getMessage();
        $message_type = "danger";
    }
}

// Récupération des données existantes
$current_data = [
    'compagnie_name' => '',
    'adresse' => '',
    'tel1' => '',
    'tel2' => '',
    'fax' => '',
    'whatsapp' => '',
    'mail_1' => '',
    'mail_2' => '',
    'mail_3' => '',
    'footer' => '',
    'logo' => '',
    'logo_format' => 'wide'
];

$sql = "SELECT compagnie_name, adresse, tel1, tel2, fax, whatsapp, mail_1, mail_2, mail_3, footer, logo, logo_format FROM compagnie_table LIMIT 1";
$result = $conn->query($sql);
if ($result && $row = $result->fetch_assoc()) {
    $current_data = array_merge($current_data, $row);
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <?php include('includes/head.php'); ?>
    
    <!-- Cropper.js pour le recadrage des images -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.12/cropper.min.js"></script>
    
    <style>
        .form-section {
            background: #f8f9fc;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            border-left: 4px solid #4e73df;
        }
        .section-title {
            color: #5a5c69;
            font-weight: 600;
            margin-bottom: 15px;
            display: flex;
            align-items: center;
        }
        .section-title i {
            margin-right: 10px;
            color: #4e73df;
        }
        .form-control:focus {
            border-color: #4e73df;
            box-shadow: 0 0 0 0.2rem rgba(78, 115, 223, 0.25);
        }
        .btn-primary {
            background-color: #4e73df;
            border-color: #4e73df;
        }        .btn-primary:hover {
            background-color: #2e59d9;
            border-color: #2e59d9;
        }
        .form-control {
            word-wrap: break-word;
            white-space: pre-wrap;
        }        #footer {
            resize: vertical;
            min-height: 120px;
            white-space: pre-wrap;
            word-wrap: break-word;
            overflow-wrap: break-word;
        }
        
        /* Styles pour la gestion du logo */
        .current-logo-container {
            padding: 10px;
            background: #f8f9fa;
            border-radius: 5px;
            text-align: center;
        }
        .current-logo {
            max-width: 200px !important;
            max-height: 100px !important;
            object-fit: contain;
        }
        .logo-preview-wrapper {
            border: 2px dashed #ddd;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            background: #f8f9fa;
        }
        #logo_crop_container {
            position: relative;
            display: inline-block;
            margin: 10px auto;
        }
        .final-preview-container {
            text-align: center;
            padding: 15px;
            background: #f8f9fa;
            border-radius: 5px;
            margin-top: 10px;
        }
        #logo_final_image {
            max-width: 250px;
            max-height: 150px;
            object-fit: contain;
        }
        .cropper-container {
            max-width: 100% !important;
        }
        .form-check-inline {
            margin-right: 1rem;
        }
        .custom-file-label::after {
            content: "Parcourir";
        }
    </style>
</head>

<body id="page-top">
    <div id="wrapper">
        <!-- Sidebar -->
        <?php include('includes/sidebar.php'); ?>
        <!-- Sidebar -->
        
        <div id="content-wrapper" class="d-flex flex-column">
            <div id="content">
                <!-- TopBar -->
                <?php include('includes/topbar.php'); ?>
                <!-- Topbar -->
                
                <!-- Container Fluid-->
                <div class="container-fluid" id="container-wrapper">
                    <div class="d-sm-flex align-items-center justify-content-between mb-4">
                        <h1 class="h3 mb-0 text-gray-800">Configuration de l'Agence</h1>
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="dashboard.php">Accueil</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Configuration Agence</li>
                        </ol>
                    </div>

                    <!-- Message de feedback -->
                    <?php if (!empty($message)): ?>
                        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                            <i class="fas fa-<?php echo $message_type === 'success' ? 'check-circle' : 'exclamation-triangle'; ?>"></i>
                            <?php echo htmlspecialchars($message); ?>
                            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                                <span aria-hidden="true">&times;</span>
                            </button>
                        </div>
                    <?php endif; ?>

                    <div class="row">
                        <div class="col-lg-12">
                            <div class="card mb-4">
                                <div class="card-header py-3 d-flex flex-row align-items-center justify-content-between">
                                    <h6 class="m-0 font-weight-bold text-primary">
                                        <i class="fas fa-building"></i> Paramètres de l'Agence
                                    </h6>
                                </div>
                                <div class="card-body">
                                    <form method="POST" action="">
                                        
                                        <!-- Section Informations Générales -->
                                        <div class="form-section">
                                            <h5 class="section-title">
                                                <i class="fas fa-info-circle"></i>
                                                Informations Générales
                                            </h5>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="compagnie_name">Nom de l'Agence <span class="text-danger">*</span></label>
                                                        <input type="text" class="form-control" id="compagnie_name" name="compagnie_name" 
                                                               value="<?php echo htmlspecialchars($current_data['compagnie_name']); ?>" required>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="adresse">Adresse Complète <span class="text-danger">*</span></label>
                                                        <textarea class="form-control" id="adresse" name="adresse" rows="3" required><?php echo htmlspecialchars($current_data['adresse']); ?></textarea>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Section Contact -->
                                        <div class="form-section">
                                            <h5 class="section-title">
                                                <i class="fas fa-phone"></i>
                                                Informations de Contact
                                            </h5>
                                            <div class="row">
                                                <div class="col-md-4">
                                                    <div class="form-group">
                                                        <label for="tel1">Téléphone Principal <span class="text-danger">*</span></label>
                                                        <input type="tel" class="form-control" id="tel1" name="tel1" 
                                                               value="<?php echo htmlspecialchars($current_data['tel1']); ?>" required>
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="form-group">
                                                        <label for="tel2">Téléphone Secondaire</label>
                                                        <input type="tel" class="form-control" id="tel2" name="tel2" 
                                                               value="<?php echo htmlspecialchars($current_data['tel2']); ?>">
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="form-group">
                                                        <label for="fax">Fax</label>
                                                        <input type="tel" class="form-control" id="fax" name="fax" 
                                                               value="<?php echo htmlspecialchars($current_data['fax']); ?>">
                                                    </div>
                                                </div>
                                            </div>                                            <div class="row">
                                                <div class="col-md-6">
                                                    <div class="form-group">
                                                        <label for="whatsapp">WhatsApp</label>
                                                        <input type="tel" class="form-control" id="whatsapp" name="whatsapp" 
                                                               value="<?php echo htmlspecialchars($current_data['whatsapp']); ?>" 
                                                               placeholder="+212600123456">
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Section Emails -->
                                        <div class="form-section">
                                            <h5 class="section-title">
                                                <i class="fas fa-envelope"></i>
                                                Adresses Email
                                            </h5>
                                            <div class="row">
                                                <div class="col-md-4">
                                                    <div class="form-group">
                                                        <label for="mail_1">Email Principal <span class="text-danger">*</span></label>
                                                        <input type="email" class="form-control" id="mail_1" name="mail_1" 
                                                               value="<?php echo htmlspecialchars($current_data['mail_1']); ?>" 
                                                               placeholder="exemple@domaine.com">
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="form-group">
                                                        <label for="mail_2">Email Secondaire</label>
                                                        <input type="email" class="form-control" id="mail_2" name="mail_2" 
                                                               value="<?php echo htmlspecialchars($current_data['mail_2']); ?>" 
                                                               placeholder="contact@domaine.com">
                                                    </div>
                                                </div>
                                                <div class="col-md-4">
                                                    <div class="form-group">
                                                        <label for="mail_3">Email Administratif</label>
                                                        <input type="email" class="form-control" id="mail_3" name="mail_3" 
                                                               value="<?php echo htmlspecialchars($current_data['mail_3']); ?>" 
                                                               placeholder="admin@domaine.com">
                                                    </div>
                                                </div>
                                            </div>
                                            <small class="form-text text-muted">
                                                <i class="fas fa-info-circle text-info"></i>
                                                L'email principal est obligatoire et apparaîtra sur les factures. Les emails secondaires sont optionnels.
                                            </small>
                                        </div>                                        <!-- Section Logo -->
                                        <div class="form-section">
                                            <h5 class="section-title">
                                                <i class="fas fa-image"></i>
                                                Logo de l'Agence
                                            </h5>
                                            
                                            <!-- Affichage du logo actuel -->
                                            <?php if (!empty($current_data['logo']) && file_exists($current_data['logo'])): ?>
                                            <div class="mb-3">
                                                <label class="form-label">Logo actuel :</label>
                                                <div class="current-logo-container">
                                                    <img src="<?php echo htmlspecialchars($current_data['logo']); ?>" 
                                                         alt="Logo actuel" class="current-logo" 
                                                         style="max-width: 200px; max-height: 100px; border: 1px solid #ddd; border-radius: 5px;">
                                                </div>
                                            </div>
                                            <?php endif; ?>
                                              <!-- Format du logo -->
                                            <div class="form-group">
                                                <label for="logo_format">Format du logo :</label>
                                                <div class="form-check-inline">
                                                    <input class="form-check-input" type="radio" name="logo_format" id="logo_format_wide" value="wide" 
                                                           <?php echo ($current_data['logo_format'] === 'wide' || empty($current_data['logo_format'])) ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="logo_format_wide">
                                                        <i class="fas fa-arrows-alt-h"></i> Large (recommandé)
                                                    </label>
                                                </div>
                                                <div class="form-check-inline ml-3">
                                                    <input class="form-check-input" type="radio" name="logo_format" id="logo_format_square" value="square"
                                                           <?php echo ($current_data['logo_format'] === 'square') ? 'checked' : ''; ?>>
                                                    <label class="form-check-label" for="logo_format_square">
                                                        <i class="fas fa-square"></i> Carré
                                                    </label>
                                                </div>
                                            </div>
                                            
                                            <!-- Upload du logo -->
                                            <div class="form-group">
                                                <label for="logo_file">Nouveau logo :</label>
                                                <div class="custom-file">
                                                    <input type="file" class="custom-file-input" id="logo_file" 
                                                           accept="image/jpeg,image/jpg,image/png,image/gif" onchange="handleLogoUpload(event)">
                                                    <label class="custom-file-label" for="logo_file">Choisir un fichier...</label>
                                                </div>
                                                <small class="form-text text-muted">
                                                    <i class="fas fa-info-circle text-info"></i>
                                                    Formats acceptés : PNG, JPG, JPEG, GIF. Taille recommandée : 400x200px pour le format large, 200x200px pour le format carré.
                                                </small>
                                            </div>
                                            
                                            <!-- Zone d'aperçu et de recadrage -->
                                            <div id="logo_preview_container" style="display: none;">
                                                <div class="form-group">
                                                    <label>Aperçu et recadrage :</label>
                                                    <div class="logo-preview-wrapper">
                                                        <div id="logo_crop_container" style="max-width: 100%; overflow: hidden;">
                                                            <img id="logo_preview" style="max-width: 100%;">
                                                        </div>
                                                    </div>
                                                    <div class="mt-2">
                                                        <button type="button" class="btn btn-sm btn-info" onclick="applyLogoCrop()">
                                                            <i class="fas fa-crop"></i> Appliquer le recadrage
                                                        </button>
                                                        <button type="button" class="btn btn-sm btn-secondary" onclick="resetLogoCrop()">
                                                            <i class="fas fa-undo"></i> Réinitialiser
                                                        </button>
                                                    </div>
                                                </div>
                                                
                                                <!-- Aperçu final -->
                                                <div id="logo_final_preview" style="display: none;">
                                                    <label>Aperçu final :</label>
                                                    <div class="final-preview-container">
                                                        <img id="logo_final_image" style="border: 1px solid #ddd; border-radius: 5px;">
                                                    </div>
                                                </div>
                                            </div>
                                              <!-- Input caché pour le logo recadré -->
                                            <input type="hidden" id="cropped_logo" name="cropped_logo">
                                        </div>
                                       
                                        <!-- Section Footer -->
                                        <div class="form-section">
                                            <h5 class="section-title">
                                                <i class="fas fa-file-contract"></i>
                                                Informations Légales (Footer)
                                            </h5>                                            <div class="form-group">
                                                <label for="footer">Texte du Footer <span class="text-danger">*</span></label>
                                                <textarea class="form-control" id="footer" name="footer" rows="6" required 
                                                          wrap="soft" style="white-space: pre-wrap; word-wrap: break-word;"
                                                          placeholder="Intermédiaire d'assurances régi par la loi 17-99.&#10;Portant code des assurances. Agrément n°C2653549002011450 du 29 Décembre 2010.&#10;RC: 44773 - IF: 40247708 - ICE: 000222791000001"><?php echo htmlspecialchars($current_data['footer']); ?></textarea>
                                                <small class="form-text text-muted">
                                                    <i class="fas fa-lightbulb text-warning"></i>
                                                    Utilisez des retours à la ligne pour séparer les informations. Ce texte apparaîtra en bas des factures et emails. Le retour à la ligne automatique est activé pour éviter la perte de texte.
                                                </small>
                                            </div>
                                        </div>

                                        <!-- Boutons d'action -->
                                        <div class="text-center">
                                            <button type="submit" class="btn btn-primary btn-lg">
                                                <i class="fas fa-save"></i> Enregistrer la Configuration
                                            </button>
                                            <a href="dashboard.php" class="btn btn-secondary btn-lg ml-2">
                                                <i class="fas fa-times"></i> Annuler
                                            </a>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                </div>
                <!-- Container Fluid-->
            </div>
            <!-- Footer -->
            <?php include('includes/footer.php'); ?>
            <!-- Footer -->
        </div>
    </div>

    <!-- Scroll to top -->
    <a class="scroll-to-top rounded" href="#page-top">
        <i class="fas fa-angle-up"></i>
    </a>

    <!-- Bootstrap core JavaScript-->
    <script src="vendor/jquery/jquery.min.js"></script>
    <script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
    <script src="vendor/jquery-easing/jquery.easing.min.js"></script>
    <script src="js/ruang-admin.min.js"></script>    <script>
        let cropper = null;
        let currentLogoFormat = 'wide';
        
        // Auto-dismiss alerts after 5 seconds
        setTimeout(function() {
            $('.alert').fadeOut('slow');
        }, 5000);

        // Format phone numbers as user types
        document.querySelectorAll('input[type="tel"]').forEach(function(input) {
            input.addEventListener('input', function(e) {
                // Basic phone number formatting (you can customize this)
                let value = e.target.value.replace(/\D/g, '');
                if (value.startsWith('212')) {
                    value = '+' + value;
                } else if (value.startsWith('0')) {
                    value = '+212' + value.substring(1);
                }
                // Don't update if user is manually formatting
                if (e.target.value !== value && e.target.value.length < value.length) {
                    e.target.value = value;
                }
            });
        });
        
        // Gestion du format du logo
        document.querySelectorAll('input[name="logo_format"]').forEach(function(radio) {
            radio.addEventListener('change', function() {
                currentLogoFormat = this.value;
                if (cropper) {
                    updateCropperAspectRatio();
                }
            });
        });
        
        // Gestion de l'upload du logo
        function handleLogoUpload(event) {
            const file = event.target.files[0];
            if (!file) return;
            
            // Vérifier le type de fichier
            if (!file.type.match(/^image\/(jpeg|jpg|png|gif)$/)) {
                alert('Veuillez sélectionner une image (PNG, JPG, JPEG, GIF)');
                event.target.value = '';
                return;
            }
            
            // Vérifier la taille du fichier (max 5MB)
            if (file.size > 5 * 1024 * 1024) {
                alert('Le fichier est trop volumineux. Taille maximum : 5MB');
                event.target.value = '';
                return;
            }
            
            // Mettre à jour le label du fichier
            const fileName = file.name;
            const label = event.target.nextElementSibling;
            label.textContent = fileName;
            
            // Lire et afficher l'image
            const reader = new FileReader();
            reader.onload = function(e) {
                showImagePreview(e.target.result);
            };
            reader.readAsDataURL(file);
        }
        
        // Afficher l'aperçu de l'image
        function showImagePreview(imageSrc) {
            const container = document.getElementById('logo_preview_container');
            const preview = document.getElementById('logo_preview');
            
            preview.src = imageSrc;
            container.style.display = 'block';
            
            // Initialiser Cropper.js
            if (cropper) {
                cropper.destroy();
            }
            
            setTimeout(() => {
                initializeCropper();
            }, 100);
        }
        
        // Initialiser Cropper.js
        function initializeCropper() {
            const preview = document.getElementById('logo_preview');
            const aspectRatio = currentLogoFormat === 'wide' ? 2 : 1; // 2:1 pour large, 1:1 pour carré
            
            cropper = new Cropper(preview, {
                aspectRatio: aspectRatio,
                viewMode: 1,
                dragMode: 'move',
                autoCropArea: 0.8,
                restore: false,
                guides: true,
                center: true,
                highlight: false,
                cropBoxMovable: true,
                cropBoxResizable: true,
                toggleDragModeOnDblclick: false,
                minContainerWidth: 300,
                minContainerHeight: 200
            });
        }
        
        // Mettre à jour le ratio du cropper
        function updateCropperAspectRatio() {
            if (!cropper) return;
            
            const aspectRatio = currentLogoFormat === 'wide' ? 2 : 1;
            cropper.setAspectRatio(aspectRatio);
        }
        
        // Appliquer le recadrage
        function applyLogoCrop() {
            if (!cropper) {
                alert('Aucune image à recadrer');
                return;
            }
            
            // Obtenir les dimensions cibles
            const targetWidth = currentLogoFormat === 'wide' ? 400 : 200;
            const targetHeight = currentLogoFormat === 'wide' ? 200 : 200;
            
            // Recadrer l'image
            const canvas = cropper.getCroppedCanvas({
                width: targetWidth,
                height: targetHeight,
                imageSmoothingEnabled: true,
                imageSmoothingQuality: 'high'
            });
            
            if (canvas) {
                const croppedDataURL = canvas.toDataURL('image/png', 0.9);
                
                // Afficher l'aperçu final
                const finalPreview = document.getElementById('logo_final_preview');
                const finalImage = document.getElementById('logo_final_image');
                finalImage.src = croppedDataURL;
                finalPreview.style.display = 'block';
                
                // Stocker les données recadrées
                document.getElementById('cropped_logo').value = croppedDataURL;
                
                // Afficher un message de succès
                showMessage('Image recadrée avec succès! Cliquez sur "Enregistrer" pour sauvegarder.', 'success');
            }
        }
        
        // Réinitialiser le recadrage
        function resetLogoCrop() {
            if (cropper) {
                cropper.reset();
                document.getElementById('logo_final_preview').style.display = 'none';
                document.getElementById('cropped_logo').value = '';
            }
        }
        
        // Afficher un message temporaire
        function showMessage(message, type) {
            // Supprimer les anciens messages temporaires
            const existingMessages = document.querySelectorAll('.temp-message');
            existingMessages.forEach(msg => msg.remove());
            
            // Créer le nouveau message
            const messageDiv = document.createElement('div');
            messageDiv.className = `alert alert-${type} alert-dismissible fade show temp-message`;
            messageDiv.innerHTML = `
                <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-triangle'}"></i>
                ${message}
                <button type="button" class="close" data-dismiss="alert">
                    <span>&times;</span>
                </button>
            `;
            
            // Insérer le message au début du container
            const container = document.querySelector('.container-fluid');
            container.insertBefore(messageDiv, container.firstChild);
            
            // Auto-dismiss après 3 secondes
            setTimeout(() => {
                $(messageDiv).fadeOut('slow', function() {
                    $(this).remove();
                });
            }, 3000);
        }
        
        // Validation avant soumission
        document.querySelector('form').addEventListener('submit', function(e) {
            const logoFile = document.getElementById('logo_file').files[0];
            const croppedLogo = document.getElementById('cropped_logo').value;
            
            if (logoFile && !croppedLogo) {
                e.preventDefault();
                alert('Veuillez recadrer l\'image avant de sauvegarder, ou ne pas sélectionner de fichier.');
                return false;
            }
        });
    </script>
</body>
</html>
