<?php
$title = lang('page_title_updates', [], 'Sistem Güncellemeleri');
$page_title = lang('page_title_updates', [], 'Sistem Güncellemeleri');

// Ayarlardan manifest url'ini oku (genel settings)
$langCode = m_get_session('admin_lang') ?: 'tr';
$manifestUrl = defined('UPDATE_MANIFEST_URL') ? UPDATE_MANIFEST_URL : (general_settings('updates_manifest_url', $langCode) ?: '');

// Mevcut sürüm
$currentVersion = general_settings('app_version', $langCode) ?: '1.0.0';

?>

<style>
.update-status {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    color: white;
    border-radius: 15px;
    padding: 25px;
    margin-bottom: 20px;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}

.update-status h5 {
    color: white;
    margin-bottom: 10px;
    font-weight: 600;
}

.version-badge {
    background: rgba(255,255,255,0.2);
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
    display: inline-block;
    margin: 5px 0;
}

.update-log {
    background: #1a1a2e;
    color: #00d4ff;
    padding: 20px;
    border-radius: 12px;
    max-height: 300px;
    overflow-y: auto;
    font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
    font-size: 13px;
    line-height: 1.5;
    border: 1px solid #2d3748;
    box-shadow: inset 0 2px 4px rgba(0,0,0,0.3);
}

.update-log::-webkit-scrollbar {
    width: 8px;
}

.update-log::-webkit-scrollbar-track {
    background: #2d3748;
    border-radius: 4px;
}

.update-log::-webkit-scrollbar-thumb {
    background: #4a5568;
    border-radius: 4px;
}

.update-log::-webkit-scrollbar-thumb:hover {
    background: #718096;
}

