<?php
/**
 * Dua İstekleri Yönetimi ve Onay
 * Admin Panel
 */

session_start();
require_once __DIR__ . '/config/database.php';

$page_title = 'Dua İstekleri';

// Admin session kontrolü
if (!isset($_SESSION['admin_id'])) {
    header('Location: login.php');
    exit();
}

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

// Form işleme
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    try {
        if (isset($_POST['action'])) {
            switch ($_POST['action']) {
                case 'approve_request':
                    $requestId = (int)($_POST['request_id'] ?? 0);
                    
                    if ($requestId <= 0) {
                        throw new Exception("Geçersiz istek ID");
                    }
                    
                    $stmt = $db->prepare("UPDATE dua_requests SET status = 'approved', approved_by = ?, approved_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                    
                    if ($stmt->execute([$_SESSION['admin_id'], $requestId])) {
                        $_SESSION['success_message'] = "Dua isteği başarıyla onaylandı";
                    } else {
                        throw new Exception("Dua isteği onaylanırken hata oluştu");
                    }
                    break;
                    
                case 'reject_request':
                    $requestId = (int)($_POST['request_id'] ?? 0);
                    $adminNotes = trim($_POST['admin_notes'] ?? '');
                    
                    if ($requestId <= 0) {
                        throw new Exception("Geçersiz istek ID");
                    }
                    
                    $stmt = $db->prepare("UPDATE dua_requests SET status = 'rejected', admin_notes = ?, approved_by = ?, approved_at = CURRENT_TIMESTAMP, updated_at = CURRENT_TIMESTAMP WHERE id = ?");
                    
                    if ($stmt->execute([$adminNotes, $_SESSION['admin_id'], $requestId])) {
                        $_SESSION['success_message'] = "Dua isteği reddedildi";
                    } else {
                        throw new Exception("Dua isteği reddedilirken hata oluştu");
                    }
                    break;
                    
                case 'delete_request':
                    $requestId = (int)($_POST['request_id'] ?? 0);
                    
                    if ($requestId <= 0) {
                        throw new Exception("Geçersiz istek ID");
                    }
                    
                    $stmt = $db->prepare("DELETE FROM dua_requests WHERE id = ?");
                    
                    if ($stmt->execute([$requestId])) {
                        $_SESSION['success_message'] = "Dua isteği başarıyla silindi";
                    } else {
                        throw new Exception("Dua isteği silinirken hata oluştu");
                    }
                    break;
            }
        }
        
        header('Location: dua-requests.php');
        exit();
        
    } catch (Exception $e) {
        $_SESSION['error_message'] = $e->getMessage();
    }
}

// Filtreleme
$statusFilter = $_GET['status'] ?? 'all';
$categoryFilter = $_GET['category'] ?? 'all';

// İstatistikleri getir
$stats = [];
try {
    $stmt = $db->prepare("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_requests");
    $stmt->execute();
    $stats = $stmt->fetch();
} catch (Exception $e) {
    error_log("İstatistik getirme hatası: " . $e->getMessage());
}

// Kategorileri getir
$categories = [];
try {
    $stmt = $db->prepare("SELECT * FROM dua_categories ORDER BY sort_order, name");
    $stmt->execute();
    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    error_log("Kategori getirme hatası: " . $e->getMessage());
}

