<?php
require_once $_SERVER['DOCUMENT_ROOT'] . '/admin/system/includes/AdminCheck.php';
?>
<?php
require $_SERVER['DOCUMENT_ROOT'] . '/admin/system/includes/Header.php';
?>

<!-- BEGIN: Content-->
<div class="app-content content ">
    <div class="content-overlay"></div>
    <div class="header-navbar-shadow"></div>
    <div class="content-wrapper container-xxl p-0">
        <div class="content-header row">
            <div class="content-header-left col-md-9 col-12 mb-2">
                <div class="row breadcrumbs-top">
                    <div class="col-12">
                        <h2 class="content-header-title float-start mb-0">Özel Günler Takvimi</h2>
                        <div class="breadcrumb-wrapper">
                            <ol class="breadcrumb">
                                <li class="breadcrumb-item"><a href="/admin/home">Anasayfa</a>
                                </li>
                                <li class="breadcrumb-item"><a href="/admin/special-days">Özel Günler</a>
                                </li>
                                <li class="breadcrumb-item active">Takvim Görünümü
                                </li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="content-body">
            <section>
                <div class="row">
                    <div class="col-md-8 col-12">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Özel Günler Takvimi</h4>
                                <div class="btn-group">
                                    <button class="btn btn-outline-primary" id="btn-month-view">Ay</button>
                                    <button class="btn btn-outline-primary" id="btn-week-view">Hafta</button>
                                    <button class="btn btn-outline-primary" id="btn-day-view">Gün</button>
                                </div>
                            </div>
                            <div class="card-body">
                                <div id="special-days-calendar" class="calendar-wrapper"></div>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-4 col-12">
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Kategoriler</h4>
                                <a href="/admin/special-day-categories" class="btn btn-sm btn-outline-primary">Kategorileri Yönet</a>
                            </div>
                            <div class="card-body">
                                <ul class="list-group" id="category-list">
                                    <?php
                                    $categoriesQuery = $DB->query("SELECT * FROM special_day_categories ORDER BY name ASC");
                                    if ($categoriesQuery->rowCount() > 0) {
                                        while ($category = $categoriesQuery->fetch(PDO::FETCH_ASSOC)) {
                                    ?>
                                        <li class="list-group-item d-flex justify-content-between align-items-center">
                                            <div>
                                                <span class="badge rounded-pill me-1" style="background-color: <?= $category['color'] ?>">&nbsp;</span>
                                                <?= htmlspecialchars($category['name']) ?>
                                            </div>
                                            <div class="form-check form-switch">
                                                <input class="form-check-input category-toggle" type="checkbox" 
                                                    id="category-<?= $category['code'] ?>" 
                                                    data-category="<?= $category['code'] ?>" 
                                                    checked>
                                            </div>
                                        </li>
                                    <?php 
                                        }
                                    } else {
                                        echo '<li class="list-group-item text-center">Henüz kategori eklenmemiş</li>';
                                    }
                                    ?>
                                </ul>
                                <hr>
                                <div class="d-grid gap-2 mt-2">
                                    <a href="/admin/special-day-add" class="btn btn-primary">
                                        <i data-feather="plus"></i> Yeni Özel Gün Ekle
                                    </a>
                                    <a href="/admin/special-days" class="btn btn-outline-secondary">
                                        <i data-feather="list"></i> Liste Görünümü
                                    </a>
                                </div>
                            </div>
                        </div>
                        <div class="card">
                            <div class="card-header">
                                <h4 class="card-title">Gelecek Özel Günler</h4>
                            </div>
                            <div class="card-body">
                                <ul class="timeline">
                                    <?php
                                    $upcomingQuery = $DB->query("SELECT sd.*, sdc.name as category_name, sdc.color as category_color 
                                                               FROM special_days sd 
                                                               LEFT JOIN special_day_categories sdc ON sd.category = sdc.code
                                                               WHERE sd.end_date >= CURDATE() AND sd.status = 1
                                                               ORDER BY sd.start_date ASC
                                                               LIMIT 5");
                                    
                                    if ($upcomingQuery->rowCount() > 0) {
                                        while ($upcoming = $upcomingQuery->fetch(PDO::FETCH_ASSOC)) {
                                            $diffDays = (strtotime($upcoming['start_date']) - time()) / (60 * 60 * 24);
                                            $badge = $diffDays <= 7 ? 'badge-light-danger' : ($diffDays <= 30 ? 'badge-light-warning' : 'badge-light-info');
                                    ?>
                                        <li class="timeline-item">
                                            <span class="timeline-point timeline-point-indicator" style="background-color: <?= $upcoming['category_color'] ?? '#7367f0' ?>"></span>
                                            <div class="timeline-event">
                                                <div class="d-flex justify-content-between flex-sm-row flex-column mb-sm-0 mb-1">
                                                    <h6><?= htmlspecialchars($upcoming['title']) ?></h6>
                                                    <span class="timeline-event-time"><?= date('d.m.Y', strtotime($upcoming['start_date'])) ?></span>
                                                </div>
                                                <p><?= htmlspecialchars($upcoming['description']) ?></p>
                                                <div class="d-flex">
                                                    <span class="badge rounded-pill <?= $badge ?> me-1">
                                                        <?= ceil($diffDays) ?> gün sonra
                                                    </span>
                                                    <span class="badge rounded-pill badge-light-primary">
                                                        <?= $upcoming['start_time'] ?>-<?= $upcoming['end_time'] ?>
                                                    </span>
                                                </div>
                                            </div>
                                        </li>
                                    <?php 
                                        }
                                    } else {
                                        echo '<p class="text-center">Yaklaşan özel gün bulunmuyor.</p>';
                                    }
                                    ?>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </section>
        </div>
    </div>
</div>
<!-- END: Content-->

<!-- Özel Gün Detayları Modal -->
<div class="modal fade" id="viewSpecialDayModal" tabindex="-1" aria-labelledby="viewSpecialDayModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="viewSpecialDayModalLabel">Özel Gün Detayları</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Kapat"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <h3 id="eventTitle" class="mb-1"></h3>
                    <p id="eventDescription" class="text-muted"></p>
                </div>
                <div class="row mb-3">
                    <div class="col-md-6">
                        <h6>Tarih Aralığı</h6>
                        <p id="eventDateRange"></p>
                    </div>
                    <div class="col-md-6">
                        <h6>Mesai Saatleri</h6>
                        <p id="eventTimeRange"></p>
                    </div>
                </div>
                <div class="row mb-3">
                    <div class="col-md-6">
                        <h6>Kategori</h6>
                        <p id="eventCategory"></p>
                    </div>
                    <div class="col-md-6">
                        <h6>Durum</h6>
                        <p id="eventStatus"></p>
                    </div>
                </div>
                <div id="repeatSection" class="mb-3" style="display:none;">
                    <h6>Tekrarlama</h6>
                    <p id="eventRepeat"></p>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">Kapat</button>
                <a href="#" id="editEventBtn" class="btn btn-primary">Düzenle</a>
            </div>
        </div>
    </div>
</div>

<link href="https://cdn.jsdelivr.net/npm/fullcalendar@5.10.0/main.min.css" rel="stylesheet" />
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.8.1/font/bootstrap-icons.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/tippy.js@6.3.7/themes/light.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@5.10.0/main.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/fullcalendar@5.10.0/locales-all.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.2/dist/umd/popper.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/tippy.js@6.3.7/dist/tippy-bundle.umd.min.js"></script>
<style>
    .fc-license-message {
        display: none !important;
    }
    .calendar-wrapper {
        width: 100%;
        overflow: visible;
    }
    .fc-view-harness {
        min-height: 650px !important;
    }
    .fc {
        width: 100% !important; 
        max-width: 100%;
    }
    .fc-media-screen {
        width: 100%;
    }
    .fc-event {
        cursor: pointer;
        border-left: 4px solid;
        padding: 5px;
        white-space: normal !important;
        margin: 2px 0 !important;
    }
    .fc-event-time {
        font-weight: bold;
    }
    .fc-event-content {
        padding: 3px;
    }
    .fc-daygrid-day.fc-day-today {
        background-color: rgba(115, 103, 240, 0.1) !important;
    }
    .fc .fc-button-primary {
        background-color: #7367f0;
        border-color: #7367f0;
    }
    .fc .fc-button-primary:hover {
        background-color: #5e50ee;
        border-color: #5e50ee;
    }
    .fc .fc-button-primary:disabled {
        background-color: #7367f0;
        border-color: #7367f0;
        opacity: 0.65;
    }
    .fc-scrollgrid-sync-inner a {
        color: #5e5873;
    }
    .fc-day-today .fc-scrollgrid-sync-inner a {
        color: #7367f0;
        font-weight: bold;
    }
</style>
<script src="//cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
    document.addEventListener('DOMContentLoaded', function() {
        // FullCalendar'ı başlat
        var calendarEl = document.getElementById('special-days-calendar');
        var calendar = new FullCalendar.Calendar(calendarEl, {
            height: 'auto',
            contentHeight: 650,
            themeSystem: 'bootstrap5',
            initialView: 'dayGridMonth',
            headerToolbar: {
                left: 'prev,next today',
                center: 'title',
                right: ''
            },
            editable: true,
            eventDidMount: function(info) {
                // Etkinliği monte ederken ekstra içerik ekle
                if (!info.event || !info.event.extendedProps) {
                    console.error("Etkinlikte props bulunamadı:", info.event);
                    return;
                }
                
                const props = info.event.extendedProps;
                const el = info.el;
                
                // Etkinlik başlığını ve zamanını içeren div
                const contentDiv = document.createElement('div');
                contentDiv.className = 'fc-event-main-frame';
                
                // Güvenli değerler için kontrol
                const startTime = props.startTime || '00:00';
                const endTime = props.endTime || '00:00';
                const categoryName = props.categoryName || 'Varsayılan';
                const title = info.event.title || 'İsimsiz Etkinlik';
                
                contentDiv.innerHTML = `
                    <div class="fc-event-time">${startTime} - ${endTime}</div>
                    <div class="fc-event-title-container">
                        <div class="fc-event-title">${title}</div>
                        <div class="small text-white-50">${categoryName}</div>
                    </div>
                `;
                
                // Mevcut içeriği temizleyip yeni içeriği ekle
                const mainElement = el.querySelector('.fc-event-main');
                if (mainElement) {
                    mainElement.innerHTML = '';
                    mainElement.appendChild(contentDiv);
                }
                
                // Güvenli değerler için tooltip
                const description = props.description || 'Açıklama yok';
                const formattedStartDate = props.formattedStartDate || '-';
                const formattedEndDate = props.formattedEndDate || '-';
                
                // Tooltip ekle
                try {
                    tippy(el, {
                        content: `
                            <div class="p-1">
                                <b>${title}</b><br>
                                <small>${description}</small><br>
                                <span>${formattedStartDate} - ${formattedEndDate}</span><br>
                                <span>${startTime} - ${endTime}</span>
                            </div>
                        `,
                        allowHTML: true,
                        theme: 'light',
                        animation: 'scale',
                        delay: [150, 0]
                    });
                } catch (err) {
                    console.error("Tooltip oluşturma hatası:", err);
                }
            },
            eventTimeFormat: {
                hour: '2-digit',
                minute: '2-digit',
                meridiem: false,
                hour12: false
            },
            events: {
                url: '/admin/eral?getSpecialDaysForCalendar=1',
                failure: function(error) {
                    console.error("Özel günler yüklenirken hata:", error);
                    Swal.fire({
                        title: "Veri Hatası",
                        text: "Özel günler yüklenirken bir hata oluştu: " + error.message,
                        icon: 'warning',
                        confirmButtonColor: '#7367f0',
                        confirmButtonText: "Tamam"
                    });
                },
                extraParams: function() {
                    // Her istekte önbelleği engellemek için rastgele bir değer ekle
                    return {
                        _: new Date().getTime()
                    };
                }
            },
            loading: function(isLoading) {
                if (isLoading) {
                    // Takvim yüklenirken yükleniyor göstergesi ekle
                    var loadingEl = document.createElement('div');
                    loadingEl.id = 'calendar-loading';
                    loadingEl.className = 'text-center p-3';
                    loadingEl.innerHTML = '<div class="spinner-border text-primary" role="status"><span class="visually-hidden">Yükleniyor...</span></div><p class="mt-2">Takvim yükleniyor...</p>';
                    document.getElementById('special-days-calendar').prepend(loadingEl);
                } else {
                    // Yükleme tamamlandığında göstergeyi kaldır
                    var loadingEl = document.getElementById('calendar-loading');
                    if (loadingEl) {
                        loadingEl.remove();
                    }
                    
                    // Etkinliklerin doğru yüklenip yüklenmediğini kontrol et
                    // Önce mevcut uyarıyı temizle (eğer varsa)
                    var existingAlert = document.querySelector('.fc-view-harness .alert');
                    if (existingAlert) {
                        existingAlert.remove();
                    }
                    
                    // Gerçekten hiç etkinlik yoksa uyarı göster
                    if (calendar.getEvents().length === 0) {
                        var noEventsEl = document.createElement('div');
                        noEventsEl.className = 'alert alert-info m-3';
                        noEventsEl.innerHTML = 'Henüz hiç özel gün eklenmemiş. Özel günleri görmek için yeni bir özel gün ekleyin.';
                        document.querySelector('.fc-view-harness').appendChild(noEventsEl);
                    }
                }
            },
            locale: 'tr',
            firstDay: 1, // Pazartesi'den başla
            buttonText: {
                today: 'Bugün',
                month: 'Ay',
                week: 'Hafta',
                day: 'Gün',
                list: 'Liste'
            },
            eventClick: function(info) {
                try {
                    // Özel gün detaylarını göster
                    const event = info.event;
                    if (!event || !event.extendedProps) {
                        console.error("Etkinlik verisi eksik:", event);
                        Swal.fire({
                            title: "Veri Hatası",
                            text: "Etkinlik detayları alınamadı.",
                            icon: 'warning',
                            confirmButtonColor: '#7367f0',
                            confirmButtonText: "Tamam"
                        });
                        return;
                    }
                    
                    const extendedProps = event.extendedProps;
                    
                    // Güvenli değerler al
                    const title = event.title || 'İsimsiz Etkinlik';
                    const description = extendedProps.description || 'Açıklama yok';
                    const startDate = extendedProps.formattedStartDate || '-';
                    const endDate = extendedProps.formattedEndDate || '-';
                    const startTime = extendedProps.startTime || '00:00';
                    const endTime = extendedProps.endTime || '00:00';
                    const categoryName = extendedProps.categoryName || 'Varsayılan';
                    const categoryColor = extendedProps.categoryColor || '#7367f0';
                    const status = typeof extendedProps.status !== 'undefined' ? extendedProps.status : 0;
                    
                    // Modal'ı doldur
                    document.getElementById('eventTitle').textContent = title;
                    document.getElementById('eventDescription').textContent = description;
                    document.getElementById('eventDateRange').textContent = `${startDate} - ${endDate}`;
                    document.getElementById('eventTimeRange').textContent = `${startTime} - ${endTime}`;
                    
                    // Kategori
                    const categorySpan = document.createElement('span');
                    categorySpan.className = 'badge rounded-pill';
                    categorySpan.style.backgroundColor = categoryColor;
                    categorySpan.textContent = categoryName;
                    document.getElementById('eventCategory').innerHTML = '';
                    document.getElementById('eventCategory').appendChild(categorySpan);
                    
                    // Durum
                    const statusSpan = document.createElement('span');
                    statusSpan.className = 'badge rounded-pill';
                    statusSpan.className += status === 1 ? ' badge-light-success' : ' badge-light-danger';
                    statusSpan.textContent = status === 1 ? 'Aktif' : 'Pasif';
                    document.getElementById('eventStatus').innerHTML = '';
                    document.getElementById('eventStatus').appendChild(statusSpan);
                    
                    // Tekrarlama bilgisi
                    const repeatSection = document.getElementById('repeatSection');
                    const eventRepeat = document.getElementById('eventRepeat');
                    
                    if (extendedProps.repeatType && extendedProps.repeatType !== 'none') {
                        repeatSection.style.display = 'block';
                        
                        const repeatInterval = extendedProps.repeatInterval || 1;
                        const repeatUntil = extendedProps.repeatUntil || null;
                        
                        let repeatText = '';
                        switch(extendedProps.repeatType) {
                            case 'daily':
                                repeatText = `Her ${repeatInterval} günde bir`;
                                break;
                            case 'weekly':
                                repeatText = `Her ${repeatInterval} haftada bir`;
                                break;
                            case 'monthly':
                                repeatText = `Her ${repeatInterval} ayda bir`;
                                break;
                            case 'yearly':
                                repeatText = `Her ${repeatInterval} yılda bir`;
                                break;
                            default:
                                repeatText = 'Tekrarlanmıyor';
                        }
                        
                        if (repeatUntil) {
                            repeatText += ` (${repeatUntil} tarihine kadar)`;
                        }
                        
                        eventRepeat.textContent = repeatText;
                    } else {
                        repeatSection.style.display = 'none';
                    }
                    
                    // Düzenleme linki
                    const eventId = extendedProps.id || 0;
                    if (eventId > 0) {
                        document.getElementById('editEventBtn').href = `/admin/special-day/${eventId}`;
                        document.getElementById('editEventBtn').style.display = 'block';
                    } else {
                        document.getElementById('editEventBtn').style.display = 'none';
                    }
                    
                    // Modal'ı göster
                    const modal = document.getElementById('viewSpecialDayModal');
                    if (window.bootstrap && bootstrap.Modal) {
                        const modalInstance = new bootstrap.Modal(modal);
                        modalInstance.show();
                    } else {
                        $('#viewSpecialDayModal').modal('show');
                    }
                } catch (error) {
                    console.error("Etkinlik detayları gösterilirken hata:", error);
                    Swal.fire({
                        title: "Hata",
                        text: "Etkinlik detayları gösterilirken bir hata oluştu.",
                        icon: 'error',
                        confirmButtonColor: '#7367f0',
                        confirmButtonText: "Tamam"
                    });
                }
            },
            eventDrop: function(info) {
                // Tarihi değiştir
                const event = info.event;
                const id = event.extendedProps.id;
                const newStartDate = event.start.toISOString().split('T')[0];
                const endDate = event.end ? event.end.toISOString().split('T')[0] : newStartDate;
                
                $.ajax({
                    type: 'post',
                    url: '/admin/eral',
                    data: {
                        updateSpecialDayDates: 1,
                        id: id,
                        start_date: newStartDate,
                        end_date: endDate
                    },
                    success: function(response) {
                        if (response === 'OK') {
                            Swal.fire({
                                title: "Başarılı!",
                                text: "Tarih aralığı güncellendi.",
                                icon: 'success',
                                confirmButtonColor: '#7367f0',
                                confirmButtonText: "Tamam",
                                timer: 1500,
                                timerProgressBar: true
                            });
                        } else {
                            Swal.fire({
                                title: "Hata!",
                                text: "Güncelleme sırasında bir hata oluştu.",
                                icon: 'error',
                                confirmButtonColor: '#7367f0',
                                confirmButtonText: "Tamam"
                            });
                            info.revert();
                        }
                    },
                    error: function() {
                        info.revert();
                        Swal.fire({
                            title: "Hata!",
                            text: "Bağlantı hatası oluştu.",
                            icon: 'error',
                            confirmButtonColor: '#7367f0',
                            confirmButtonText: "Tamam"
                        });
                    }
                });
            }
        });
        
        calendar.render();
        
        // Görünüm butonlarına tıklama işlemleri
        document.getElementById('btn-month-view').addEventListener('click', function() {
            calendar.changeView('dayGridMonth');
            updateViewButtons('btn-month-view');
        });
        
        document.getElementById('btn-week-view').addEventListener('click', function() {
            calendar.changeView('timeGridWeek');
            updateViewButtons('btn-week-view');
        });
        
        document.getElementById('btn-day-view').addEventListener('click', function() {
            calendar.changeView('timeGridDay');
            updateViewButtons('btn-day-view');
        });
        
        // Başlangıçta ay görünümü aktif
        updateViewButtons('btn-month-view');
        
        // Lisans uyarısını gizle
        setTimeout(function() {
            const licenseWarnings = document.querySelectorAll('.fc-license-message');
            if (licenseWarnings) {
                licenseWarnings.forEach(el => el.style.display = 'none');
            }
        }, 100);
        
        // Kategori filtreleme
        document.querySelectorAll('.category-toggle').forEach(function(toggle) {
            toggle.addEventListener('change', function() {
                const category = this.dataset.category;
                const checked = this.checked;
                
                if (checked) {
                    // Kategoriyi göster
                    calendar.getEvents().forEach(function(event) {
                        if (event.extendedProps.category === category) {
                            event.setProp('display', 'auto');
                        }
                    });
                } else {
                    // Kategoriyi gizle
                    calendar.getEvents().forEach(function(event) {
                        if (event.extendedProps.category === category) {
                            event.setProp('display', 'none');
                        }
                    });
                }
            });
        });
        
        // Görünüm butonlarını güncelleme
        function updateViewButtons(activeButtonId) {
            document.querySelectorAll('#btn-month-view, #btn-week-view, #btn-day-view').forEach(function(button) {
                button.classList.remove('btn-primary');
                button.classList.add('btn-outline-primary');
            });
            
            document.getElementById(activeButtonId).classList.remove('btn-outline-primary');
            document.getElementById(activeButtonId).classList.add('btn-primary');
        }
    });
</script>

<?php
require $_SERVER['DOCUMENT_ROOT'] . '/admin/system/includes/Footer.php';
?>