
<?php
/**
 * Gestion des témoignages avec design moderne - SERVICES-AE
 * Utilise le template Materio
 */

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

require_once '../config/config.php';
require_once '../config/db.php';

// Ensure $admin_logged is defined by auth-check or fallback to false to avoid notices
if (!isset($admin_logged)) {
    $admin_logged = false;
}

// Configuration de la page
$page_title = 'Gestion des Témoignages';
$current_page = 'testimonials';
$current_action = 'manage';

// Pagination et filtres
$page = intval($_GET['page'] ?? 1);
$per_page = 10;
$filter_status = $_GET['status'] ?? 'all';
$search = $_GET['search'] ?? '';
$sort = $_GET['sort'] ?? 'date_creation';
$order = $_GET['order'] ?? 'DESC';

// Traitement des actions admin
$is_ajax = isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && $admin_logged) {
    $action = $_POST['action'] ?? '';
    
    try {
        switch ($action) {
            case 'bulk_action':
                $bulk_action = $_POST['bulk_action'] ?? '';
                $selected_ids = $_POST['selected_testimonials'] ?? [];
                
                if (!empty($selected_ids) && !empty($bulk_action)) {
                    $ids_placeholder = implode(',', array_fill(0, count($selected_ids), '?'));
                    
                    switch ($bulk_action) {
                        case 'approve':
                            executeQuery("UPDATE testimonials SET approuve = 1, date_approbation = NOW() WHERE id IN ($ids_placeholder)", $selected_ids);
                            $success_message = count($selected_ids) . " témoignages approuvés avec succès !";
                            break;
                        case 'reject':
                            executeQuery("UPDATE testimonials SET approuve = 0 WHERE id IN ($ids_placeholder)", $selected_ids);
                            $success_message = count($selected_ids) . " témoignages rejetés.";
                            break;
                        case 'delete':
                            $testimonials = fetchAll("SELECT image_client FROM testimonials WHERE id IN ($ids_placeholder) AND image_client IS NOT NULL", $selected_ids);
                            foreach ($testimonials as $t) {
                                if (file_exists('../' . $t['image_client'])) {
                                    unlink('../' . $t['image_client']);
                                }
                            }
                            executeQuery("DELETE FROM testimonials WHERE id IN ($ids_placeholder)", $selected_ids);
                            $success_message = count($selected_ids) . " témoignages supprimés définitivement.";
                            break;
                    }
                }
                break;
                
            case 'single_action':
                $testimonial_id = intval($_POST['testimonial_id']);
                $single_action = $_POST['single_action'];
                
                switch ($single_action) {
                    case 'approve':
                        executeQuery("UPDATE testimonials SET approuve = 1, date_approbation = NOW() WHERE id = ?", [$testimonial_id]);
                        $success_message = "Témoignage approuvé !";
                        break;
                    case 'reject':
                        executeQuery("UPDATE testimonials SET approuve = 0 WHERE id = ?", [$testimonial_id]);
                        $success_message = "Témoignage rejeté.";
                        break;
                    case 'delete':
                        $testimonial = fetchOne("SELECT image_client FROM testimonials WHERE id = ?", [$testimonial_id]);
                        if ($testimonial && $testimonial['image_client'] && file_exists('../' . $testimonial['image_client'])) {
                            unlink('../' . $testimonial['image_client']);
                        }
                        executeQuery("DELETE FROM testimonials WHERE id = ?", [$testimonial_id]);
                        $success_message = "Témoignage supprimé définitivement.";
                        break;
                }
                break;
                
            case 'update_testimonial':
                $testimonial_id = intval($_POST['testimonial_id']);
                $nom_client = trim($_POST['nom_client']);
                $entreprise = trim($_POST['entreprise']);
                $poste = trim($_POST['poste']);
                $message = trim($_POST['message']);
                $note = intval($_POST['note']);
                
                executeQuery("
                    UPDATE testimonials 
                    SET nom_client = ?, entreprise = ?, poste = ?, message = ?, note = ?
                    WHERE id = ?
                ", [$nom_client, $entreprise, $poste, $message, $note, $testimonial_id]);
                
                $success_message = "Témoignage mis à jour avec succès !";
                break;
                
            case 'toggle_home_display':
                $testimonial_id = intval($_POST['testimonial_id']);
                $display_home = intval($_POST['display_home']);
                
                executeQuery("UPDATE testimonials SET affiche_page_accueil = ? WHERE id = ?", [$display_home, $testimonial_id]);
                $success_message = $display_home ? "Témoignage affiché sur la page d'accueil !" : "Témoignage masqué de la page d'accueil.";
                break;
        }
    } catch (Exception $e) {
        $error_message = "Erreur : " . $e->getMessage();
    }
}

// Construction de la requête avec filtres
$where_conditions = ["1=1"];
$params = [];

if ($filter_status !== 'all') {
    if ($filter_status === 'approved') {
        $where_conditions[] = "approuve = 1";
    } elseif ($filter_status === 'pending') {
        $where_conditions[] = "approuve = 0";
    }
}

if (!empty($search)) {
    $where_conditions[] = "(nom_client LIKE ? OR entreprise LIKE ? OR message LIKE ?)";
    $search_param = "%$search%";
    $params = array_merge($params, [$search_param, $search_param, $search_param]);
}

$where_clause = implode(' AND ', $where_conditions);

// Compter le total pour la pagination
$total_testimonials = fetchOne("SELECT COUNT(*) as count FROM testimonials WHERE $where_clause", $params)['count'];
$total_pages = ceil($total_testimonials / $per_page);
$offset = ($page - 1) * $per_page;

// Récupérer les témoignages
$testimonials = fetchAll("
    SELECT id, nom_client, entreprise, poste, message, note, approuve, image_client, affiche_page_accueil,
           DATE_FORMAT(date_creation, '%d/%m/%Y %H:%i') as date_creation_fmt,
           DATE_FORMAT(date_approbation, '%d/%m/%Y %H:%i') as date_approbation_fmt
    FROM testimonials 
    WHERE $where_clause
    ORDER BY $sort $order
    LIMIT $per_page OFFSET $offset
", $params);

// Statistiques
$total_count = fetchOne("SELECT COUNT(*) as count FROM testimonials")['count'];
$approved_count = fetchOne("SELECT COUNT(*) as count FROM testimonials WHERE approuve = 1")['count'];
$pending_count = fetchOne("SELECT COUNT(*) as count FROM testimonials WHERE approuve = 0")['count'];

// Variables pour le template
$pending_testimonials = $pending_count;

// Contenu de la page
ob_start();
?>

<!-- Alertes -->
<?php if (isset($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 $success_message; ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<?php if (isset($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 $error_message; ?>
    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>

<!-- Statistiques rapides -->
<div class="row mb-6">
    <div class="col-lg-3 col-md-6 mb-4">
        <div class="card h-100 border-start border-4 border-primary">
            <div class="card-body text-center">
                <div class="mb-3">
                    <i class="ri ri-chat-quote-line text-primary" style="font-size: 3rem;"></i>
                </div>
                <h3 class="card-title text-primary mb-2"><?php echo number_format($total_count); ?></h3>
                <p class="text-muted mb-0">Total Témoignages</p>
            </div>
        </div>
    </div>
    
    <div class="col-lg-3 col-md-6 mb-4">
        <div class="card h-100 border-start border-4 border-success">
            <div class="card-body text-center">
                <div class="mb-3">
                    <i class="ri ri-check-line text-success" style="font-size: 3rem;"></i>
                </div>
                <h3 class="card-title text-success mb-2"><?php echo number_format($approved_count); ?></h3>
                <p class="text-muted mb-0">Approuvés</p>
            </div>
        </div>
    </div>
    
    <div class="col-lg-3 col-md-6 mb-4">
        <div class="card h-100 border-start border-4 <?php echo $pending_count > 0 ? 'border-warning' : 'border-dark'; ?>">
            <div class="card-body text-center">
                <div class="mb-3">
                    <i class="ri ri-time-line <?php echo $pending_count > 0 ? 'text-warning' : 'text-dark'; ?>" style="font-size: 3rem;"></i>
                </div>
                <h3 class="card-title <?php echo $pending_count > 0 ? 'text-warning' : 'text-dark'; ?> mb-2"><?php echo number_format($pending_count); ?></h3>
                <p class="text-muted mb-0">En Attente</p>
            </div>
        </div>
    </div>
    
    <div class="col-lg-3 col-md-6 mb-4">
        <div class="card h-100 border-start border-4 border-info">
            <div class="card-body text-center">
                <div class="mb-3">
                    <i class="ri ri-star-line text-info" style="font-size: 3rem;"></i>
                </div>
                <h3 class="card-title text-info mb-2">
                    <?php 
                    $avg_rating = fetchOne("SELECT AVG(note) as avg FROM testimonials WHERE approuve = 1")['avg'];
                    echo $avg_rating ? number_format($avg_rating, 1) : '0';
                    ?>
                </h3>
                <p class="text-muted mb-0">Note Moyenne</p>
            </div>
        </div>
    </div>
</div>

<!-- Actions et filtres -->
<div class="card mb-4">
    <div class="card-header d-flex align-items-center justify-content-between">
        <h5 class="mb-0">
            <i class="ri ri-filter-line me-2"></i>
            Filtres et Actions
        </h5>
        <div class="d-flex gap-2">
            <a href="../add-testimonial.php" class="btn btn-success">
                <i class="ri ri-add-line me-2"></i>
                Nouveau Témoignage
            </a>
            <a href="../testimonials.php" class="btn btn-outline-primary" target="_blank">
                <i class="ri ri-eye-line me-2"></i>
                Vue Publique
            </a>
        </div>
    </div>
    <div class="card-body">
        <form method="GET" class="row g-3">
            <div class="col-md-3">
                <label class="form-label">Statut</label>
                <select name="status" class="form-select" onchange="this.form.submit()">
                    <option value="all" <?php echo $filter_status === 'all' ? 'selected' : ''; ?>>Tous</option>
                    <option value="approved" <?php echo $filter_status === 'approved' ? 'selected' : ''; ?>>Approuvés</option>
                    <option value="pending" <?php echo $filter_status === 'pending' ? 'selected' : ''; ?>>En attente</option>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label">Rechercher</label>
                <div class="input-group">
                    <input type="text" name="search" class="form-control" placeholder="Nom, entreprise, message..." value="<?php echo htmlspecialchars($search); ?>">
                    <button type="submit" class="btn btn-outline-primary">
                        <i class="ri ri-search-line"></i>
                    </button>
                </div>
            </div>
            <div class="col-md-2">
                <label class="form-label">Trier par</label>
                <select name="sort" class="form-select" onchange="this.form.submit()">
                    <option value="date_creation" <?php echo $sort === 'date_creation' ? 'selected' : ''; ?>>Date de création</option>
                    <option value="nom_client" <?php echo $sort === 'nom_client' ? 'selected' : ''; ?>>Nom client</option>
                    <option value="note" <?php echo $sort === 'note' ? 'selected' : ''; ?>>Note</option>
                    <option value="approuve" <?php echo $sort === 'approuve' ? 'selected' : ''; ?>>Statut</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label">Ordre</label>
                <select name="order" class="form-select" onchange="this.form.submit()">
                    <option value="DESC" <?php echo $order === 'DESC' ? 'selected' : ''; ?>>Décroissant</option>
                    <option value="ASC" <?php echo $order === 'ASC' ? 'selected' : ''; ?>>Croissant</option>
                </select>
            </div>
            <div class="col-md-1 d-flex align-items-end">
                <button type="button" class="btn btn-outline-secondary" onclick="location.reload()">
                    <i class="ri ri-refresh-line"></i>
                </button>
            </div>
        </form>
    </div>
</div>

<!-- Liste des témoignages -->
<div class="card">
    <div class="card-header d-flex align-items-center justify-content-between">
        <h5 class="mb-0">
            <i class="ri ri-list-check me-2"></i>
            Témoignages (<?php echo number_format($total_testimonials); ?>)
        </h5>
        <div class="d-flex align-items-center gap-3">
            <?php if (!empty($testimonials)): ?>
            <div class="d-flex align-items-center gap-2">
                <select id="bulk-action-select" class="form-select form-select-sm">
                    <option value="">Actions groupées</option>
                    <option value="approve">Approuver</option>
                    <option value="reject">Rejeter</option>
                    <option value="delete">Supprimer</option>
                </select>
                <button type="button" class="btn btn-sm btn-outline-primary" onclick="executeBulkAction()">
                    Appliquer
                </button>
            </div>
            <?php endif; ?>
        </div>
    </div>
    
    <?php if (empty($testimonials)): ?>
    <div class="card-body text-center py-5">
        <i class="ri ri-inbox-line text-muted mb-4 d-block" style="font-size: 4rem;"></i>
        <h5 class="text-muted mb-3">Aucun témoignage trouvé</h5>
        <p class="text-muted mb-4">
            <?php if (!empty($search) || $filter_status !== 'all'): ?>
                Aucun résultat ne correspond à vos critères de recherche.
            <?php else: ?>
                Il n'y a pas encore de témoignages dans la base de données.
            <?php endif; ?>
        </p>
        <div class="d-flex justify-content-center gap-2">
            <?php if (!empty($search) || $filter_status !== 'all'): ?>
            <a href="admin-testimonials.php" class="btn btn-outline-primary">
                <i class="ri ri-refresh-line me-2"></i>
                Réinitialiser les filtres
            </a>
            <?php endif; ?>
            <a href="../add-testimonial.php" class="btn btn-primary">
                <i class="ri ri-add-line me-2"></i>
                Ajouter le premier témoignage
            </a>
        </div>
    </div>
    
    <?php else: ?>
    <div class="table-responsive">
        <table class="table table-hover mb-0">
            <thead class="table-light">
                <tr>
                    <th width="40">
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input" id="select-all" onchange="toggleAllCheckboxes()">
                        </div>
                    </th>
                    <th>Client</th>
                    <th>Note</th>
                    <th>Statut</th>
                    <th>Accueil</th>
                    <th>Date</th>
                    <th width="120">Actions</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($testimonials as $testimonial): ?>
                <tr>
                    <td>
                        <div class="form-check">
                            <input type="checkbox" class="form-check-input testimonial-checkbox" value="<?php echo $testimonial['id']; ?>">
                        </div>
                    </td>
                    <td>
                        <div class="d-flex align-items-center">
                            <div class="avatar avatar-sm me-3">
                                <?php if ($testimonial['image_client']): ?>
                                    <img src="../<?php echo htmlspecialchars($testimonial['image_client']); ?>" 
                                         alt="Photo" class="rounded-circle">
                                <?php else: ?>
                                    <div class="avatar-initial bg-label-primary rounded-circle">
                                        <?php echo strtoupper(substr($testimonial['nom_client'], 0, 1)); ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                            <div>
                                <h6 class="mb-0"><?php echo htmlspecialchars($testimonial['nom_client']); ?></h6>
                                <small class="text-muted">
                                    <?php echo htmlspecialchars($testimonial['poste'] ?? ''); ?>
                                    <?php if ($testimonial['entreprise']): ?>
                                        chez <?php echo htmlspecialchars($testimonial['entreprise']); ?>
                                    <?php endif; ?>
                                </small>
                            </div>
                        </div>
                    </td>
                    <td>
                        <div class="d-flex align-items-center">
                            <?php for ($i = 1; $i <= 5; $i++): ?>
                                <i class="ri ri-star-<?php echo $i <= $testimonial['note'] ? 'fill' : 'line'; ?> text-warning"></i>
                            <?php endfor; ?>
                            <span class="ms-2 small text-muted"><?php echo $testimonial['note']; ?>/5</span>
                        </div>
                    </td>
                    <td>
                        <?php if ($testimonial['approuve']): ?>
                            <span class="badge bg-label-success">
                                <i class="ri ri-check-line me-1"></i>Approuvé
                            </span>
                        <?php else: ?>
                            <span class="badge bg-label-warning">
                                <i class="ri ri-time-line me-1"></i>En attente
                            </span>
                        <?php endif; ?>
                    </td>
                    <td>
                        <form method="POST" style="display: inline;">
                            <input type="hidden" name="action" value="toggle_home_display">
                            <input type="hidden" name="testimonial_id" value="<?php echo $testimonial['id']; ?>">
                            <input type="hidden" name="display_home" value="<?php echo $testimonial['affiche_page_accueil'] ? 0 : 1; ?>">
                            <button type="submit" 
                                    class="btn btn-sm <?php echo $testimonial['affiche_page_accueil'] ? 'btn-warning' : 'btn-outline-info'; ?>"
                                    title="<?php echo $testimonial['affiche_page_accueil'] ? 'Masquer de l\'accueil' : 'Afficher en accueil'; ?>">
                                <i class="ri <?php echo $testimonial['affiche_page_accueil'] ? 'ri-eye-off-line' : 'ri-eye-line'; ?> me-1"></i>
                                <?php echo $testimonial['affiche_page_accueil'] ? 'Visible' : 'Masqué'; ?>
                            </button>
                        </form>
                    </td>
                    <td>
                        <small class="text-muted d-block"><?php echo $testimonial['date_creation_fmt']; ?></small>
                        <?php if ($testimonial['date_approbation_fmt']): ?>
                            <small class="text-success">Approuvé le <?php echo $testimonial['date_approbation_fmt']; ?></small>
                        <?php endif; ?>
                    </td>
                    <td>
                        <div class="dropdown">
                            <button type="button" class="btn btn-sm btn-outline-secondary dropdown-toggle" 
                                    data-bs-toggle="dropdown">
                                Actions
                            </button>
                            <ul class="dropdown-menu">
                                <li>
                                    <a class="dropdown-item" href="admin-testimonial-preview.php?id=<?php echo $testimonial['id']; ?>">
                                        <i class="ri ri-eye-line me-2"></i>Aperçu
                                    </a>
                                </li>
                                <li><hr class="dropdown-divider"></li>
                                <li>
                                    <a class="dropdown-item" href="#" onclick="editTestimonial(<?php echo $testimonial['id']; ?>)">
                                        <i class="ri ri-edit-line me-2"></i>Modifier
                                    </a>
                                </li>
                                <li><hr class="dropdown-divider"></li>
                                <?php if (!$testimonial['approuve']): ?>
                                <li>
                                    <form method="POST" style="display: inline; margin: 0;">
                                        <input type="hidden" name="action" value="single_action">
                                        <input type="hidden" name="testimonial_id" value="<?php echo $testimonial['id']; ?>">
                                        <input type="hidden" name="single_action" value="approve">
                                        <button type="submit" class="dropdown-item text-success" style="border: none; background: transparent;">
                                            <i class="ri ri-check-line me-2"></i>Approuver
                                        </button>
                                    </form>
                                </li>
                                <?php else: ?>
                                <li>
                                    <form method="POST" style="display: inline; margin: 0;">
                                        <input type="hidden" name="action" value="single_action">
                                        <input type="hidden" name="testimonial_id" value="<?php echo $testimonial['id']; ?>">
                                        <input type="hidden" name="single_action" value="reject">
                                        <button type="submit" class="dropdown-item text-warning" style="border: none; background: transparent;">
                                            <i class="ri-close-line me-2"></i>Rejeter
                                        </button>
                                    </form>
                                </li>
                                <?php endif; ?>
                                <li><hr class="dropdown-divider"></li>
                                <li>
                                    <form method="POST" onsubmit="return confirm('Voulez-vous vraiment supprimer ce témoignage ?');" style="display: inline; margin: 0;">
                                        <input type="hidden" name="action" value="single_action">
                                        <input type="hidden" name="testimonial_id" value="<?php echo $testimonial['id']; ?>">
                                        <input type="hidden" name="single_action" value="delete">
                                        <button type="submit" class="dropdown-item text-danger" style="border: none; background: transparent;">
                                            <i class="ri-delete-bin-line me-2"></i>Supprimer
                                        </button>
                                    </form>
                                </li>
                            </ul>
                        </div>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>

    <!-- Pagination -->
    <?php if ($total_pages > 1): ?>
    <div class="card-footer">
        <nav aria-label="Navigation des témoignages">
            <ul class="pagination pagination-sm justify-content-center mb-0">
                <!-- Première page -->
                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => 1])); ?>">
                        <i class="ri-skip-back-line"></i>
                    </a>
                </li>
                
                <!-- Page précédente -->
                <li class="page-item <?php echo $page <= 1 ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => max(1, $page - 1)])); ?>">
                        <i class="ri-arrow-left-s-line"></i>
                    </a>
                </li>

                <!-- Pages numériques -->
                <?php
                $start = max(1, $page - 2);
                $end = min($total_pages, $page + 2);
                for ($i = $start; $i <= $end; $i++):
                ?>
                <li class="page-item <?php echo $i == $page ? 'active' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $i])); ?>">
                        <?php echo $i; ?>
                    </a>
                </li>
                <?php endfor; ?>

                <!-- Page suivante -->
                <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => min($total_pages, $page + 1)])); ?>">
                        <i class="ri-arrow-right-s-line"></i>
                    </a>
                </li>
                
                <!-- Dernière page -->
                <li class="page-item <?php echo $page >= $total_pages ? 'disabled' : ''; ?>">
                    <a class="page-link" href="?<?php echo http_build_query(array_merge($_GET, ['page' => $total_pages])); ?>">
                        <i class="ri-skip-forward-line"></i>
                    </a>
                </li>
            </ul>
        </nav>
        
        <div class="text-center mt-3">
            <small class="text-muted">
                Page <?php echo $page; ?> sur <?php echo $total_pages; ?> 
                (<?php echo number_format($total_testimonials); ?> témoignages au total)
            </small>
        </div>
    </div>
    <?php endif; ?>
    
    <?php endif; ?>
</div>

<!-- Formulaires cachés pour les actions -->
<form id="bulk-action-form" method="POST" style="display: none;">
    <input type="hidden" name="action" value="bulk_action">
    <input type="hidden" name="bulk_action" id="bulk-action-input">
    <div id="selected-testimonials-container"></div>
</form>

<form id="single-action-form" method="POST" style="display: none;">
    <input type="hidden" name="action" value="single_action">
    <input type="hidden" name="testimonial_id" id="single-action-id">
    <input type="hidden" name="single_action" id="single-action-type">
</form>

<?php
$page_content = ob_get_clean();

// JavaScript pour les interactions
$page_js_files = ['admin/js/testimonials.js'];

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