<?php
/**
 * Dua Yorumları Yönetim Sayfası
 * Admin Panel - Yorum Onaylama/Reddetme/Silme
 */

require_once __DIR__ . '/config/database.php';

$page_title = "Yorum Yönetimi";

// Header include et
require_once __DIR__ . '/includes/header.php';

// Veritabanı bağlantısı
$database = new Database();
$pdo = $database->getConnection();

// İşlem kontrolü
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $action = $_POST['action'] ?? '';
    $comment_id = $_POST['comment_id'] ?? 0;
    
    if ($action && $comment_id) {
        try {
            switch ($action) {
                case 'approve':
                    $stmt = $pdo->prepare("UPDATE dua_comments SET status = 'approved', admin_notes = ?, approved_by = ?, approved_at = NOW() WHERE id = ?");
                    $stmt->execute(['Admin tarafindan onaylandi', $_SESSION['admin_id'] ?? 1, $comment_id]);
                    $_SESSION['success_message'] = "Yorum başarıyla onaylandı.";
                    break;
                    
                case 'reject':
                    $admin_notes = $_POST['admin_notes'] ?? 'Admin tarafindan reddedildi';
                    // Türkçe karakterleri temizle
                    $admin_notes = mb_convert_encoding($admin_notes, 'UTF-8', 'UTF-8');
                    $stmt = $pdo->prepare("UPDATE dua_comments SET status = 'rejected', admin_notes = ?, approved_by = ?, approved_at = NOW() WHERE id = ?");
                    $stmt->execute([$admin_notes, $_SESSION['admin_id'] ?? 1, $comment_id]);
                    $_SESSION['success_message'] = "Yorum reddedildi.";
                    break;
                    
                case 'delete':
                    $stmt = $pdo->prepare("DELETE FROM dua_comments WHERE id = ?");
                    $stmt->execute([$comment_id]);
                    $_SESSION['success_message'] = "Yorum silindi.";
                    break;
            }
        } catch (PDOException $e) {
            $_SESSION['error_message'] = "İşlem sırasında hata oluştu: " . $e->getMessage();
        }
        
        // Mevcut filtre durumunu koruyarak redirect yap
        $redirect_params = [];
        if (isset($_GET['status']) && $_GET['status'] !== 'all') {
            $redirect_params['status'] = $_GET['status'];
        }
        if (isset($_GET['page']) && $_GET['page'] > 1) {
            $redirect_params['page'] = $_GET['page'];
        }
        
        $redirect_url = 'dua-comments.php';
        if (!empty($redirect_params)) {
            $redirect_url .= '?' . http_build_query($redirect_params);
        }
        
        header('Location: ' . $redirect_url);
        exit();
    }
}

// Filtreleme
$status_filter = $_GET['status'] ?? 'all';
$page = max(1, intval($_GET['page'] ?? 1));
$per_page = 20;
$offset = ($page - 1) * $per_page;

// Toplam yorum sayısı
$count_query = "SELECT COUNT(*) FROM dua_comments dc 
                LEFT JOIN dua_requests dr ON dc.request_id = dr.id 
                LEFT JOIN dua_users du ON dc.user_id = du.id";

$where_conditions = [];
$params = [];

if ($status_filter !== 'all') {
    $where_conditions[] = "dc.status = ?";
    $params[] = $status_filter;
}

if (!empty($where_conditions)) {
    $count_query .= " WHERE " . implode(" AND ", $where_conditions);
}

$count_stmt = $pdo->prepare($count_query);
$count_stmt->execute($params);
$total_comments = $count_stmt->fetchColumn();
$total_pages = ceil($total_comments / $per_page);

// Yorumları getir
$query = "SELECT dc.*, dr.description as request_content, du.full_name as user_name, du.email as user_email
          FROM dua_comments dc 
          LEFT JOIN dua_requests dr ON dc.request_id = dr.id 
          LEFT JOIN dua_users du ON dc.user_id = du.id";

if (!empty($where_conditions)) {
    $query .= " WHERE " . implode(" AND ", $where_conditions);
}

