<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
/**
 * Gestion des Pages Légales - SERVICES-AE
 * Interface pour gérer cookies, termes et politique de confidentialité
 */

// Protection d'authentification
require_once __DIR__ . '/auth-check.php';

// Inclure les dépendances
require_once '../config/config.php';
require_once '../config/db.php';
require_once __DIR__ . '/LegalPagesManager.php';

// Initialiser LegalPagesManager
$legalManager = new LegalPagesManager($pdo);

// Vérifier et créer la table si nécessaire
if (!$legalManager->tableExists()) {
    $legalManager->createTable();
}

// Variables pour les messages
$success_message = '';
$error_message = '';

// Traitement des actions
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    $action = $_POST['action'];
    
    switch ($action) {
        case 'update_page':
            $pageId = $_POST['page_id'] ?? '';
            $data = [
                'title' => trim($_POST['title'] ?? ''),
                'content' => trim($_POST['content'] ?? ''),
                'meta_description' => trim($_POST['meta_description'] ?? ''),
                'status' => $_POST['status'] ?? 'active'
            ];
            
            if (empty($data['title']) || empty($data['content'])) {
                $error_message = 'Le titre et le contenu sont obligatoires.';
            } else {
                if ($legalManager->update($pageId, $data)) {
                    $success_message = 'Page mise à jour avec succès !';
                } else {
                    $error_message = 'Erreur lors de la mise à jour.';
                }
            }
            
            // Retourner une réponse JSON si c'est une requête AJAX
            if (isset($_POST['ajax'])) {
                header('Content-Type: application/json');
                echo json_encode([
                    'success' => !empty($success_message),
                    'message' => $success_message ?: $error_message
                ]);
                exit;
            }
            break;
    }
}

// Récupérer les actions GET
if (isset($_GET['action'])) {
    $action = $_GET['action'];
    
    switch ($action) {
        case 'get_page':
            $pageId = $_GET['id'] ?? '';
            $page = $legalManager->getById($pageId);
            
            header('Content-Type: application/json');
            echo json_encode([
                'success' => $page !== false,
                'page' => $page
            ]);
            exit;
            break;
    }
}

// Récupérer toutes les pages légales
$legalPages = $legalManager->getAllPages();

// Configuration pour le contenu de la page
ob_start();
?>

