// Backup of previous script.js
// Date: Auto-generated backup
// Original content preserved for reference
document.addEventListener('DOMContentLoaded', function() {
    // AJAX Form işleme
    const uploadForm = document.getElementById('uploadForm');
    if (uploadForm) {
        uploadForm.addEventListener('submit', function(e) {
            e.preventDefault();
            handleFileUpload();
        });
    }
    
    // Dosya seçildiğinde validasyon
    const fileInputs = document.querySelectorAll('input[type="file"]');
    fileInputs.forEach(input => {
        input.addEventListener('change', function() {
            validateFile(this);
        });
    });
    
    // Mesajları otomatik gizle
    const messages = document.querySelectorAll('.message');
    messages.forEach(message => {
        setTimeout(() => {
            message.style.opacity = '0';
            message.style.transition = 'opacity 0.5s';
            setTimeout(() => {
                message.remove();
            }, 500);
        }, 5000);
    });
});

function validateFile(input) {
    const file = input.files[0];
    const statusDiv = document.getElementById(input.id + '_status');
    
    if (!statusDiv) {
        console.error('Status div not found for input:', input.id);
        return false;
    }
    
    if (!file) {
        statusDiv.innerHTML = '';
        return false;
    }
    
    const maxSize = 10 * 1024 * 1024;
    if (file.size > maxSize) {
        statusDiv.innerHTML = '<span class="error">Dosya boyutu çok büyük (Max: 10MB)</span>';
        return false;
    }
    
    const allowedExtensions = ['xlsx', 'xls'];
    const extension = file.name.split('.').pop().toLowerCase();
    
    if (!allowedExtensions.includes(extension)) {
        statusDiv.innerHTML = '<span class="error">Sadece .xlsx ve .xls dosyaları kabul edilir</span>';
        return false;
    }
    
    statusDiv.innerHTML = '<span class="success">✓ ' + file.name + ' (' + formatFileSize(file.size) + ')</span>';
    return true;
}

function handleFileUpload() {
    const form = document.getElementById('uploadForm');
    const formData = new FormData(form);
    const submitBtn = document.getElementById('submitBtn');
    const progressContainer = document.getElementById('progressContainer');
    const progressFill = document.getElementById('progressFill');
    const progressText = document.getElementById('progressText');
    
    const bankFile = document.getElementById('bank_file');
    const stockFile = document.getElementById('stock_file');
    
    if (!bankFile.files[0] || !stockFile.files[0]) {
        showMessage('Lütfen her iki dosyayı da seçin.', 'error');
        return;
    }
    
    if (!validateFile(bankFile) || !validateFile(stockFile)) {
        showMessage('Lütfen geçerli dosyalar seçin.', 'error');
        return;
    }
    
    submitBtn.disabled = true;
    submitBtn.textContent = 'İşleniyor...';
    progressContainer.style.display = 'block';
    
    let progress = 0;
    const progressInterval = setInterval(() => {
        progress += Math.random() * 15;
        if (progress > 90) progress = 90;
        progressFill.style.width = progress + '%';
    }, 200);
    
    fetch('php/api.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
        clearInterval(progressInterval);
        progressFill.style.width = '100%';
        
            if (data.success) {
            progressText.textContent = 'Tamamlandı!';
            showMessage(data.message, 'success');
            loadAndCompareData();
            } else {
            showMessage(data.error, 'error');
            resetForm();
            }
        })
        .catch(error => {
        clearInterval(progressInterval);
            console.error('Error:', error);
        showMessage('Sunucu hatası oluştu. Lütfen tekrar deneyin.', 'error');
        resetForm();
    });
}

function resetForm() {
    const submitBtn = document.getElementById('submitBtn');
    const progressContainer = document.getElementById('progressContainer');
    
    submitBtn.disabled = false;
    submitBtn.textContent = 'Dosyaları Karşılaştır';
    progressContainer.style.display = 'none';
}

function showMessage(message, type) {
    const existingMessages = document.querySelectorAll('.message');
    existingMessages.forEach(msg => msg.remove());
    
    const messageDiv = document.createElement('div');
    messageDiv.className = `message ${type}`;
    messageDiv.textContent = message;
    
    const main = document.querySelector('main');
    main.insertBefore(messageDiv, main.firstChild);
    
    setTimeout(() => {
        messageDiv.style.opacity = '0';
        messageDiv.style.transition = 'opacity 0.5s';
        setTimeout(() => {
            messageDiv.remove();
        }, 500);
    }, 5000);
}

function formatFileSize(bytes) {
    if (bytes === 0) return '0 Bytes';
    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}