$query .= " ORDER BY dc.created_at DESC LIMIT ? OFFSET ?";
$params[] = $per_page;
$params[] = $offset;

$stmt = $pdo->prepare($query);
$stmt->execute($params);
$comments = $stmt->fetchAll(PDO::FETCH_ASSOC);

// İstatistikler
$stats_query = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'pending' THEN 1 ELSE 0 END) as pending,
    SUM(CASE WHEN status = 'approved' THEN 1 ELSE 0 END) as approved,
    SUM(CASE WHEN status = 'rejected' THEN 1 ELSE 0 END) as rejected
    FROM dua_comments";
$stats_stmt = $pdo->query($stats_query);
$stats = $stats_stmt->fetch(PDO::FETCH_ASSOC);
?>

<div class="page-header">
    <h2>Yorum Yönetimi</h2>
    <p>Kullanıcıların dua taleplerine yaptığı yorumları yönetin</p>
</div>

<!-- ��statistik Kartları -->
<div class="stats-grid">
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-comments"></i>
        </div>
        <div class="stat-content">
            <h3><?php echo number_format($stats['total']); ?></h3>
            <p>Toplam Yorum</p>
        </div>
    </div>
    
    <div class="stat-card pending">
        <div class="stat-icon">
            <i class="fas fa-clock"></i>
        </div>
        <div class="stat-content">
            <h3><?php echo number_format($stats['pending']); ?></h3>
            <p>Bekleyen Yorum</p>
        </div>
    </div>
    
    <div class="stat-card approved">
        <div class="stat-icon">
            <i class="fas fa-check-circle"></i>
        </div>
        <div class="stat-content">
            <h3><?php echo number_format($stats['approved']); ?></h3>
            <p>Onaylanan Yorum</p>
        </div>
    </div>
    
    <div class="stat-card rejected">
        <div class="stat-icon">
            <i class="fas fa-times-circle"></i>
        </div>
        <div class="stat-content">
            <h3><?php echo number_format($stats['rejected']); ?></h3>
            <p>Reddedilen Yorum</p>
        </div>
    </div>
</div>

<!-- Filtreler -->
<div class="filters-section">
    <div class="filter-tabs">
        <a href="?status=all" class="filter-tab <?php echo $status_filter === 'all' ? 'active' : ''; ?>">
            Tümü (<?php echo $stats['total']; ?>)
        </a>
        <a href="?status=pending" class="filter-tab <?php echo $status_filter === 'pending' ? 'active' : ''; ?>">
            Bekleyen (<?php echo $stats['pending']; ?>)
        </a>
        <a href="?status=approved" class="filter-tab <?php echo $status_filter === 'approved' ? 'active' : ''; ?>">
            Onaylanan (<?php echo $stats['approved']; ?>)
        </a>
        <a href="?status=rejected" class="filter-tab <?php echo $status_filter === 'rejected' ? 'active' : ''; ?>">
            Reddedilen (<?php echo $stats['rejected']; ?>)
        </a>
    </div>
</div>