<!-- Messages d'alerte -->
<div id="alertContainer">
    <?php if (!empty($success_message)): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="ri ri-check-circle-line me-2"></i>
            <?php echo htmlspecialchars($success_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <?php if (!empty($error_message)): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="ri ri-error-warning-line me-2"></i>
            <?php echo htmlspecialchars($error_message); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
</div>

<!-- Titre et statistiques -->
<div class="row mb-4">
    <div class="col-12">
        <div class="card bg-gradient-primary text-white">
            <div class="card-body">
                <div class="row align-items-center">
                    <div class="col">
                        <h4 class="card-title text-white mb-1">
                            <i class="ri ri-file-text-line me-2"></i>
                            Gestion des Pages Légales
                        </h4>
                        <p class="card-text mb-0 opacity-75">
                            Gérez vos cookies, conditions d'utilisation et politique de confidentialité
                        </p>
                    </div>
                    <div class="col-auto">
                        <div class="avatar avatar-lg bg-white bg-opacity-25">
                            <i class="ri ri-shield-check-line ri-2x text-white"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- Liste des pages légales -->
<div class="row">
    <?php foreach ($legalPages as $page): ?>
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card h-100">
                <div class="card-header d-flex justify-content-between align-items-center">
                    <h6 class="card-title mb-0">
                        <i class="ri ri-file-text-line me-2"></i>
                        <?php echo htmlspecialchars($page['title']); ?>
                    </h6>
                    <span class="badge bg-label-<?php echo $page['status'] === 'active' ? 'success' : 'secondary'; ?>">
                        <?php echo $page['status'] === 'active' ? 'Actif' : 'Inactif'; ?>
                    </span>
                </div>
                
                <div class="card-body">
                    <div class="mb-3">
                        <small class="text-muted">Type de page</small>
                        <p class="mb-2">
                            <?php 
                            $types = [
                                'cookies' => 'Politique de Cookies',
                                'terms' => 'Conditions d\'Utilisation', 
                                'privacy' => 'Politique de Confidentialité'
                            ];
                            echo $types[$page['page_type']] ?? ucfirst($page['page_type']);
                            ?>
                        </p>
                    </div>
                    
                    <div class="mb-3">
                        <small class="text-muted">Meta Description</small>
                        <p class="text-truncate" title="<?php echo htmlspecialchars($page['meta_description']); ?>">
                            <?php echo htmlspecialchars(substr($page['meta_description'], 0, 100) . '...'); ?>
                        </p>
                    </div>
                    
                    <div class="mb-3">
                        <small class="text-muted">Dernière modification</small>
                        <p class="mb-0"><?php echo date('d/m/Y H:i', strtotime($page['updated_at'])); ?></p>
                    </div>
                </div>
                
                <div class="card-footer">
                    <div class="d-flex justify-content-between">
                        <button type="button" class="btn btn-primary btn-sm" 
                                onclick="editLegalPage(<?php echo $page['id']; ?>)">
                            <i class="ri ri-edit-line me-1"></i>
                            Modifier
                        </button>
                        
                        <a href="<?php echo '../' . $page['page_type'] . '.php'; ?>" 
                           class="btn btn-outline-secondary btn-sm" 
                           target="_blank">
                            <i class="ri ri-eye-line me-1"></i>
                            Voir
                        </a>
                    </div>
                </div>
            </div>
        </div>
    <?php endforeach; ?>
</div>

<!-- Modal d'édition -->
<div class="modal fade" id="editLegalModal" tabindex="-1">
    <div class="modal-dialog modal-xl">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">
                    <i class="ri ri-edit-line me-2"></i>
                    Modifier la page légale
                </h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            
            <form id="editLegalForm">
                <div class="modal-body">
                    <input type="hidden" name="action" value="update_page">
                    <input type="hidden" name="ajax" value="1">
                    <input type="hidden" name="page_id" id="pageId">
                    
                    <div class="row mb-3">
                        <div class="col-md-8">
                            <label class="form-label">Titre de la page</label>
                            <input type="text" class="form-control" name="title" id="pageTitle" required>
                        </div>
                        
                        <div class="col-md-4">
                            <label class="form-label">Statut</label>
                            <select class="form-select" name="status" id="pageStatus">
                                <option value="active">Actif</option>
                                <option value="inactive">Inactif</option>
                            </select>
                        </div>
                    </div>
                    
                    <div class="mb-3">
                        <label class="form-label">Meta Description</label>
                        <textarea class="form-control" name="meta_description" id="pageMetaDesc" 
                                  rows="2" placeholder="Description pour les moteurs de recherche"></textarea>
                    </div>
                    
                    <!-- Summernote CSS & JS -->
                    <link href="https://cdn.jsdelivr.net/npm/summernote@0.8.20/dist/summernote-lite.min.css" rel="stylesheet">
                    <script src="https://cdn.jsdelivr.net/npm/summernote@0.8.20/dist/summernote-lite.min.js"></script>

                    <div class="mb-3">
                        <label class="form-label">Contenu de la page</label>
                        <textarea class="form-control" name="content" id="pageContent" rows="15" required></textarea>
                        <div class="form-text">Vous pouvez utiliser du HTML pour formater le contenu</div>
                    </div>
                </div>
                
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">
                        Annuler
                    </button>
                    <button type="submit" class="btn btn-primary">
                        <i class="ri ri-save-line me-1"></i>
                        Sauvegarder
                    </button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Initialize Summernote only if the element exists
document.addEventListener('DOMContentLoaded', function() {
    const pageContentEl = document.getElementById('pageContent');
    if (pageContentEl && typeof $ !== 'undefined' && typeof $.fn.summernote === 'function') {
        $('#pageContent').summernote({
            height: 400,
            toolbar: [
                ['style', ['style']],
                ['font', ['bold', 'italic', 'underline', 'clear', 'strikethrough', 'superscript', 'subscript']],
                ['fontname', ['fontname']],
                ['color', ['color']],
                ['para', ['ul', 'ol', 'paragraph']],
                ['insert', ['link', 'picture', 'video']],
                ['view', ['codeview', 'help']]
            ],
            fontNames: ['Arial', 'Courier New', 'Times New Roman', 'Verdana', 'Tahoma', 'Comic Sans MS', 'Impact'],
            fontNamesIgnoreCheck: ['Comic Sans MS', 'Impact']
        });
    }
});

// When modal shown, sync the value into summernote
if (typeof $ !== 'undefined') {
    $('#editLegalModal').on('shown.bs.modal', function () {
        try {
            const content = document.getElementById('pageContent') ? document.getElementById('pageContent').value : '';
            if (typeof $.fn.summernote === 'function') {
                $('#pageContent').summernote('code', content);
            }
        } catch (e) {
            console.error('Error setting summernote content:', e);
        }
    });
}

// Fonction pour afficher les alertes
function showAlert(message, type = 'info') {
    const alertContainer = document.getElementById('alertContainer');
    if (!alertContainer) return console.warn('alertContainer introuvable');
    const icon = type === 'success' ? 'check-circle' : 'error-warning';
    const alertHTML = `\n        <div class="alert alert-${type} alert-dismissible fade show" role="alert">\n            <i class="ri ri-${icon}-line me-2"></i>\n            ${message}\n            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>\n        </div>\n    `;
    alertContainer.innerHTML = alertHTML;
    console.log('showAlert:', type, message);
}

// Modifier une page légale
function editLegalPage(pageId) {
    console.log('editLegalPage called for id=', pageId);
    const modalElement = document.getElementById('editLegalModal');
    if (!modalElement) return console.error('Modal element introuvable');
    const modal = new bootstrap.Modal(modalElement);
    
    // Charger les données de la page
    fetch(`legal-pages.php?action=get_page&id=${pageId}`)
        .then(response => response.json())
        .then(function(data) {
            console.log('get_page response', data);
            if (data && data.success) {
                const page = data.page;
                // Remplir le formulaire en vérifiant l'existence des éléments
                const el = id => document.getElementById(id);
                if (el('pageId')) el('pageId').value = page.id || '';
                if (el('pageTitle')) el('pageTitle').value = page.title || '';
                if (el('pageMetaDesc')) el('pageMetaDesc').value = page.meta_description || '';
                if (el('pageContent')) el('pageContent').value = page.content || '';
                if (el('pageStatus')) el('pageStatus').value = page.status || 'active';
                fillContentFields(page.content || '');

                // Ouvrir la modal
                modal.show();
            } else {
                showAlert('Erreur lors du chargement de la page.', 'danger');
            }
        })
        .catch(function(error) {
            console.error('Erreur fetch get_page:', error);
            showAlert('Erreur de connexion au serveur.', 'danger');
        });
}

// Remplir le contenu lors de l'ouverture de la modal
function fillContentFields(content) {
    try {
        if (typeof $ !== 'undefined' && typeof $.fn.summernote === 'function') {
            $('#pageContent').summernote('code', content);
        } else if (document.getElementById('pageContent')) {
            document.getElementById('pageContent').value = content;
        }
    } catch (e) {
        console.error('fillContentFields error:', e);
    }
}

// Soumission du formulaire
const editForm = document.getElementById('editLegalForm');
if (editForm) {
    editForm.addEventListener('submit', function(e) {
        e.preventDefault();
        
        const formData = new FormData(this);
        const submitBtn = this.querySelector('button[type="submit"]');
        const originalText = submitBtn ? submitBtn.innerHTML : 'Sauvegarder';
        
        if (submitBtn) {
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="ri-loader-4-line ri-spin me-1"></i>Sauvegarde...';
        }
        
        fetch('legal-pages.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(function(data) {
            console.log('update_page response', data);
            if (data && data.success) {
                showAlert(data.message, 'success');
                try {
                    const modalInst = bootstrap.Modal.getInstance(document.getElementById('editLegalModal'));
                    if (modalInst) modalInst.hide();
                } catch (e) { console.warn('modal hide failed', e); }
                setTimeout(() => location.reload(), 1000);
            } else {
                showAlert(data.message || 'Erreur inconnue', 'danger');
            }
        })
        .catch(function(error) {
            console.error('Erreur fetch update_page:', error);
            showAlert('Erreur de connexion au serveur.', 'danger');
        })
        .finally(function() {
            if (submitBtn) {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            }
        });
    });
} else {
    console.warn('editLegalForm introuvable');
}
</script>

<style>
.bg-gradient-primary {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
}

.card-footer {
    background-color: #f8f9fa;
    border-top: 1px solid #e7eaf3;
}

.text-truncate {
    max-width: 100%;
}

.avatar-lg {
    width: 3rem;
    height: 3rem;
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 50%;
}

.ri-2x {
    font-size: 2rem;
}

textarea#pageContent {
    font-family: 'Courier New', monospace;
    font-size: 0.875rem;
}
</style>

<?php
// Capturer le contenu généré
$page_content = ob_get_clean();

// Inclure le template avec le contenu
include 'template.php';
?>