async function loadAndCompareData() {
    try {
        const [bankResponse, stockResponse] = await Promise.all([
            fetch('assets/json/bank_data.json'),
            fetch('assets/json/stock_data.json')
        ]);
        
        const bankData = await bankResponse.json();
        const stockData = await stockResponse.json();
        
        const matches = compareData(bankData, stockData);
        
        showResults({
            bank_count: bankData.length,
            stock_count: stockData.length,
            matches_count: matches.length,
            matches: matches
        });
        
    } catch (error) {
        console.error('JSON yükleme hatası:', error);
        showMessage('Veri yükleme hatası. Lütfen tekrar deneyin.', 'error');
        resetForm();
    }
}

function compareData(bankData, stockData) {
    const matches = [];
    const unmatched = [];
    const usedBankIndices = new Set();
    
    const bankByAmount = {};
    bankData.forEach((bank, index) => {
        const amountKey = Math.round(bank.amount * 100) / 100;
        if (!bankByAmount[amountKey]) {
            bankByAmount[amountKey] = [];
        }
        bankByAmount[amountKey].push({...bank, originalIndex: index});
    });
    
    stockData.forEach(stock => {
        const amountKey = Math.round(stock.amount * 100) / 100;
        let bestMatch = null;
        let bestSimilarity = 0;
        let bestBankIndex = -1;
        
        if (bankByAmount[amountKey]) {
            bankByAmount[amountKey].forEach(bank => {
                if (usedBankIndices.has(bank.originalIndex)) return;
                const similarity = calculateAdvancedSimilarity(stock.account, bank.account);
                if (similarity > bestSimilarity) {
                    bestMatch = bank;
                    bestSimilarity = similarity;
                    bestBankIndex = bank.originalIndex;
                }
            });
        }
        
        if (bestMatch && bestBankIndex !== -1 && bestSimilarity > 0.4) {
            matches.push({
                bank_row: bestMatch.row,
                stock_row: stock.row,
                bank_account: bestMatch.account,
                stock_account: stock.account,
                amount: stock.amount,
                similarity: Math.round(bestSimilarity * 100),
                bank_data: bestMatch.data,
                stock_data: stock.data,
                bank_headers: bestMatch.headers,
                stock_headers: stock.headers,
                isMatch: true
            });
            usedBankIndices.add(bestBankIndex);
        } else {
            unmatched.push({
                stock_row: stock.row,
                stock_account: stock.account,
                amount: stock.amount,
                stock_data: stock.data,
                stock_headers: stock.headers,
                isMatch: false,
                similarity: bestSimilarity > 0 ? Math.round(bestSimilarity * 100) : 0
            });
        }
    });
    
    matches.sort((a, b) => b.similarity - a.similarity);
    unmatched.sort((a, b) => b.similarity - a.similarity);
    
    return [...matches, ...unmatched];
}

function calculateAdvancedSimilarity(str1, str2) {
    str1 = normalizeText(str1);
    str2 = normalizeText(str2);
    if (str1 === str2) return 1.0;
    if (str1.length < 3 || str2.length < 3) return 0;
    const wordScore = calculateWordSimilarity(str1, str2);
    return wordScore;
}

function calculateWordSimilarity(str1, str2) {
    const words1 = str1.split(' ').filter(w => w.length > 1);
    const words2 = str2.split(' ').filter(w => w.length > 1);
    if (words1.length === 0 || words2.length === 0) return 0;
    let totalMatches = 0;
    let totalWeight = 0;
    words1.forEach(word1 => {
        let bestMatch = 0;
        const wordWeight = getWordWeight(word1);
        words2.forEach(word2 => {
            const similarity = calculateWordMatch(word1, word2);
            if (similarity > bestMatch) {
                bestMatch = similarity;
            }
        });
        totalMatches += bestMatch * wordWeight;
        totalWeight += wordWeight;
    });
    return totalWeight > 0 ? totalMatches / totalWeight : 0;
}

function getWordWeight(word) {
    const length = word.length;
    if (length <= 2) return 0.5;
    if (length <= 4) return 1.0;
    if (length <= 6) return 1.5;
    return 2.0;
}

function calculateWordMatch(word1, word2) {
    if (word1 === word2) return 1.0;
    const len1 = word1.length;
    const len2 = word2.length;
    if (len1 === 0 || len2 === 0) return 0;
    if (len1 <= 2 || len2 <= 2) {
        return word1 === word2 ? 1.0 : 0;
    }
    const maxLen = Math.max(len1, len2);
    const distance = levenshteinDistance(word1, word2);
    const levenshteinScore = 1 - (distance / maxLen);
    return levenshteinScore;
}