<!-- Yorumlar Tablosu -->
<div class="table-container">
    <?php if (empty($comments)): ?>
        <div class="empty-state">
            <i class="fas fa-comments"></i>
            <h3>Yorum Bulunamadı</h3>
            <p>Seçilen kriterlere uygun yorum bulunmuyor.</p>
        </div>
    <?php else: ?>
        <table class="data-table">
            <thead>
                <tr>
                    <th>Yorum</th>
                    <th>Kullanıcı</th>
                    <th>Dua Talebi</th>
                    <th>Durum</th>
                    <th>Tarih</th>
                    <th>İşlemler</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($comments as $comment): ?>
                    <tr>
                        <td>
                            <div class="comment-content">
                                <?php echo htmlspecialchars(mb_substr($comment['comment'], 0, 100)); ?>
                                <?php if (mb_strlen($comment['comment']) > 100): ?>...<?php endif; ?>
                            </div>
                        </td>
                        <td>
                            <div class="user-info">
                                <strong><?php echo htmlspecialchars($comment['commenter_name'] ?: 'Anonim'); ?></strong>
                                <?php if ($comment['user_name']): ?>
                                    <br><small><?php echo htmlspecialchars($comment['user_name']); ?></small>
                                <?php endif; ?>
                            </div>
                        </td>
                        <td>
                            <div class="request-preview">
                                <?php echo htmlspecialchars(mb_substr($comment['request_content'], 0, 50)); ?>...
                            </div>
                        </td>
                        <td>
                            <span class="status-badge status-<?php echo $comment['status']; ?>">
                                <?php 
                                switch($comment['status']) {
                                    case 'pending': echo 'Bekliyor'; break;
                                    case 'approved': echo 'Onaylandı'; break;
                                    case 'rejected': echo 'Reddedildi'; break;
                                }
                                ?>
                            </span>
                        </td>
                        <td>
                            <div class="date-info">
                                <?php echo date('d.m.Y H:i', strtotime($comment['created_at'])); ?>
                            </div>
                        </td>
                        <td>
                            <div class="action-buttons">
                                <?php if ($comment['status'] === 'pending'): ?>
                                    <button class="btn btn-success btn-sm" onclick="approveComment(<?php echo $comment['id']; ?>)">
                                        <i class="fas fa-check"></i> Onayla
                                    </button>
                                    <button class="btn btn-danger btn-sm" onclick="rejectComment(<?php echo $comment['id']; ?>)">
                                        <i class="fas fa-times"></i> Reddet
                                    </button>
                                <?php endif; ?>
                                <button class="btn btn-info btn-sm" onclick="viewComment(<?php echo $comment['id']; ?>)">
                                    <i class="fas fa-eye"></i> Görüntüle
                                </button>
                                <button class="btn btn-danger btn-sm" onclick="deleteComment(<?php echo $comment['id']; ?>)">
                                    <i class="fas fa-trash"></i> Sil
                                </button>
                            </div>
                        </td>
                    </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    <?php endif; ?>
</div>

<!-- Sayfalama -->
<?php if ($total_pages > 1): ?>
    <div class="pagination">
        <?php if ($page > 1): ?>
            <a href="?status=<?php echo $status_filter; ?>&page=<?php echo $page - 1; ?>" class="pagination-btn">
                <i class="fas fa-chevron-left"></i> Önceki
            </a>
        <?php endif; ?>
        
        <span class="pagination-info">
            Sayfa <?php echo $page; ?> / <?php echo $total_pages; ?>
        </span>
        
        <?php if ($page < $total_pages): ?>
            <a href="?status=<?php echo $status_filter; ?>&page=<?php echo $page + 1; ?>" class="pagination-btn">
                Sonraki <i class="fas fa-chevron-right"></i>
            </a>
        <?php endif; ?>
    </div>
<?php endif; ?>

<!-- Yorum Görüntüleme Modal -->
<div id="commentModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Yorum Detayları</h3>
            <span class="close" onclick="closeModal()">&times;</span>
        </div>
        <div class="modal-body" id="commentModalBody">
            <!-- İçerik JavaScript ile doldurulacak -->
        </div>
    </div>
</div>

<!-- Reddetme Modal -->
<div id="rejectModal" class="modal">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Yorumu Reddet</h3>
            <span class="close" onclick="closeRejectModal()">&times;</span>
        </div>
        <div class="modal-body">
            <form id="rejectForm" method="POST">
                <input type="hidden" name="action" value="reject">
                <input type="hidden" name="comment_id" id="rejectCommentId">
                
                <div class="form-group">
                    <label for="admin_notes">Reddetme Sebebi:</label>
                    <textarea name="admin_notes" id="admin_notes" rows="3" class="form-control" 
                              placeholder="Yorumun neden reddedildiğini açıklayın..."></textarea>
                </div>
                
                <div class="form-actions">
                    <button type="button" class="btn btn-secondary" onclick="closeRejectModal()">İptal</button>
                    <button type="submit" class="btn btn-danger">Reddet</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script>