.btn-update {
    background: linear-gradient(45deg, #ff6b6b, #ee5a24);
    border: none;
    padding: 12px 30px;
    border-radius: 25px;
    font-weight: 600;
    font-size: 16px;
    transition: all 0.3s ease;
    box-shadow: 0 4px 15px rgba(238, 90, 36, 0.3);
}

.btn-update:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(238, 90, 36, 0.4);
    background: linear-gradient(45deg, #ee5a24, #ff6b6b);
}

.btn-update:disabled {
    background: #718096;
    box-shadow: none;
    transform: none;
}

.notes-card {
    background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
    border: none;
    border-radius: 15px;
    color: white;
    box-shadow: 0 10px 30px rgba(0,0,0,0.1);
}

.notes-card .card-title {
    color: white;
    font-weight: 600;
}

.notes-content {
    background: rgba(255,255,255,0.1);
    padding: 15px;
    border-radius: 10px;
    white-space: pre-wrap;
    font-size: 14px;
    line-height: 1.6;
    backdrop-filter: blur(10px);
}

.status-indicator {
    display: inline-flex;
    align-items: center;
    gap: 8px;
    padding: 8px 16px;
    border-radius: 20px;
    font-size: 14px;
    font-weight: 500;
}

.status-checking {
    background: rgba(255, 193, 7, 0.2);
    color: #ffc107;
}

.status-available {
    background: rgba(40, 167, 69, 0.2);
    color: #28a745;
}

.status-up-to-date {
    background: rgba(108, 117, 125, 0.2);
    color: #6c757d;
}

.spinner-custom {
    width: 16px;
    height: 16px;
    border: 2px solid rgba(255,255,255,0.3);
    border-top: 2px solid white;
    border-radius: 50%;
    animation: spin 1s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

.fade-in {
    animation: fadeIn 0.5s ease-in;
}

@keyframes fadeIn {
    from { opacity: 0; transform: translateY(20px); }
    to { opacity: 1; transform: translateY(0); }
}

.pulse {
    animation: pulse 2s infinite;
}

@keyframes pulse {
    0% { transform: scale(1); }
    50% { transform: scale(1.05); }
    100% { transform: scale(1); }
}
</style>

<div class="row">
    <div class="col-lg-12">
        <div class="card">
            <div class="card-header d-flex align-items-center justify-content-between">
                <h4 class="card-title mb-0 flex-grow-1">
                    <i class="fas fa-sync-alt me-2"></i>
                    <?= htmlspecialchars($page_title) ?>
                </h4>
            </div>
            <div class="card-body">
                <form method="post" action="<?= ADMIN_FOLDER ?>/controller/updates.php" class="row g-3" id="updatesForm">
                    <input type="hidden" name="csrf_token" value="<?= $_SESSION['csrf_token']['value'] ?>">
                    <input type="hidden" name="mode" value="ajax">
                    
                    <!-- Status Card -->
                    <div class="col-12">
                        <div class="update-status fade-in">
                            <h5><i class="fas fa-info-circle me-2"></i><?= lang('updates.status.title', [], 'Sistem Durumu') ?></h5>
                            <div class="version-badge">
                                <i class="fas fa-code-branch me-1"></i>
                                <?= lang('updates.current_version', [], 'Mevcut Sürüm') ?>: <strong><?= htmlspecialchars($currentVersion) ?></strong>
                            </div>
                            <div id="statusIndicator" class="status-indicator status-checking mt-2">
                                <div class="spinner-custom"></div>
                                <?= lang('updates.log.checking', [], 'Güncellemeler kontrol ediliyor...') ?>
                            </div>
                        </div>
                    </div>

                    <!-- Update Button -->
                    <div class="col-12 text-center">
                        <button type="button" id="btnUpdate" class="btn btn-update" disabled>
                            <i class="fas fa-download me-2"></i>
                            <?= lang('updates.update_now') ?>
                        </button>
                    </div>

                    <!-- Update Log -->
                    <div class="col-12">
                        <h6 class="mb-3">
                            <i class="fas fa-terminal me-2"></i>
                            <?= lang('updates.log.title', [], 'Güncelleme Logları') ?>
                        </h6>
                        <pre id="updateLog" class="update-log"><?= lang('updates.log.ready', [], 'Sistem hazır. Güncellemeler kontrol ediliyor...') ?></pre>
                    </div>

                    <!-- Release Notes -->
                    <div class="col-12" id="notesCard" style="display:none;">
                        <div class="card notes-card fade-in">
                            <div class="card-body">
                                <h6 class="card-title mb-3">
                                    <i class="fas fa-sticky-note me-2"></i>
                                    <?= lang('updates.notes.title', [], 'Sürüm Notları') ?>
                                </h6>
                                <div id="releaseNotes" class="notes-content"></div>
                            </div>
                        </div>
                    </div>
                </form>

                <script>
                (function(){
                    var form = document.getElementById('updatesForm');
                    var logEl = document.getElementById('updateLog');
                    var statusIndicator = document.getElementById('statusIndicator');
                    
                    function log(txt){ 
                        if (!logEl) return; 
                        logEl.textContent += '\n' + txt; 
                        logEl.scrollTop = logEl.scrollHeight; 
                    }
                    
                    function updateStatus(type, text) {
                        statusIndicator.className = 'status-indicator status-' + type;
                        statusIndicator.innerHTML = text;
                    }
                    
                    function post(action, extra){
                        var fd = new FormData(form);
                        fd.set('action', action);
                        fd.set('mode', 'ajax');
                        if (extra && extra.step) fd.set('step', extra.step);
                        return fetch('<?= ADMIN_FOLDER ?>/controller/updates.php', { 
                            method:'POST', 
                            body: fd, 
                            credentials: 'same-origin', 
                            cache: 'no-store' 
                        })
                        .then(function(r){ return r.text(); })
                        .then(function(t){ 
                            try { return JSON.parse(t); } 
                            catch(e){ return { ok:false, message:'Invalid response', raw:t }; } 
                        });
                    }
                    
                    // Sayfa açıldığında bir kez güncelleme kontrolü
                    var checkedOnce = false;
                    function runCheckOnce(){
                        if (checkedOnce) return; 
                        checkedOnce = true;
                        
                        log('<?= lang('updates.log.checking', [], 'Güncellemeler kontrol ediliyor...') ?>');
                        
                        post('check').then(function(res){
                            if(!res.ok){ 
                                log('<?= lang('updates.log.error', [], 'Hata:') ?> ' + (res.message||'failed')); 
                                updateStatus('error', '<i class="fas fa-exclamation-triangle me-1"></i>Kontrol hatası');
                                return; 
                            }
                            
                            if(res.update){
                                log('<?= lang('updates.log.available', [], 'Yeni sürüm mevcut:') ?> ' + res.latest + ' (<?= lang('updates.current_version', [], 'Mevcut sürüm') ?>: ' + res.current + ')');
                                updateStatus('available', '<i class="fas fa-arrow-up me-1"></i>Güncelleme mevcut: ' + res.latest);
                                
                                var notesWrap = document.getElementById('notesCard');
                                var notesEl = document.getElementById('releaseNotes');
                                if (res.notes && res.notes.length){ 
                                    notesEl.textContent = res.notes; 
                                    notesWrap.style.display = ''; 
                                    notesWrap.classList.add('fade-in');
                                } else { 
                                    notesWrap.style.display = 'none'; 
                                    notesEl.textContent = ''; 
                                }
                                
                                var btnUpdate = document.getElementById('btnUpdate');
                                btnUpdate.disabled = false;
                                btnUpdate.classList.add('pulse');
                            } else {
                                log('<?= lang('updates.result.up_to_date') ?> (<?= lang('updates.current_version', [], 'Mevcut sürüm') ?>: ' + res.current + ')');
                                updateStatus('up-to-date', '<i class="fas fa-check-circle me-1"></i>Güncel: ' + res.current);
                                
                                var notesWrap = document.getElementById('notesCard'); 
                                var notesEl = document.getElementById('releaseNotes'); 
                                notesWrap.style.display = 'none'; 
                                notesEl.textContent = '';
                                
                                document.getElementById('btnUpdate').disabled = true;
                            }
                        }).catch(function(){ 
                            log('<?= lang('updates.log.request_failed', [], 'İstek başarısız') ?>'); 
                            updateStatus('error', '<i class="fas fa-exclamation-triangle me-1"></i>Bağlantı hatası');
                        });
                    }
                    
                    runCheckOnce();
                    
                    document.getElementById('btnUpdate').addEventListener('click', function(){
                        var btn = this; 
                        var originalHtml = btn.innerHTML; 
                        btn.disabled = true;
                        btn.classList.remove('pulse');
                        btn.innerHTML = '<span class="spinner-custom me-2"></span><?= lang('updates.ui.updating', [], 'Güncelleniyor...') ?>';
                        
                        updateStatus('checking', '<div class="spinner-custom"></div>Güncelleme işlemi devam ediyor...');
                        log('<?= lang('updates.log.starting', [], 'Güncelleme başlatılıyor...') ?>');
                        
                        post('update', {step:'download'})
                        .then(function(res){ 
                            if(!res.ok){ 
                                log('<?= lang('updates.log.download_error', [], 'İndirme hatası:') ?> ' + (res.message||'failed')); 
                                throw new Error('download'); 
                            } 
                            log('<?= lang('updates.log.downloaded', [], 'Paket indirildi. Çıkartılıyor...') ?>'); 
                            return post('update', {step:'extract'}); 
                        })
                        .then(function(res){ 
                            if(!res.ok){ 
                                log('<?= lang('updates.log.extract_error', [], 'Çıkarma hatası:') ?> ' + (res.message||'failed')); 
                                throw new Error('extract'); 
                            } 
                            log('<?= lang('updates.log.extracted', [], 'Dosyalar çıkarıldı. Sonlandırılıyor...') ?>'); 
                            return post('update', {step:'finalize'}); 
                        })
                        .then(function(res){ 
                            if(!res.ok){ 
                                log('<?= lang('updates.log.finalize_error', [], 'Sonlandırma hatası:') ?> ' + (res.message||'failed') + (res.error ? (' :: ' + res.error) : '')); 
                                btn.disabled = false; 
                                btn.innerHTML = originalHtml; 
                                updateStatus('error', '<i class="fas fa-exclamation-triangle me-1"></i>Güncelleme hatası');
                                return; 
                            } 
                            log('<?= lang('updates.log.completed', [], 'Güncelleme başarıyla tamamlandı.') ?>'); 
                            log('<?= lang('updates.log.db_saved', [], 'Kaydedildi:') ?> ' + (res.key||'-') + ' => ' + (res.latest||'-')); 
                            updateStatus('available', '<i class="fas fa-check-circle me-1"></i>Güncelleme tamamlandı!');
                            return post('get_current'); 
                        })
                        .then(function(res){ 
                            if(res && res.ok){ 
                                log('<?= lang('updates.log.db_check', [], 'DB kontrol:') ?> ' + (res.key||'-') + ' => ' + (res.value||'-')); 
                                setTimeout(function(){ location.reload(); }, 1500); 
                            } 
                        })
                        .catch(function(){ 
                            btn.disabled = false; 
                            btn.innerHTML = originalHtml; 
                            updateStatus('error', '<i class="fas fa-exclamation-triangle me-1"></i>İşlem hatası');
                        });
                    });
                })();
                </script>
                
                <?php if (isset($_SESSION['formSuccess'])): ?>
                    <div class="mt-3">
                        <?php if ($_SESSION['formSuccess']): ?>
                            <div class="alert alert-success mb-0"><?= $_SESSION['success_message'] ?></div>
                        <?php else: ?>
                            <div class="alert alert-danger mb-0"><?= $_SESSION['error_message'] ?></div>
                        <?php endif; unset($_SESSION['formSuccess'], $_SESSION['success_message'], $_SESSION['error_message']); ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
</div>


