/* =====================================================
   DALTON PANEL - JAVASCRIPT
===================================================== */

// Matrix Arka Plan Animasyonu
class MatrixBackground {
    constructor(canvasId) {
        this.canvas = document.getElementById(canvasId);
        if (!this.canvas) return;
        
        this.ctx = this.canvas.getContext('2d');
        this.characters = 'DALTON0123456789@#$%^&*()アイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワヲン';
        this.fontSize = 14;
        this.columns = 0;
        this.drops = [];
        
        this.init();
        this.animate();
        
        window.addEventListener('resize', () => this.init());
    }
    
    init() {
        this.canvas.width = window.innerWidth;
        this.canvas.height = window.innerHeight;
        this.columns = Math.floor(this.canvas.width / this.fontSize);
        this.drops = Array(this.columns).fill(1);
    }
    
    animate() {
        // Yarı saydam siyah ile önceki kareleri soldur
        this.ctx.fillStyle = 'rgba(5, 5, 16, 0.05)';
        this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
        
        // Turuncu/altın tonlarında matrix karakterleri
        this.ctx.fillStyle = '#FF8C00';
        this.ctx.font = `${this.fontSize}px monospace`;
        
        for (let i = 0; i < this.drops.length; i++) {
            const char = this.characters[Math.floor(Math.random() * this.characters.length)];
            const x = i * this.fontSize;
            const y = this.drops[i] * this.fontSize;
            
            // Rastgele parlaklık efekti
            if (Math.random() > 0.95) {
                this.ctx.fillStyle = '#FFB347';
            } else {
                this.ctx.fillStyle = 'rgba(255, 140, 0, 0.8)';
            }
            
            this.ctx.fillText(char, x, y);
            
            // Sütunu sıfırla veya devam et
            if (y > this.canvas.height && Math.random() > 0.975) {
                this.drops[i] = 0;
            }
            this.drops[i]++;
        }
        
        requestAnimationFrame(() => this.animate());
    }
}

// Sayfa yüklendiğinde matrix'i başlat
document.addEventListener('DOMContentLoaded', () => {
    new MatrixBackground('matrix-bg');
});

/* =====================================================
   TAB SİSTEMİ
===================================================== */
function initTabs() {
    const tabBtns = document.querySelectorAll('.tab-btn');
    const tabPanes = document.querySelectorAll('.tab-pane');
    
    tabBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const target = btn.dataset.tab;
            
            // Tüm tab butonlarından active'i kaldır
            tabBtns.forEach(b => b.classList.remove('active'));
            // Tıklanan butona active ekle
            btn.classList.add('active');
            
            // Tüm panellerden active'i kaldır
            tabPanes.forEach(pane => pane.classList.remove('active'));
            // Hedef paneli göster
            document.getElementById(target)?.classList.add('active');
        });
    });
}

/* =====================================================
   PLATFORM SEÇİMİ DİNAMİK FORM
===================================================== */
function initPlatformSelector() {
    const checkboxes = document.querySelectorAll('.platform-checkbox');
    const forms = document.querySelectorAll('.platform-form');
    
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', () => {
            const platform = checkbox.value;
            const form = document.getElementById(`form-${platform}`);
            
            if (checkbox.checked) {
                form?.classList.add('active');
            } else {
                form?.classList.remove('active');
            }
        });
    });
}

/* =====================================================
   TARİH SAAT GÖSTERİMİ
===================================================== */
function updateDateTime() {
    const dateTimeEl = document.getElementById('datetime');
    if (!dateTimeEl) return;
    
    const now = new Date();
    const options = {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
        hour12: false
    };
    
    dateTimeEl.textContent = now.toLocaleString('tr-TR', options);
}

// Her saniye güncelle
setInterval(updateDateTime, 1000);
document.addEventListener('DOMContentLoaded', updateDateTime);

/* =====================================================
   LOG OTOMATİK YENİLEME (6 SANİYE)
===================================================== */
let logRefreshInterval = null;

function startLogRefresh() {
    if (logRefreshInterval) return;
    
    logRefreshInterval = setInterval(() => {
        refreshLogs();
    }, 6000);
}

function stopLogRefresh() {
    if (logRefreshInterval) {
        clearInterval(logRefreshInterval);
        logRefreshInterval = null;
    }
}

function refreshLogs() {
    const logContainer = document.getElementById('log-container');
    if (!logContainer) return;
    
    fetch('includes/girislog/birlesik_log.php')
        .then(response => response.text())
        .then(html => {
            logContainer.innerHTML = html;
        })
        .catch(err => console.error('Log yenileme hatası:', err));
}

/* =====================================================
   AJAX FORM GÖNDERİMİ
===================================================== */
function submitForm(formId, url, successCallback) {
    const form = document.getElementById(formId);
    if (!form) return;
    
    form.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const submitBtn = form.querySelector('[type="submit"]');
        const originalText = submitBtn?.innerHTML;
        
        if (submitBtn) {
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<span class="spinner"></span> İşleniyor...';
        }
        
        try {
            const formData = new FormData(form);
            const response = await fetch(url, {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            
            if (data.sonuc === 'tamam') {
                showAlert('success', data.mesaj || 'İşlem başarılı!');
                if (successCallback) successCallback(data);
            } else {
                showAlert('danger', data.mesaj || 'Bir hata oluştu!');
            }
        } catch (error) {
            showAlert('danger', 'Bağlantı hatası!');
            console.error(error);
        } finally {
            if (submitBtn) {
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalText;
            }
        }
    });
}