// Yorum onaylama
function approveComment(commentId) {
    if (confirm('Bu yorumu onaylamak istediğinizden emin misiniz?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="approve">
            <input type="hidden" name="comment_id" value="${commentId}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

// Yorum reddetme
function rejectComment(commentId) {
    document.getElementById('rejectCommentId').value = commentId;
    document.getElementById('rejectModal').style.display = 'block';
}

// Yorum silme
function deleteComment(commentId) {
    if (confirm('Bu yorumu kalıcı olarak silmek istediğinizden emin misiniz?')) {
        const form = document.createElement('form');
        form.method = 'POST';
        form.innerHTML = `
            <input type="hidden" name="action" value="delete">
            <input type="hidden" name="comment_id" value="${commentId}">
        `;
        document.body.appendChild(form);
        form.submit();
    }
}

// Yorum görüntüleme
function viewComment(commentId) {
    // AJAX ile yorum detaylarını getir
    fetch(`api/dua-comments.php?id=${commentId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                const comment = data.comment;
                document.getElementById('commentModalBody').innerHTML = `
                    <div class="comment-details">
                        <div class="detail-row">
                            <strong>Yorum:</strong>
                            <p>${comment.comment}</p>
                        </div>
                        <div class="detail-row">
                            <strong>Yorumcu:</strong>
                            <p>${comment.commenter_name || 'Anonim'}</p>
                        </div>
                        <div class="detail-row">
                            <strong>Kullanıcı:</strong>
                            <p>${comment.user_name || 'Kayıtlı değil'}</p>
                        </div>
                        <div class="detail-row">
                            <strong>Dua Talebi:</strong>
                            <p>${comment.request_content}</p>
                        </div>
                        <div class="detail-row">
                            <strong>Durum:</strong>
                            <span class="status-badge status-${comment.status}">
                                ${comment.status === 'pending' ? 'Bekliyor' : 
                                  comment.status === 'approved' ? 'Onaylandı' : 'Reddedildi'}
                            </span>
                        </div>
                        <div class="detail-row">
                            <strong>Tarih:</strong>
                            <p>${new Date(comment.created_at).toLocaleString('tr-TR')}</p>
                        </div>
                        ${comment.admin_notes ? `
                            <div class="detail-row">
                                <strong>Admin Notları:</strong>
                                <p>${comment.admin_notes}</p>
                            </div>
                        ` : ''}
                    </div>
                `;
                document.getElementById('commentModal').style.display = 'block';
            }
        })
        .catch(error => {
            alert('Yorum detayları yüklenirken hata oluştu.');
        });
}

// Modal kapatma
function closeModal() {
    document.getElementById('commentModal').style.display = 'none';
}

function closeRejectModal() {
    document.getElementById('rejectModal').style.display = 'none';
}

// Modal dışına tıklayınca kapatma
window.onclick = function(event) {
    const commentModal = document.getElementById('commentModal');
    const rejectModal = document.getElementById('rejectModal');
    
    if (event.target === commentModal) {
        commentModal.style.display = 'none';
    }
    if (event.target === rejectModal) {
        rejectModal.style.display = 'none';
    }
}
</script>

<style>
.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.stat-card {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    gap: 15px;
}

.stat-card.pending { border-left: 4px solid #ffc107; }
.stat-card.approved { border-left: 4px solid #28a745; }
.stat-card.rejected { border-left: 4px solid #dc3545; }

.stat-icon {
    font-size: 2rem;
    color: #6c757d;
}

.stat-card.pending .stat-icon { color: #ffc107; }
.stat-card.approved .stat-icon { color: #28a745; }
.stat-card.rejected .stat-icon { color: #dc3545; }

.stat-content h3 {
    margin: 0;
    font-size: 2rem;
    font-weight: bold;
}

.stat-content p {
    margin: 0;
    color: #6c757d;
}

.filters-section {
    margin-bottom: 20px;
}

.filter-tabs {
    display: flex;
    gap: 10px;
    border-bottom: 1px solid #dee2e6;
}

.filter-tab {
    padding: 10px 20px;
    text-decoration: none;
    color: #6c757d;
    border-bottom: 2px solid transparent;
    transition: all 0.3s;
}

.filter-tab:hover {
    color: #007bff;
}

.filter-tab.active {
    color: #007bff;
    border-bottom-color: #007bff;
}

.table-container {
    background: white;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.data-table {
    width: 100%;
    border-collapse: collapse;
}

.data-table th,
.data-table td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid #dee2e6;
}

.data-table th {
    background: #f8f9fa;
    font-weight: 600;
}

.comment-content {
    max-width: 200px;
    word-wrap: break-word;
}

.user-info strong {
    color: #333;
}

.user-info small {
    color: #6c757d;
}

.request-preview {
    max-width: 150px;
    color: #6c757d;
    font-size: 0.9rem;
}

.status-badge {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 0.8rem;
    font-weight: 500;
}

.status-pending {
    background: #fff3cd;
    color: #856404;
}

.status-approved {
    background: #d4edda;
    color: #155724;
}

.status-rejected {
    background: #f8d7da;
    color: #721c24;
}

.action-buttons {
    display: flex;
    gap: 5px;
    flex-wrap: wrap;
}

.btn {
    padding: 6px 12px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    text-decoration: none;
    font-size: 0.8rem;
    transition: all 0.3s;
}

.btn-sm {
    padding: 4px 8px;
    font-size: 0.75rem;
}

.btn-success {
    background: #28a745;
    color: white;
}

.btn-success:hover {
    background: #218838;
}

.btn-danger {
    background: #dc3545;
    color: white;
}

.btn-danger:hover {
    background: #c82333;
}

.btn-info {
    background: #17a2b8;
    color: white;
}

.btn-info:hover {
    background: #138496;
}

.btn-secondary {
    background: #6c757d;
    color: white;
}

.btn-secondary:hover {
    background: #5a6268;
}

.empty-state {
    text-align: center;
    padding: 60px 20px;
    color: #6c757d;
}

.empty-state i {
    font-size: 4rem;
    margin-bottom: 20px;
}

.pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 20px;
    margin-top: 20px;
}

.pagination-btn {
    padding: 8px 16px;
    background: #007bff;
    color: white;
    text-decoration: none;
    border-radius: 4px;
    transition: background 0.3s;
}

.pagination-btn:hover {
    background: #0056b3;
}

.pagination-info {
    color: #6c757d;
}

.modal {
    display: none;
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}

.modal-content {
    background-color: white;
    margin: 5% auto;
    padding: 0;
    border-radius: 8px;
    width: 90%;
    max-width: 600px;
    max-height: 80vh;
    overflow-y: auto;
}

.modal-header {
    padding: 20px;
    border-bottom: 1px solid #dee2e6;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.modal-header h3 {
    margin: 0;
}

.close {
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
    color: #aaa;
}

.close:hover {
    color: #000;
}

.modal-body {
    padding: 20px;
}

.comment-details .detail-row {
    margin-bottom: 15px;
}

.comment-details .detail-row strong {
    display: block;
    margin-bottom: 5px;
    color: #333;
}

.comment-details .detail-row p {
    margin: 0;
    padding: 10px;
    background: #f8f9fa;
    border-radius: 4px;
    border-left: 3px solid #007bff;
}

.form-group {
    margin-bottom: 15px;
}

.form-group label {
    display: block;
    margin-bottom: 5px;
    font-weight: 500;
}

.form-control {
    width: 100%;
    padding: 8px 12px;
    border: 1px solid #ced4da;
    border-radius: 4px;
    font-size: 14px;
}

.form-control:focus {
    outline: none;
    border-color: #007bff;
    box-shadow: 0 0 0 2px rgba(0,123,255,0.25);
}

.form-actions {
    display: flex;
    gap: 10px;
    justify-content: flex-end;
    margin-top: 20px;
}
</style>

<?php require_once 'includes/footer.php'; ?>