// Dua isteklerini getir
$requests = [];
try {
    $whereConditions = [];
    $params = [];
    
    if ($statusFilter !== 'all') {
        $whereConditions[] = "dr.status = ?";
        $params[] = $statusFilter;
    }
    
    if ($categoryFilter !== 'all') {
        $whereConditions[] = "dr.category_id = ?";
        $params[] = $categoryFilter;
    }
    
    $whereClause = !empty($whereConditions) ? 'WHERE ' . implode(' AND ', $whereConditions) : '';
    
    $stmt = $db->prepare("
        SELECT dr.*, 
               du.username, du.full_name, du.email,
               dc.name as category_name,
               au.full_name as approved_by_name
        FROM dua_requests dr
        LEFT JOIN dua_users du ON dr.user_id = du.id
        LEFT JOIN dua_categories dc ON dr.category_id = dc.id
        LEFT JOIN admin_users au ON dr.approved_by = au.id
        $whereClause
        ORDER BY 
            CASE WHEN dr.status = 'pending' THEN 1 ELSE 2 END,
            dr.created_at DESC
    ");
    $stmt->execute($params);
    $requests = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
} catch (Exception $e) {
    error_log("Dua istekleri getirme hatası: " . $e->getMessage());
}

include 'includes/header.php';
?>

<div class="page-header">
    <h2>Dua İstekleri Yönetimi</h2>
    <p>Kullanıcıların gönderdiği dua isteklerini onaylayın veya reddedin</p>
</div>

<!-- İstatistikler -->
<div class="stats-container">
    <div class="stat-card">
        <div class="stat-icon">
            <i class="fas fa-list"></i>
        </div>
        <div class="stat-content">
            <h3><?php echo $stats['total'] ?? 0; ?></h3>
            <p>Toplam İstek</p>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon pending">
            <i class="fas fa-clock"></i>
        </div>
        <div class="stat-content">
            <h3><?php echo $stats['pending'] ?? 0; ?></h3>
            <p>Bekleyen</p>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon approved">
            <i class="fas fa-check-circle"></i>
        </div>
        <div class="stat-content">
            <h3><?php echo $stats['approved'] ?? 0; ?></h3>
            <p>Onaylanan</p>
        </div>
    </div>
    
    <div class="stat-card">
        <div class="stat-icon rejected">
            <i class="fas fa-times-circle"></i>
        </div>
        <div class="stat-content">
            <h3><?php echo $stats['rejected'] ?? 0; ?></h3>
            <p>Reddedilen</p>
        </div>
    </div>
</div>

<!-- Filtreler -->
<div class="filters-container">
    <form method="GET" class="filters-form">
        <div class="filter-group">
            <label for="status">Durum:</label>
            <select name="status" id="status" onchange="this.form.submit()">
                <option value="all" <?php echo $statusFilter === 'all' ? 'selected' : ''; ?>>Tümü</option>
                <option value="pending" <?php echo $statusFilter === 'pending' ? 'selected' : ''; ?>>Bekleyen</option>
                <option value="approved" <?php echo $statusFilter === 'approved' ? 'selected' : ''; ?>>Onaylanan</option>
                <option value="rejected" <?php echo $statusFilter === 'rejected' ? 'selected' : ''; ?>>Reddedilen</option>
            </select>
        </div>
        
        <div class="filter-group">
            <label for="category">Kategori:</label>
            <select name="category" id="category" onchange="this.form.submit()">
                <option value="all" <?php echo $categoryFilter === 'all' ? 'selected' : ''; ?>>Tümü</option>
                <?php foreach ($categories as $category): ?>
                    <option value="<?php echo $category['id']; ?>" <?php echo $categoryFilter == $category['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($category['name']); ?>
                    </option>
                <?php endforeach; ?>
            </select>
        </div>
    </form>
</div>

<!-- Dua İstekleri Listesi -->
<div class="content-card">
    <div class="card-header">
        <h3>
            <i class="fas fa-pray"></i>
            Dua İstekleri
            <?php if ($statusFilter !== 'all' || $categoryFilter !== 'all'): ?>
                <span class="filter-badge">(Filtrelenmiş)</span>
            <?php endif; ?>
        </h3>
    </div>
    
    <div class="requests-container">
        <?php if (count($requests) > 0): ?>
            <?php foreach ($requests as $request): ?>
                <div class="request-card status-<?php echo $request['status']; ?>">
                    <div class="request-header">
                        <div class="request-meta">
                            <span class="status-badge status-<?php echo $request['status']; ?>">
                                <?php 
                                switch($request['status']) {
                                    case 'pending': echo 'Bekleyen'; break;
                                    case 'approved': echo 'Onaylanan'; break;
                                    case 'rejected': echo 'Reddedilen'; break;
                                }
                                ?>
                            </span>
                            <span class="category-badge"><?php echo htmlspecialchars($request['category_name']); ?></span>
                            <span class="date"><?php echo date('d.m.Y H:i', strtotime($request['created_at'])); ?></span>
                        </div>
                        
                        <?php if ($request['status'] === 'pending'): ?>
                            <div class="quick-actions">
                                <form method="POST" style="display: inline;">
                                    <input type="hidden" name="action" value="approve_request">
                                    <input type="hidden" name="request_id" value="<?php echo $request['id']; ?>">
                                    <button type="submit" class="btn btn-sm btn-success" title="Onayla">
                                        <i class="fas fa-check"></i>
                                    </button>
                                </form>
                                
                                <button type="button" class="btn btn-sm btn-danger" 
                                        onclick="showRejectModal(<?php echo $request['id']; ?>)" title="Reddet">
                                    <i class="fas fa-times"></i>
                                </button>
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="request-content">
                        <h4 class="request-title"><?php echo htmlspecialchars($request['title']); ?></h4>
                        <p class="request-description"><?php echo nl2br(htmlspecialchars($request['description'])); ?></p>
                        
                        <div class="request-info">
                            <div class="requester-info">
                                <strong>İsteyen:</strong>
                                <?php if ($request['is_anonymous']): ?>
                                    <span class="anonymous">Anonim</span>
                                <?php else: ?>
                                    <?php echo htmlspecialchars($request['requester_name'] ?: $request['full_name']); ?>
                                <?php endif; ?>
                            </div>
                            
                            <div class="user-info">
                                <strong>Kullanıcı:</strong>
                                <?php echo htmlspecialchars($request['full_name']); ?> 
                                (@<?php echo htmlspecialchars($request['username']); ?>)
                            </div>
                            
                            <?php if ($request['prayer_count'] > 0): ?>
                                <div class="prayer-count">
                                    <strong>Dua Sayısı:</strong> <?php echo $request['prayer_count']; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                        
                        <?php if ($request['status'] !== 'pending'): ?>
                            <div class="approval-info">
                                <strong>
                                    <?php echo $request['status'] === 'approved' ? 'Onaylayan:' : 'Reddeden:'; ?>
                                </strong>
                                <?php echo htmlspecialchars($request['approved_by_name']); ?>
                                <span class="approval-date">
                                    (<?php echo date('d.m.Y H:i', strtotime($request['approved_at'])); ?>)
                                </span>
                                
                                <?php if (!empty($request['admin_notes'])): ?>
                                    <div class="admin-notes">
                                        <strong>Not:</strong> <?php echo nl2br(htmlspecialchars($request['admin_notes'])); ?>
                                    </div>
                                <?php endif; ?>
                            </div>
                        <?php endif; ?>
                    </div>
                    
                    <div class="request-actions">
                        <?php if ($request['status'] === 'pending'): ?>
                            <form method="POST" style="display: inline;">
                                <input type="hidden" name="action" value="approve_request">
                                <input type="hidden" name="request_id" value="<?php echo $request['id']; ?>">
                                <button type="submit" class="btn btn-success">
                                    <i class="fas fa-check"></i> Onayla
                                </button>
                            </form>
                            
                            <button type="button" class="btn btn-danger" 
                                    onclick="showRejectModal(<?php echo $request['id']; ?>)">
                                <i class="fas fa-times"></i> Reddet
                            </button>
                        <?php endif; ?>
                        
                        <form method="POST" style="display: inline;" 
                              onsubmit="return confirm('Bu dua isteğini silmek istediğinizden emin misiniz?')">
                            <input type="hidden" name="action" value="delete_request">
                            <input type="hidden" name="request_id" value="<?php echo $request['id']; ?>">
                            <button type="submit" class="btn btn-outline-danger">
                                <i class="fas fa-trash"></i> Sil
                            </button>
                        </form>
                    </div>
                </div>
            <?php endforeach; ?>
        <?php else: ?>
            <div class="empty-state">
                <i class="fas fa-pray"></i>
                <h3>Dua isteği bulunmuyor</h3>
                <p>
                    <?php if ($statusFilter !== 'all' || $categoryFilter !== 'all'): ?>
                        Seçilen filtrelere uygun dua isteği bulunamadı
                    <?php else: ?>
                        Henüz hiç dua isteği gönderilmemiş
                    <?php endif; ?>
                </p>
            </div>
        <?php endif; ?>
    </div>
</div>

<!-- Reddetme Modal -->
<div id="rejectModal" class="modal" style="display: none;">
    <div class="modal-content">
        <div class="modal-header">
            <h3>Dua İsteğini Reddet</h3>
            <span class="close" onclick="closeRejectModal()">&times;</span>
        </div>
        <form method="POST" id="rejectForm">
            <input type="hidden" name="action" value="reject_request">
            <input type="hidden" name="request_id" id="rejectRequestId">
            
            <div class="modal-body">
                <div class="form-group">
                    <label for="admin_notes">Reddetme Sebebi (İsteğe bağlı):</label>
                    <textarea name="admin_notes" id="admin_notes" rows="4" 
                              placeholder="Reddetme sebebini açıklayın..."></textarea>
                </div>
            </div>
            
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" onclick="closeRejectModal()">İptal</button>
                <button type="submit" class="btn btn-danger">Reddet</button>
            </div>
        </form>
    </div>
</div>

<style>
.stats-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 1.5rem;
    margin-bottom: 2rem;
}

.stat-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    display: flex;
    align-items: center;
    gap: 1rem;
}

