<?php

include 'config/connexion.php';

$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'] ?? '';
    $footer = $_POST['footer'] ?? '';
    
    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
            $sql = "UPDATE compagnie_table SET 
                    compagnie_name = ?, 
                    adresse = ?, 
                    tel1 = ?, 
                    tel2 = ?, 
                    fax = ?, 
                    whatsapp = ?, 
                    footer = ?
                    LIMIT 1";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sssssss", 
                $compagnie_name, $adresse, $tel1, $tel2, $fax, 
                $whatsapp, $footer);
        } else {
            // Insertion d'un nouvel enregistrement
            $sql = "INSERT INTO compagnie_table 
                    (compagnie_name, adresse, tel1, tel2, fax, whatsapp, footer) 
                    VALUES (?, ?, ?, ?, ?, ?, ?)";
            $stmt = $conn->prepare($sql);
            $stmt->bind_param("sssssss",
                $compagnie_name, $adresse, $tel1, $tel2, $fax, 
                $whatsapp, $footer);
        }
        
        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' => '',
    'footer' => ''
];

$sql = "SELECT compagnie_name, adresse, tel1, tel2, fax, whatsapp, footer 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;
        }
        
        .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;
        }
        
        .facture-section {
            background: linear-gradient(135deg, #36b9cc 0%, #258391 100%);
            color: white;
            border-radius: 0.5rem;
            padding: 2rem;
            margin: 1.5rem 0;
            text-align: center;
        }
    </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 la Compagnie</h1>
                        <ol class="breadcrumb">
                            <li class="breadcrumb-item"><a href="./">Accueil</a></li>
                            <li class="breadcrumb-item active" aria-current="page">Configuration Compagnie</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-building"></i>
                                            Informations de la Compagnie
                                        </h4>
                                        <p class="mb-0 mt-2 opacity-75">
                                            Configurez les informations générales de votre compagnie d'assurance.
                                        </p>
                                    </div>

                                    <form method="POST" action="">
                                        <!-- 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-12">
                                                    <div class="form-group">
                                                        <label for="compagnie_name">Nom de la Compagnie <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>
                                                        <small class="form-text text-muted">Ce nom apparaîtra sur toutes les factures et documents</small>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-12">
                                                    <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>
                                                        <small class="form-text text-muted">Adresse complète avec ville et code postal</small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Coordonnées -->
                                        <div class="form-section">
                                            <h5 class="section-title">
                                                <i class="fas fa-phone"></i>
                                                Coordonnées
                                            </h5>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <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>
                                                        <small class="form-text text-muted">Format: 05XXXXXXXX ou +212XXXXXXXXX</small>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <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']); ?>">
                                                        <small class="form-text text-muted">Optionnel</small>
                                                    </div>
                                                </div>
                                            </div>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <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']); ?>">
                                                        <small class="form-text text-muted">Numéro de fax si disponible</small>
                                                    </div>
                                                </div>
                                                <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">
                                                        <small class="form-text text-muted">Numéro WhatsApp professionnel</small>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>

                                        <!-- Section Factures - Lien vers page dédiée -->
                                        <div class="facture-section">
                                            <h5 class="mb-3">
                                                <i class="fas fa-file-invoice"></i>
                                                Configuration des Factures
                                            </h5>
                                            <p class="mb-3">
                                                Configurez la numérotation avancée de vos factures avec des options automatiques et des séparateurs personnalisés.
                                            </p>
                                            <a href="config_facture.php" class="btn btn-light btn-lg">
                                                <i class="fas fa-cogs"></i> Configurer la Numérotation des Factures
                                            </a>
                                            <p class="mt-3 mb-0" style="opacity: 0.8;">
                                                <small>
                                                    <i class="fas fa-star"></i>
                                                    Options avancées : préfixes/suffixes automatiques, redémarrage annuel, séparateurs personnalisés
                                                </small>
                                            </p>
                                        </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.
                                                </small>
                                            </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>
                                            <a href="config_facture.php" class="btn btn-info btn-lg ml-2">
                                                <i class="fas fa-file-invoice-dollar"></i> Config Factures
                                            </a>
                                            <a href="dashboard.php" class="btn btn-secondary btn-lg ml-2">
                                                <i class="fas fa-home"></i> Accueil
                                            </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>
        // 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;
                }
            });
        });
    </script>
</body>
</html>