/* =====================================================
   BİLDİRİM SİSTEMİ (SweetAlert benzeri)
===================================================== */
function showAlert(type, message, duration = 3000) {
    // Mevcut alertleri kaldır
    document.querySelectorAll('.floating-alert').forEach(el => el.remove());
    
    const alert = document.createElement('div');
    alert.className = `floating-alert alert alert-${type}`;
    alert.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 9999;
        min-width: 300px;
        animation: slideInRight 0.3s ease;
    `;
    
    const icons = {
        success: '✓',
        danger: '✕',
        warning: '⚠',
        info: 'ℹ'
    };
    
    alert.innerHTML = `
        <span style="font-size: 1.3rem;">${icons[type] || 'ℹ'}</span>
        <span>${message}</span>
    `;
    
    document.body.appendChild(alert);
    
    // Otomatik kaldır
    setTimeout(() => {
        alert.style.animation = 'slideOutRight 0.3s ease';
        setTimeout(() => alert.remove(), 300);
    }, duration);
}

// CSS animasyonları ekle
const alertStyles = document.createElement('style');
alertStyles.textContent = `
    @keyframes slideInRight {
        from { transform: translateX(100%); opacity: 0; }
        to { transform: translateX(0); opacity: 1; }
    }
    @keyframes slideOutRight {
        from { transform: translateX(0); opacity: 1; }
        to { transform: translateX(100%); opacity: 0; }
    }
`;
document.head.appendChild(alertStyles);

/* =====================================================
   MODAL SİSTEMİ
===================================================== */
function openModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.add('active');
        document.body.style.overflow = 'hidden';
    }
}

function closeModal(modalId) {
    const modal = document.getElementById(modalId);
    if (modal) {
        modal.classList.remove('active');
        document.body.style.overflow = '';
    }
}

// Modal dışına tıklayınca kapat
document.addEventListener('click', (e) => {
    if (e.target.classList.contains('modal-overlay')) {
        e.target.classList.remove('active');
        document.body.style.overflow = '';
    }
});

// ESC tuşu ile kapat
document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
        document.querySelectorAll('.modal-overlay.active').forEach(modal => {
            modal.classList.remove('active');
        });
        document.body.style.overflow = '';
    }
});

/* =====================================================
   SİLME İŞLEMİ ONAY
===================================================== */
function confirmDelete(id, type, callback) {
    if (confirm('Bu kaydı silmek istediğinize emin misiniz?')) {
        fetch('includes/deletes.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: `action=${type}&id=${id}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.sonuc === 'tamam') {
                showAlert('success', 'Kayıt silindi!');
                if (callback) callback();
            } else {
                showAlert('danger', 'Silme işlemi başarısız!');
            }
        })
        .catch(() => showAlert('danger', 'Bağlantı hatası!'));
    }
}

/* =====================================================
   LİNK KOPYALAMA
===================================================== */
function copyToClipboard(text) {
    navigator.clipboard.writeText(text).then(() => {
        showAlert('success', 'Kopyalandı!', 2000);
    }).catch(() => {
        // Fallback
        const textarea = document.createElement('textarea');
        textarea.value = text;
        document.body.appendChild(textarea);
        textarea.select();
        document.execCommand('copy');
        document.body.removeChild(textarea);
        showAlert('success', 'Kopyalandı!', 2000);
    });
}

/* =====================================================
   SADECE SAYI GİRİŞİ
===================================================== */
function onlyNumbers(input) {
    input.value = input.value.replace(/[^0-9]/g, '');
}

function formatPrice(input) {
    let value = input.value.replace(/[^0-9]/g, '');
    if (value.length > 3) {
        value = value.replace(/\B(?=(\d{3})+(?!\d))/g, '.');
    }
    input.value = value;
}

/* =====================================================
   TELEFON FORMATLAMA
===================================================== */
function formatPhone(input) {
    let value = input.value.replace(/\D/g, '');
    
    if (value.length > 0) {
        if (value.length <= 1) {
            value = value;
        } else if (value.length <= 4) {
            value = `${value.slice(0, 1)} (${value.slice(1)}`;
        } else if (value.length <= 7) {
            value = `${value.slice(0, 1)} (${value.slice(1, 4)}) ${value.slice(4)}`;
        } else if (value.length <= 9) {
            value = `${value.slice(0, 1)} (${value.slice(1, 4)}) ${value.slice(4, 7)} ${value.slice(7)}`;
        } else {
            value = `${value.slice(0, 1)} (${value.slice(1, 4)}) ${value.slice(4, 7)} ${value.slice(7, 9)} ${value.slice(9, 11)}`;
        }
    }
    
    input.value = value;
}

/* =====================================================
   ARAMA FONKSİYONU
===================================================== */
function searchTable(inputId, tableId) {
    const input = document.getElementById(inputId);
    const table = document.getElementById(tableId);
    
    if (!input || !table) return;
    
    input.addEventListener('keyup', () => {
        const filter = input.value.toLowerCase();
        const rows = table.querySelectorAll('tbody tr');
        
        rows.forEach(row => {
            const text = row.textContent.toLowerCase();
            row.style.display = text.includes(filter) ? '' : 'none';
        });
    });
}

/* =====================================================
   SAYFA YÜKLENDİĞİNDE
===================================================== */
document.addEventListener('DOMContentLoaded', () => {
    initTabs();
    initPlatformSelector();
    
    // Log sekmesi açıkken otomatik yenileme başlat
    const logTab = document.querySelector('[data-tab="tab-logs"]');
    if (logTab) {
        logTab.addEventListener('click', () => {
            startLogRefresh();
            refreshLogs();
        });
    }
    
    // Diğer sekmelere geçince log yenilemeyi durdur
    document.querySelectorAll('.tab-btn:not([data-tab="tab-logs"])').forEach(btn => {
        btn.addEventListener('click', stopLogRefresh);
    });
});