.stat-icon {
    width: 50px;
    height: 50px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 1.2rem;
}

.stat-icon {
    background: #e3f2fd;
    color: #1976d2;
}

.stat-icon.pending {
    background: #fff3e0;
    color: #f57c00;
}

.stat-icon.approved {
    background: #e8f5e8;
    color: #2e7d32;
}

.stat-icon.rejected {
    background: #ffebee;
    color: #d32f2f;
}

.filters-container {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    margin-bottom: 2rem;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
}

.filters-form {
    display: flex;
    gap: 2rem;
    align-items: end;
}

.filter-group {
    display: flex;
    flex-direction: column;
    gap: 0.5rem;
}

.filter-group label {
    font-weight: 600;
    color: #374151;
}

.filter-group select {
    padding: 0.5rem;
    border: 2px solid #e5e7eb;
    border-radius: 8px;
    background: white;
}

.requests-container {
    display: flex;
    flex-direction: column;
    gap: 1.5rem;
}

.request-card {
    background: white;
    border-radius: 12px;
    padding: 1.5rem;
    box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    border-left: 4px solid #e5e7eb;
}

.request-card.status-pending {
    border-left-color: #f59e0b;
}

.request-card.status-approved {
    border-left-color: #10b981;
}

.request-card.status-rejected {
    border-left-color: #ef4444;
}