function normalizeText(text) {
    const turkishChars = {
        'ç': 'c', 'ğ': 'g', 'ı': 'i', 'ö': 'o', 'ş': 's', 'ü': 'u',
        'Ç': 'C', 'Ğ': 'G', 'İ': 'I', 'Ö': 'O', 'Ş': 'S', 'Ü': 'U'
    };
    return text.toLowerCase()
        .replace(/[çğıöşüÇĞİÖŞÜ]/g, char => turkishChars[char] || char)
        .replace(/[^\w\s]/g, '')
        .replace(/\s+/g, ' ')
        .trim();
}

function levenshteinDistance(str1, str2) {
    const matrix = [];
    for (let i = 0; i <= str2.length; i++) {
        matrix[i] = [i];
    }
    for (let j = 0; j <= str1.length; j++) {
        matrix[0][j] = j;
    }
    for (let i = 1; i <= str2.length; i++) {
        for (let j = 1; j <= str1.length; j++) {
            if (str2.charAt(i - 1) === str1.charAt(j - 1)) {
                matrix[i][j] = matrix[i - 1][j - 1];
            } else {
                matrix[i][j] = Math.min(
                    matrix[i - 1][j - 1] + 1,
                    matrix[i][j - 1] + 1,
                    matrix[i - 1][j] + 1
                );
            }
        }
    }
    return matrix[str2.length][str1.length];
}

function showResults(data) {
    const existingResults = document.querySelector('.results-section');
    if (existingResults) {
        existingResults.remove();
    }
    const resultsSection = document.createElement('div');
    resultsSection.className = 'results-section';
    resultsSection.innerHTML = `
        <h2>Karşılaştırma Sonuçları</h2>
        <div id="results-table">
            ${data.matches_count > 0 ? 
                generateResultsTable(data.matches) : 
                '<p>Hiç eşleşen kayıt bulunamadı.</p>'
            }
        </div>
    `;
    const main = document.querySelector('main');
    main.appendChild(resultsSection);
    resetForm();
}

function generateResultsTable(matches) {
    const matchedCount = matches.filter(m => m.isMatch).length;
    const unmatchedCount = matches.filter(m => !m.isMatch).length;
    let html = '<div class="results-table">';
    html += '<h3>Karşılaştırma Sonuçları</h3>';
    html += '<div class="results-summary">';
    html += `<div class="summary-item"><span class="label">Eşleşen:</span> <span class="value success">${matchedCount} adet</span></div>`;
    html += `<div class="summary-item"><span class="label">Eşleşmeyen:</span> <span class="value warning">${unmatchedCount} adet</span></div>`;
    html += `<div class="summary-item"><span class="label">Toplam:</span> <span class="value">${matches.length} adet</span></div>`;
    html += '</div>';
    html += '<div class="table-container">';
    html += '<table class="table">';
    html += '<thead><tr><th>#</th><th>Banka Satır</th><th>ML Satır</th><th>Banka Hesap</th><th>ML Hesap</th><th>Tutar</th><th>Benzerlik</th><th>Detay</th></tr></thead>';
    html += '<tbody>';
    matches.forEach((match, index) => {
        const rowNumber = index + 1;
        const similarity = match.similarity || 0;
        html += `<tr class="match-row">
            <td class="row-number">${rowNumber}</td>
            <td class="bank-row">${match.bank_row || '-'}</td>
            <td class="stock-row">${match.stock_row || '-'}</td>
            <td class="bank-account">${match.bank_account || '-'}</td>
            <td class="stock-account">${match.stock_account || '-'}</td>
            <td class="amount">${match.bank_amount ? match.bank_amount.toFixed(2) : (match.amount ? match.amount.toFixed(2) : '-')} ₺</td>
            <td class="similarity">%${similarity}</td>
            <td class="actions">
                <button onclick="toggleDetails(${index})" class="btn btn-sm btn-detail">Detay</button>
            </td>
        </tr>`;
        html += `<tr id="detail-${index}" class="detail-row" style="display: none;">
            <td colspan="8">
                <div class="detail-content">
                    <div class="detail-body">
                        ${match.bank_data ? `<details><summary>Banka Ham Verisi</summary><pre>${JSON.stringify(match.bank_data, null, 2)}</pre></details>` : ''}
                        ${match.stock_data ? `<details><summary>ML Ham Verisi</summary><pre>${JSON.stringify(match.stock_data, null, 2)}</pre></details>` : ''}
                    </div>
                </div>
            </td>
        </tr>`;
    });
    html += '</tbody></table></div></div>';
    return html;
}

function toggleDetails(index) {
    const detailRow = document.getElementById(`detail-${index}`);
    if (detailRow.style.display === 'none') {
        detailRow.style.display = 'table-row';
    } else {
        detailRow.style.display = 'none';
    }
}

function printResults() {}
function exportToExcel() {}


