<?php
/**
 * Admin Paneli - Gelişmiş Deneme ve Sınav Takvimi Yönetimi
 * Konum: /magaza/admin/denemetakvimi/index.php
 */
require_once '../../includes/db.php';

// --- 1. FİLTRELEME VE SIRALAMA PARAMETRELERİ ---
$search = isset($_GET['q']) ? trim($_GET['q']) : '';
$type_filter = isset($_GET['type']) ? $_GET['type'] : '';
$official_filter = isset($_GET['official']) ? $_GET['official'] : ''; // 1: Resmi, 0: Yayın, '': Tümü
$date_start = isset($_GET['start']) ? $_GET['start'] : '';
$date_end = isset($_GET['end']) ? $_GET['end'] : '';

// Sıralama Ayarları
$sort_by = isset($_GET['sort']) ? $_GET['sort'] : 'exam_date';
$order = isset($_GET['order']) ? $_GET['order'] : 'ASC';

// --- 2. SAYFALAMA AYARLARI ---
$limit = 20; 
$page = isset($_GET['page']) && is_numeric($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// --- 3. SQL SORGUSU (FİLTRELERLE BİRLİKTE) ---
$where_clauses = [];
$params = [];

if (!empty($search)) {
    $where_clauses[] = "title LIKE ?";
    $params[] = "%$search%";
}
if (!empty($type_filter)) {
    $where_clauses[] = "exam_type = ?";
    $params[] = $type_filter;
}
if ($official_filter !== '') {
    $where_clauses[] = "is_official = ?";
    $params[] = $official_filter;
}
if (!empty($date_start)) {
    $where_clauses[] = "exam_date >= ?";
    $params[] = $date_start;
}
if (!empty($date_end)) {
    $where_clauses[] = "exam_date <= ?";
    $params[] = $date_end;
}

$where_str = count($where_clauses) > 0 ? " WHERE " . implode(" AND ", $where_clauses) : "";

// Alt sorgu ile birleştirilmiş tablo yapısı
$final_sql = "
    SELECT * FROM (
        SELECT ec.id as source_id, ec.title, ec.exam_type, ec.exam_date, 1 as is_official, 
               b.name as brand_name, ec.status, 'calendar' as source_table
        FROM exam_calendar ec 
        LEFT JOIN brands b ON ec.brand_id = b.id 
        WHERE ec.is_official = 1

        UNION ALL

        SELECT p.id as source_id, p.name as title, p.exam_type, p.exam_date, 0 as is_official, 
               b.name as brand_name, p.status, 'product' as source_table
        FROM products p 
        LEFT JOIN brands b ON p.brand_id = b.id 
        WHERE p.type = 'single_exam' AND p.exam_date IS NOT NULL
    ) as combined_table
    $where_str
    ORDER BY $sort_by $order
    LIMIT $limit OFFSET $offset
";

$stmt = $db->prepare($final_sql);
$stmt->execute($params);
$takvim = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Toplam kayıt sayısını bulma (Sayfalama için)
$count_sql = "SELECT COUNT(*) FROM (
    SELECT ec.title, ec.exam_type, ec.exam_date, ec.is_official FROM exam_calendar ec WHERE ec.is_official = 1
    UNION ALL
    SELECT p.name, p.exam_type, p.exam_date, 0 as is_official FROM products p WHERE p.type = 'single_exam' AND p.exam_date IS NOT NULL
) as count_table $where_str";
$count_stmt = $db->prepare($count_sql);
$count_stmt->execute($params);
$total_rows = $count_stmt->fetchColumn();
$total_pages = ceil($total_rows / $limit);

$page_title = "Sınav Takvimi Yönetimi";
require_once '../header.php';
?>

