<?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') {
    $facture_ref = $_POST['facture_ref'] ?? '';
    $facture_prefixe = $_POST['facture_prefixe'] ?? '';
    $facture_suffixe = $_POST['facture_suffixe'] ?? '';
    
    // Nouvelles options pour année/mois automatiques
    $use_year_prefix = isset($_POST['use_year_prefix']) ? 1 : 0;
    $use_monthyear_prefix = isset($_POST['use_monthyear_prefix']) ? 1 : 0;
    $use_year_suffix = isset($_POST['use_year_suffix']) ? 1 : 0;
    $use_monthyear_suffix = isset($_POST['use_monthyear_suffix']) ? 1 : 0;
    $reset_number_yearly = isset($_POST['reset_number_yearly']) ? 1 : 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 des paramètres de facturation uniquement
            $sql = "UPDATE compagnie_table SET 
                    facture_ref = ?, 
                    facture_prefixe = ?, 
                    facture_suffixe = ?,
                    use_year_prefix = ?,
                    use_monthyear_prefix = ?,
                    use_year_suffix = ?,
                    use_monthyear_suffix = ?,
                    reset_number_yearly = ?
                    LIMIT 1";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sssiiiii", 
                $facture_ref, $facture_prefixe, $facture_suffixe,
                $use_year_prefix, $use_monthyear_prefix, $use_year_suffix, $use_monthyear_suffix, $reset_number_yearly);
        } else {
            // Insertion d'un nouvel enregistrement avec seulement les données de facturation
            $sql = "INSERT INTO compagnie_table 
                    (facture_ref, facture_prefixe, facture_suffixe, use_year_prefix, use_monthyear_prefix, use_year_suffix, use_monthyear_suffix, reset_number_yearly) 
                    VALUES (?, ?, ?, ?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sssiiiii",
                $facture_ref, $facture_prefixe, $facture_suffixe,
                $use_year_prefix, $use_monthyear_prefix, $use_year_suffix, $use_monthyear_suffix, $reset_number_yearly);
        }
        
        if ($stmt->execute()) {
            $message = "Configuration des factures 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 = [
    '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
];