.request-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 1rem;
}

.request-meta {
    display: flex;
    gap: 0.75rem;
    align-items: center;
}

.status-badge {
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 600;
}

.status-badge.status-pending {
    background: #fef3c7;
    color: #92400e;
}

.status-badge.status-approved {
    background: #dcfce7;
    color: #166534;
}

.status-badge.status-rejected {
    background: #fee2e2;
    color: #991b1b;
}

.category-badge {
    background: #e0e7ff;
    color: #3730a3;
    padding: 0.25rem 0.75rem;
    border-radius: 20px;
    font-size: 0.8rem;
    font-weight: 500;
}

.date {
    color: #6b7280;
    font-size: 0.85rem;
}

.quick-actions {
    display: flex;
    gap: 0.5rem;
}

.request-title {
    margin: 0 0 0.75rem 0;
    color: #1f2937;
    font-size: 1.1rem;
}

.request-description {
    color: #4b5563;
    line-height: 1.6;
    margin-bottom: 1rem;
}

.request-info {
    background: #f9fafb;
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 1rem;
}

.request-info > div {
    margin-bottom: 0.5rem;
}

.request-info > div:last-child {
    margin-bottom: 0;
}

.anonymous {
    color: #6b7280;
    font-style: italic;
}

.approval-info {
    background: #f3f4f6;
    padding: 1rem;
    border-radius: 8px;
    margin-bottom: 1rem;
}

.approval-date {
    color: #6b7280;
    font-size: 0.9rem;
}

.admin-notes {
    margin-top: 0.5rem;
    padding-top: 0.5rem;
    border-top: 1px solid #e5e7eb;
}

.request-actions {
    display: flex;
    gap: 0.75rem;
    flex-wrap: wrap;
}

.filter-badge {
    background: #dbeafe;
    color: #1e40af;
    padding: 0.25rem 0.5rem;
    border-radius: 6px;
    font-size: 0.8rem;
    margin-left: 0.5rem;
}

/* Modal Styles */
.modal {
    position: fixed;
    z-index: 1000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
    display: flex;
    align-items: center;
    justify-content: center;
}

.modal-content {
    background: white;
    border-radius: 12px;
    width: 90%;
    max-width: 500px;
    max-height: 90vh;
    overflow-y: auto;
}

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

.modal-header h3 {
    margin: 0;
}

.close {
    font-size: 1.5rem;
    cursor: pointer;
    color: #6b7280;
}

.modal-body {
    padding: 1.5rem;
}

.modal-footer {
    padding: 1.5rem;
    border-top: 1px solid #e5e7eb;
    display: flex;
    gap: 1rem;
    justify-content: flex-end;
}

.form-group {
    margin-bottom: 1rem;
}

.form-group label {
    display: block;
    margin-bottom: 0.5rem;
    font-weight: 600;
    color: #374151;
}

.form-group textarea {
    width: 100%;
    padding: 0.75rem;
    border: 2px solid #e5e7eb;
    border-radius: 8px;
    resize: vertical;
}

@media (max-width: 768px) {
    .filters-form {
        flex-direction: column;
        align-items: stretch;
    }
    
    .request-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 1rem;
    }
    
    .request-actions {
        flex-direction: column;
    }
}
</style>

<script>
function showRejectModal(requestId) {
    document.getElementById('rejectRequestId').value = requestId;
    document.getElementById('rejectModal').style.display = 'flex';
}

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

// Modal dışına tıklandığında kapat
window.onclick = function(event) {
    const modal = document.getElementById('rejectModal');
    if (event.target === modal) {
        closeRejectModal();
    }
}
</script>

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