<div class="container-fluid px-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h1 class="mt-4">Sınav ve Deneme Takvimi</h1>
        <a href="ekle.php" class="btn btn-primary shadow-sm fw-bold"><i class="bi bi-plus-lg"></i> Yeni Resmi Sınav Ekle</a>
    </div>

    <div class="card mb-4 border-0 shadow-sm rounded-4 overflow-hidden">
        <div class="card-body bg-light">
            <form method="GET" class="row g-3">
                <div class="col-md-2">
                    <label class="small fw-bold text-muted">Kelime Ara</label>
                    <input type="text" name="q" class="form-control form-control-sm" placeholder="Ara..." value="<?= htmlspecialchars($search) ?>">
                </div>
                <div class="col-md-2">
                    <label class="small fw-bold text-muted">Sınav Türü</label>
                    <select name="type" class="form-select form-select-sm">
                        <option value="">Tümü</option>
                        <option value="TYT" <?= $type_filter == 'TYT' ? 'selected' : '' ?>>TYT</option>
                        <option value="AYT" <?= $type_filter == 'AYT' ? 'selected' : '' ?>>AYT</option>
                        <option value="LGS" <?= $type_filter == 'LGS' ? 'selected' : '' ?>>LGS</option>
                        <option value="AGS" <?= $type_filter == 'AGS' ? 'selected' : '' ?>>AGS</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="small fw-bold text-muted">Nitelik</label>
                    <select name="official" class="form-select form-select-sm">
                        <option value="">Tümü</option>
                        <option value="1" <?= $official_filter === '1' ? 'selected' : '' ?>>Sadece Resmi</option>
                        <option value="0" <?= $official_filter === '0' ? 'selected' : '' ?>>Sadece Yayın</option>
                    </select>
                </div>
                <div class="col-md-2">
                    <label class="small fw-bold text-muted">Başlangıç Tarihi</label>
                    <input type="date" name="start" class="form-control form-control-sm" value="<?= $date_start ?>">
                </div>
                <div class="col-md-2">
                    <label class="small fw-bold text-muted">Bitiş Tarihi</label>
                    <input type="date" name="end" class="form-control form-control-sm" value="<?= $date_end ?>">
                </div>
                <div class="col-md-2 d-flex align-items-end gap-1">
                    <button type="submit" class="btn btn-sm btn-primary w-100 fw-bold">Uygula</button>
                    <a href="index.php" class="btn btn-sm btn-outline-secondary w-100 fw-bold">Temizle</a>
                </div>
            </form>
        </div>
    </div>

    <div class="card mb-4 shadow-sm border-0 rounded-4 overflow-hidden">
        <div class="card-body p-0 table-responsive">
            <table class="table table-hover align-middle mb-0">
                <thead class="table-dark">
                    <tr>
                        <th class="ps-3"><a href="?sort=exam_date&order=<?= $order == 'ASC' ? 'DESC' : 'ASC' ?>&q=<?= $search ?>&type=<?= $type_filter ?>&official=<?= $official_filter ?>&start=<?= $date_start ?>&end=<?= $date_end ?>" class="text-white text-decoration-none">Tarih <?= $sort_by == 'exam_date' ? ($order == 'ASC' ? '↑' : '↓') : '' ?></a></th>
                        <th><a href="?sort=exam_type&order=<?= $order == 'ASC' ? 'DESC' : 'ASC' ?>&q=<?= $search ?>&type=<?= $type_filter ?>&official=<?= $official_filter ?>&start=<?= $date_start ?>&end=<?= $date_end ?>" class="text-white text-decoration-none">Tür <?= $sort_by == 'exam_type' ? ($order == 'ASC' ? '↑' : '↓') : '' ?></a></th>
                        <th>Başlık</th>
                        <th>Nitelik</th>
                        <th>Durum</th>
                        <th class="text-end pe-3">İşlemler</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if(count($takvim) > 0): ?>
                        <?php foreach ($takvim as $row): ?>
                            <tr>
                                <td class="ps-3 fw-bold"><?= date('d.m.Y', strtotime($row['exam_date'])) ?></td>
                                <td><span class="badge bg-secondary rounded-pill px-3"><?= htmlspecialchars($row['exam_type'] ?? '-') ?></span></td>
                                <td>
                                    <div class="fw-bold"><?= htmlspecialchars($row['title']) ?></div>
                                    <?php if($row['source_table'] == 'product'): ?>
                                        <span class="badge bg-light text-muted border" style="font-size: 0.6rem;"><i class="bi bi-shop me-1"></i>Mağaza Ürünü</span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?php if ($row['is_official'] == 1): ?>
                                        <span class="badge bg-danger bg-opacity-10 text-danger border border-danger border-opacity-25 px-2 py-1"><i class="bi bi-bank me-1"></i> Resmi Sınav</span>
                                    <?php else: ?>
                                        <span class="badge bg-info bg-opacity-10 text-info border border-info border-opacity-25 px-2 py-1"><i class="bi bi-journal-bookmark me-1"></i> <?= htmlspecialchars($row['brand_name'] ?? 'Yayın') ?></span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <?= $row['status'] == 1 ? '<span class="badge bg-success-soft text-success"><i class="bi bi-check-circle me-1"></i>Aktif</span>' : '<span class="badge bg-secondary-soft text-muted"><i class="bi bi-eye-slash me-1"></i>Pasif</span>' ?>
                                </td>
                                <td class="text-end pe-3">
                                    <div class="btn-group shadow-sm border rounded-pill overflow-hidden bg-white">
                                        <?php if($row['source_table'] == 'calendar'): ?>
                                            <a href="duzenle.php?id=<?= $row['source_id'] ?>" class="btn btn-sm btn-white text-warning border-end" title="Düzenle"><i class="bi bi-pencil-square"></i></a>
                                            <a href="sil.php?id=<?= $row['source_id'] ?>" class="btn btn-sm btn-white text-danger" onclick="return confirm('Bu takvim kaydını silmek istediğinize emin misiniz?');" title="Sil"><i class="bi bi-trash"></i></a>
                                        <?php else: ?>
                                            <a href="../urunler/duzenle.php?id=<?= $row['source_id'] ?>" class="btn btn-sm btn-white text-primary px-3 fw-bold" title="Ürün Detayına Git">Ürünü Yönet <i class="bi bi-arrow-right-short"></i></a>
                                        <?php endif; ?>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <tr>
                            <td colspan="6" class="text-center py-5 text-muted">
                                <i class="bi bi-search fs-2 d-block mb-2 opacity-50"></i>
                                Aradığınız kriterlere uygun kayıt bulunamadı.
                            </td>
                        </tr>
                    <?php endif; ?>
                </tbody>
            </table>
        </div>
    </div>

    <?php if($total_pages > 1): ?>
    <nav class="pb-5">
        <ul class="pagination pagination-sm justify-content-center">
            <li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
                <a class="page-link" href="?page=<?= $page-1 ?>&q=<?= $search ?>&type=<?= $type_filter ?>&official=<?= $official_filter ?>&start=<?= $date_start ?>&end=<?= $date_end ?>&sort=<?= $sort_by ?>&order=<?= $order ?>">Geri</a>
            </li>
            <?php for($i=1; $i<=$total_pages; $i++): ?>
                <li class="page-item <?= $i == $page ? 'active' : '' ?>">
                    <a class="page-link shadow-none" href="?page=<?= $i ?>&q=<?= $search ?>&type=<?= $type_filter ?>&official=<?= $official_filter ?>&start=<?= $date_start ?>&end=<?= $date_end ?>&sort=<?= $sort_by ?>&order=<?= $order ?>"><?= $i ?></a>
                </li>
            <?php endfor; ?>
            <li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
                <a class="page-link" href="?page=<?= $page+1 ?>&q=<?= $search ?>&type=<?= $type_filter ?>&official=<?= $official_filter ?>&start=<?= $date_start ?>&end=<?= $date_end ?>&sort=<?= $sort_by ?>&order=<?= $order ?>">İleri</a>
            </li>
        </ul>
    </nav>
    <?php endif; ?>
</div>

<style>
    .bg-success-soft { background-color: #e8f5e9; }
    .bg-secondary-soft { background-color: #f8f9fa; }
    .table thead th { font-weight: 600; font-size: 0.8rem; text-transform: uppercase; letter-spacing: 0.5px; border-top: none; }
    .btn-white { background: white; border: none; }
    .btn-white:hover { background: #f8f9fa; }
    .page-link { border-radius: 5px; margin: 0 2px; color: #333; }
    .page-item.active .page-link { background-color: #212529; border-color: #212529; }
</style>

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