$sql = "SELECT facture_ref, facture_prefixe, facture_suffixe, use_year_prefix, use_monthyear_prefix, use_year_suffix, use_monthyear_suffix, reset_number_yearly 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'); ?>
    
    <style>
        .form-section {
            background: #f8f9fc;
            border: 1px solid #e3e6f0;
            border-radius: 0.35rem;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .section-title {
            color: #5a5c69;
            border-bottom: 1px solid #e3e6f0;
            padding-bottom: 0.5rem;
            margin-bottom: 1rem;
        }
        
        .preview-section {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 0.5rem;
            padding: 1.5rem;
            margin: 1rem 0;
        }
        
        .config-header {
            background: linear-gradient(135deg, #4e73df 0%, #224abe 100%);
            color: white;
            margin: -1.5rem -1.5rem 1.5rem -1.5rem;
            padding: 1.5rem;
            border-radius: 0.35rem 0.35rem 0 0;
        }
    </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 des Factures</h1>
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="./">Accueil</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Configuration Factures</li>
                        </ol>
                    </div>

                    <!-- Message de feedback -->
                    <?php if (!empty($message)): ?>
                        <div class="alert alert-<?php echo $message_type; ?> alert-dismissible fade show" role="alert">
                            <strong><?php echo $message_type === 'success' ? 'Succès!' : 'Erreur!'; ?></strong> <?php echo $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-body">
                                    <div class="config-header">
                                        <h4 class="mb-0">
                                            <i class="fas fa-file-invoice-dollar"></i>
                                            Configuration Avancée de la Numérotation des Factures
                                        </h4>
                                        <p class="mb-0 mt-2 opacity-75">
                                            Configurez le format et la logique de numérotation de vos factures avec des options automatiques intelligentes.
                                        </p>
                                    </div>

                                    <form method="POST" action="">
                                        <!-- Référence de départ -->
                                        <div class="form-section">
                                            <h5 class="section-title">
                                                <i class="fas fa-play"></i>
                                                Numéro de Départ
                                            </h5>
                                            <div class="row">
                                                <div class="col-md-12">
                                                    <div class="form-group">
                                                        <label for="facture_ref">Référence de Départ</label>
                                                        <input type="text" class="form-control" id="facture_ref" name="facture_ref" 
                                                               value="<?php echo htmlspecialchars($current_data['facture_ref']); ?>" 
                                                               placeholder="Ex: 1">
                                                        <small class="form-text text-muted">
                                                            <i class="fas fa-info-circle"></i>
                                                            Numéro de départ pour la première facture ou lors d'un redémarrage annuel (ex: 1, 100, 255)
                                                        </small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Configuration Préfixe -->
                                        <div class="card mb-3">
                                            <div class="card-header bg-primary text-white">
                                                <h6 class="mb-0"><i class="fas fa-arrow-right"></i> Configuration du Préfixe</h6>
                                            </div>
                                            <div class="card-body">
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="form-group">
                                                            <label for="prefixe_text">Texte du Préfixe</label>
                                                            <input type="text" class="form-control" id="prefixe_text" 
                                                                   placeholder="Ex: FAC, HIBA, 2025" onkeyup="updatePrefixe()">
                                                            <small class="form-text text-muted">Texte qui apparaîtra avant le numéro</small>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="form-group">
                                                            <label for="prefixe_separator">Séparateur du Préfixe</label>
                                                            <select class="form-control" id="prefixe_separator" onchange="updatePrefixe()">
                                                                <option value="">Aucun</option>
                                                                <option value="-">Tiret ( - )</option>
                                                                <option value="/">Slash ( / )</option>
                                                                <option value="_">Underscore ( _ )</option>
                                                                <option value=".">Point ( . )</option>
                                                                <option value=" ">Espace</option>
                                                            </select>
                                                            <small class="form-text text-muted">Séparateur entre le préfixe et le numéro</small>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="form-group">
                                                    <label for="facture_prefixe">Préfixe Final (avec séparateur)</label>
                                                    <input type="text" class="form-control" id="facture_prefixe" name="facture_prefixe" 
                                                           value="<?php echo htmlspecialchars($current_data['facture_prefixe']); ?>" 
                                                           placeholder="Ex: FAC-, HIBA/, 2025-">
                                                    <small class="form-text text-muted">Valeur finale enregistrée (modifiable manuellement)</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Configuration Suffixe -->
                                        <div class="card mb-3">
                                            <div class="card-header bg-info text-white">
                                                <h6 class="mb-0"><i class="fas fa-arrow-left"></i> Configuration du Suffixe</h6>
                                            </div>
                                            <div class="card-body">
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="form-group">
                                                            <label for="suffixe_separator">Séparateur du Suffixe</label>
                                                            <select class="form-control" id="suffixe_separator" onchange="updateSuffixe()">
                                                                <option value="">Aucun</option>
                                                                <option value="-">Tiret ( - )</option>
                                                                <option value="/">Slash ( / )</option>
                                                                <option value="_">Underscore ( _ )</option>
                                                                <option value=".">Point ( . )</option>
                                                                <option value=" ">Espace</option>
                                                            </select>
                                                            <small class="form-text text-muted">Séparateur entre le numéro et le suffixe</small>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="form-group">
                                                            <label for="suffixe_text">Texte du Suffixe</label>
                                                            <input type="text" class="form-control" id="suffixe_text" 
                                                                   placeholder="Ex: HIBA, 2025, ASS" onkeyup="updateSuffixe()">
                                                            <small class="form-text text-muted">Texte qui apparaîtra après le numéro</small>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="form-group">
                                                    <label for="facture_suffixe">Suffixe Final (avec séparateur)</label>
                                                    <input type="text" class="form-control" id="facture_suffixe" name="facture_suffixe" 
                                                           value="<?php echo htmlspecialchars($current_data['facture_suffixe']); ?>" 
                                                           placeholder="Ex: /HIBA, -2025, .ASS">
                                                    <small class="form-text text-muted">Valeur finale enregistrée (modifiable manuellement)</small>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Options Automatiques -->
                                        <div class="card mb-3 border-warning">
                                            <div class="card-header bg-warning text-dark">
                                                <h6 class="mb-0"><i class="fas fa-robot"></i> Options Automatiques (Année/Mois)</h6>
                                            </div>
                                            <div class="card-body">
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <h6 class="text-primary"><i class="fas fa-arrow-right"></i> Préfixe Automatique</h6>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" id="use_year_prefix" name="use_year_prefix" 
                                                                   <?php echo $current_data['use_year_prefix'] ? 'checked' : ''; ?> onchange="toggleAutomaticOptions()">
                                                            <label class="form-check-label" for="use_year_prefix">
                                                                <strong>Utiliser l'année comme préfixe</strong> (ex: 2025-)
                                                            </label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" id="use_monthyear_prefix" name="use_monthyear_prefix" 
                                                                   <?php echo $current_data['use_monthyear_prefix'] ? 'checked' : ''; ?> onchange="toggleAutomaticOptions()">
                                                            <label class="form-check-label" for="use_monthyear_prefix">
                                                                <strong>Utiliser mois/année comme préfixe</strong> (ex: 0725-)
                                                            </label>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <h6 class="text-info"><i class="fas fa-arrow-left"></i> Suffixe Automatique</h6>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" id="use_year_suffix" name="use_year_suffix" 
                                                                   <?php echo $current_data['use_year_suffix'] ? 'checked' : ''; ?> onchange="toggleAutomaticOptions()">
                                                            <label class="form-check-label" for="use_year_suffix">
                                                                <strong>Utiliser l'année comme suffixe</strong> (ex: /2025)
                                                            </label>
                                                        </div>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" id="use_monthyear_suffix" name="use_monthyear_suffix" 
                                                                   <?php echo $current_data['use_monthyear_suffix'] ? 'checked' : ''; ?> onchange="toggleAutomaticOptions()">
                                                            <label class="form-check-label" for="use_monthyear_suffix">
                                                                <strong>Utiliser mois/année comme suffixe</strong> (ex: /0725)
                                                            </label>
                                                        </div>
                                                    </div>
                                                </div>
                                                <hr>
                                                <div class="row">
                                                    <div class="col-md-12">
                                                        <h6 class="text-success"><i class="fas fa-redo"></i> Numérotation</h6>
                                                        <div class="form-check">
                                                            <input class="form-check-input" type="checkbox" id="reset_number_yearly" name="reset_number_yearly" 
                                                                   <?php echo $current_data['reset_number_yearly'] ? 'checked' : ''; ?>>
                                                            <label class="form-check-label" for="reset_number_yearly">
                                                                <strong>Redémarrer la numérotation à 1 chaque année</strong>
                                                            </label>
                                                            <small class="form-text text-muted">Si activé, les numéros recommencent à 1 en janvier de chaque année.</small>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="alert alert-warning mt-3">
                                                    <i class="fas fa-exclamation-triangle"></i>
                                                    <strong>Important :</strong> Les options automatiques remplacent les préfixes/suffixes manuels configurés ci-dessus.
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Aperçu de la numérotation -->
                                        <div class="preview-section">
                                            <h5 class="mb-3">
                                                <i class="fas fa-eye"></i>
                                                Aperçu de la Numérotation
                                            </h5>
                                            <div class="text-center">
                                                <div class="badge badge-light badge-lg p-3" style="font-size: 1.2rem; font-family: monospace;">
                                                    <span id="preview_prefixe" class="text-primary"><?php echo htmlspecialchars($current_data['facture_prefixe']); ?></span><!--
                                                    --><span class="text-warning font-weight-bold">001</span><!--
                                                    --><span id="preview_suffixe" class="text-info"><?php echo htmlspecialchars($current_data['facture_suffixe']); ?></span>
                                                </div>
                                                <p class="mt-3 mb-0 opacity-75">
                                                    Exemples des prochaines factures : 
                                                    <span id="example_numbers" class="font-weight-bold"></span>
                                                </p>
                                            </div>
                                        </div>

                                        <!-- Boutons d'action -->
                                        <div class="text-center mt-4">
                                            <button type="submit" class="btn btn-primary btn-lg">
                                                <i class="fas fa-save"></i> Enregistrer la Configuration
                                            </button>
                                        </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>
        // Auto-dismiss alerts after 5 seconds
        setTimeout(function() {
            $('.alert').fadeOut('slow');
        }, 5000);

        // Fonctions pour gérer les séparateurs et l'aperçu de numérotation
        function updatePrefixe() {
            const text = document.getElementById('prefixe_text').value;
            const separator = document.getElementById('prefixe_separator').value;
            const finalPrefixe = text + separator;
            
            document.getElementById('facture_prefixe').value = finalPrefixe;
            updatePreview();
        }

        function updateSuffixe() {
            const separator = document.getElementById('suffixe_separator').value;
            const text = document.getElementById('suffixe_text').value;
            const finalSuffixe = separator + text;
            
            document.getElementById('facture_suffixe').value = finalSuffixe;
            updatePreview();
        }

        function updatePreview() {
            // Vérifier si les options automatiques sont activées
            const useYearPrefix = document.getElementById('use_year_prefix').checked;
            const useMonthYearPrefix = document.getElementById('use_monthyear_prefix').checked;
            const useYearSuffix = document.getElementById('use_year_suffix').checked;
            const useMonthYearSuffix = document.getElementById('use_monthyear_suffix').checked;
            
            let prefixe = '';
            let suffixe = '';
            
            // Calculer le préfixe
            if (useYearPrefix) {
                prefixe = new Date().getFullYear() + '-';
            } else if (useMonthYearPrefix) {
                const now = new Date();
                const month = String(now.getMonth() + 1).padStart(2, '0');
                const year = String(now.getFullYear()).slice(-2);
                prefixe = month + year + '-';
            } else {
                prefixe = document.getElementById('facture_prefixe').value;
            }
            
            // Calculer le suffixe
            if (useYearSuffix) {
                suffixe = '/' + new Date().getFullYear();
            } else if (useMonthYearSuffix) {
                const now = new Date();
                const month = String(now.getMonth() + 1).padStart(2, '0');
                const year = String(now.getFullYear()).slice(-2);
                suffixe = '/' + month + year;
            } else {
                suffixe = document.getElementById('facture_suffixe').value;
            }
            
            document.getElementById('preview_prefixe').textContent = prefixe;
            document.getElementById('preview_suffixe').textContent = suffixe;
            
            // Générer des exemples
            const examples = [];
            for (let i = 1; i <= 3; i++) {
                examples.push(prefixe + String(i).padStart(3, '0') + suffixe);
            }
            document.getElementById('example_numbers').textContent = examples.join(', ') + '...';
        }
        
        // Fonction pour gérer l'activation/désactivation des options automatiques
        function toggleAutomaticOptions() {
            // Désactiver les options mutuellement exclusives pour le préfixe
            if (document.getElementById('use_year_prefix').checked) {
                document.getElementById('use_monthyear_prefix').checked = false;
            }
            if (document.getElementById('use_monthyear_prefix').checked) {
                document.getElementById('use_year_prefix').checked = false;
            }
            
            // Désactiver les options mutuellement exclusives pour le suffixe
            if (document.getElementById('use_year_suffix').checked) {
                document.getElementById('use_monthyear_suffix').checked = false;
            }
            if (document.getElementById('use_monthyear_suffix').checked) {
                document.getElementById('use_year_suffix').checked = false;
            }
            
            // Activer/désactiver les champs manuels
            const hasAutomaticPrefix = document.getElementById('use_year_prefix').checked || 
                                     document.getElementById('use_monthyear_prefix').checked;
            const hasAutomaticSuffix = document.getElementById('use_year_suffix').checked || 
                                     document.getElementById('use_monthyear_suffix').checked;
            
            // Griser les champs manuels si automatique activé
            const prefixeFields = ['prefixe_text', 'prefixe_separator', 'facture_prefixe'];
            const suffixeFields = ['suffixe_separator', 'suffixe_text', 'facture_suffixe'];
            
            prefixeFields.forEach(fieldId => {
                const field = document.getElementById(fieldId);
                if (field) {
                    field.disabled = hasAutomaticPrefix;
                    field.style.opacity = hasAutomaticPrefix ? '0.5' : '1';
                }
            });
            
            suffixeFields.forEach(fieldId => {
                const field = document.getElementById(fieldId);
                if (field) {
                    field.disabled = hasAutomaticSuffix;
                    field.style.opacity = hasAutomaticSuffix ? '0.5' : '1';
                }
            });
            
            updatePreview();
        }

        // Initialiser les champs séparateurs selon les valeurs actuelles
        function initializeSeparators() {
            const currentPrefixe = document.getElementById('facture_prefixe').value;
            const currentSuffixe = document.getElementById('facture_suffixe').value;
            
            // Analyser le préfixe actuel pour déterminer le texte et le séparateur
            if (currentPrefixe) {
                const separators = ['-', '/', '_', '.', ' '];
                let foundSeparator = '';
                let prefixeText = currentPrefixe;
                
                for (let sep of separators) {
                    if (currentPrefixe.endsWith(sep)) {
                        foundSeparator = sep;
                        prefixeText = currentPrefixe.slice(0, -1);
                        break;
                    }
                }
                
                document.getElementById('prefixe_text').value = prefixeText;
                document.getElementById('prefixe_separator').value = foundSeparator;
            }
            
            // Analyser le suffixe actuel pour déterminer le séparateur et le texte
            if (currentSuffixe) {
                const separators = ['-', '/', '_', '.', ' '];
                let foundSeparator = '';
                let suffixeText = currentSuffixe;
                
                for (let sep of separators) {
                    if (currentSuffixe.startsWith(sep)) {
                        foundSeparator = sep;
                        suffixeText = currentSuffixe.slice(1);
                        break;
                    }
                }
                
                document.getElementById('suffixe_separator').value = foundSeparator;
                document.getElementById('suffixe_text').value = suffixeText;
            }
            
            updatePreview();
        }

        // Écouter les changements manuels sur les champs finaux
        document.getElementById('facture_prefixe').addEventListener('input', updatePreview);
        document.getElementById('facture_suffixe').addEventListener('input', updatePreview);

        // Initialiser au chargement de la page
        document.addEventListener('DOMContentLoaded', function() {
            initializeSeparators();
            toggleAutomaticOptions(); // Initialiser l'état des options automatiques
        });
    </script>
</body>
</html>
