<?php
require_once __DIR__ . '/../includes/config.php';
yetkili_mi(['hesap_yonetimi', 'raporlar']);

$sayfa_baslik = __("account_transactions");

// FİLTRELEME PARAMETRELERİ
$filtre_hesap_id = filter_input(INPUT_GET, 'hesap_id', FILTER_VALIDATE_INT);
$filtre_cari_id = filter_input(INPUT_GET, 'cari_id', FILTER_VALIDATE_INT);
$filtre_baslangic = filter_input(INPUT_GET, 'baslangic', FILTER_SANITIZE_SPECIAL_CHARS);
$filtre_bitis = filter_input(INPUT_GET, 'bitis', FILTER_SANITIZE_SPECIAL_CHARS);
$filtre_tur = filter_input(INPUT_GET, 'tur', FILTER_SANITIZE_SPECIAL_CHARS); // giris, cikis, transfer

// Tarihleri doğrula veya varsayılan ata
if (!$filtre_baslangic || !preg_match("/^\d{4}-\d{2}-\d{2}$/", $filtre_baslangic)) {
    $filtre_baslangic = date('Y-m-01'); // Ay başı
}
if (!$filtre_bitis || !preg_match("/^\d{4}-\d{2}-\d{2}$/", $filtre_bitis)) {
    $filtre_bitis = date('Y-m-d'); // Bugün
}

// Diğer filtreleri temizle
$filtre_hesap_id = $filtre_hesap_id ?: null; // Boşsa null yap
$filtre_cari_id = $filtre_cari_id ?: null;
$filtre_tur = in_array($filtre_tur, ['giris', 'cikis', 'transfer']) ? $filtre_tur : null;

// Verileri Çekme
try {
    // Filtreler için WHERE koşullarını ve parametreleri oluştur
    $where_clauses = [
        "hh.sirket_id = :sirket_id", 
        "hh.tarih BETWEEN :baslangic AND DATE_ADD(:bitis, INTERVAL 1 DAY)"
    ];
    $params = [
        ':sirket_id' => $aktif_sirket_id,
        ':baslangic' => $filtre_baslangic,
        ':bitis' => $filtre_bitis
    ];

    if ($filtre_hesap_id) {
        $where_clauses[] = "hh.hesap_id = :hesap_id";
        $params[':hesap_id'] = $filtre_hesap_id;
    }
    if ($filtre_cari_id) {
        $where_clauses[] = "hh.cari_id = :cari_id";
        $params[':cari_id'] = $filtre_cari_id;
    }
     if ($filtre_tur) {
        $where_clauses[] = "hh.tur = :tur";
        $params[':tur'] = $filtre_tur;
    }

    $where_sql = implode(' AND ', $where_clauses);

    // Ana Sorgu
    $sql = "SELECT hh.*, h.hesap_adi, h.para_birimi as hesap_para_birimi, c.ad_soyad as cari_ad_soyad,
                   b.tur as borc_tur, b.aciklama as borc_aciklama, b.id as borc_kayit_id,
                   h_transfer.hesap_adi as transfer_hedef_hesap
            FROM hesap_hareketleri hh
            LEFT JOIN hesaplar h ON hh.hesap_id = h.id
            LEFT JOIN cariler c ON hh.cari_id = c.id
            LEFT JOIN borclar b ON hh.borc_id = b.id
            LEFT JOIN hesap_hareketleri hh_transfer ON (hh.tur = 'transfer' AND hh.baglanti_id = hh_transfer.id)
            LEFT JOIN hesaplar h_transfer ON hh_transfer.hesap_id = h_transfer.id
            WHERE $where_sql
            ORDER BY hh.tarih DESC, hh.id DESC";

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

    // Filtreleme formları için hesapları ve carileri al (Sadece aktif şirkete ait olanlar)
    $hesaplar_stmt = $db->prepare("SELECT id, hesap_adi FROM hesaplar WHERE sirket_id = ? ORDER BY hesap_adi");
    $hesaplar_stmt->execute([$aktif_sirket_id]);
    $hesaplar = $hesaplar_stmt->fetchAll();

    $cariler_stmt = $db->prepare("SELECT id, ad_soyad FROM cariler WHERE sirket_id = ? ORDER BY ad_soyad");
    $cariler_stmt->execute([$aktif_sirket_id]);
    $cariler = $cariler_stmt->fetchAll();
    
    // Toplamları hesapla (Hata vermemesi için)
    $toplam_giris = 0;
    $toplam_cikis = 0;
    foreach ($hareketler as $hareket) {
        if ($hareket['tur'] == 'giris') {
            $toplam_giris += $hareket['tutar'];
        } elseif ($hareket['tur'] == 'cikis') {
            $toplam_cikis += $hareket['tutar'];
        }
    }
    $genel_bakiye = $toplam_giris - $toplam_cikis;


} catch(PDOException $e) {
    error_log("Hesap Hareketleri Hatası: ".$e->getMessage());
    $_SESSION['hata'] = "Hesap hareketleri alınırken bir hata oluştu.";
    $hareketler = [];
    $hesaplar = [];
    $cariler = [];
    $toplam_giris = 0;
    $toplam_cikis = 0;
    $genel_bakiye = 0;
}

$csrf_token = csrf_token_olustur(); // Gerekirse silme vb. işlemler için
?>
<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Odjoo - <?= __("account_transactions") ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
</head>
<body>
    <?php include __DIR__ . '/../includes/navbar.php'; ?>

    <div class="container mt-4">
        <div class="d-flex justify-content-between align-items-center mb-3">
            <h2 class="mb-0"><i class="bi bi-list-ol me-2"></i> <?= htmlspecialchars($sayfa_baslik) ?></h2>
            <div class="btn-group">
                <a href="hesap_hareketleri_pdf.php?hesap_id=<?= $filtre_hesap_id ?>&cari_id=<?= $filtre_cari_id ?>&baslangic=<?= $filtre_baslangic ?>&bitis=<?= $filtre_bitis ?>&tur=<?= $filtre_tur ?>" target="_blank" class="btn btn-sm btn-outline-primary">
                    <i class="bi bi-file-pdf"></i> <?= __("download_pdf") ?>
                </a>
                <a href="hesap_hareketleri_excel.php?hesap_id=<?= $filtre_hesap_id ?>&cari_id=<?= $filtre_cari_id ?>&baslangic=<?= $filtre_baslangic ?>&bitis=<?= $filtre_bitis ?>&tur=<?= $filtre_tur ?>" class="btn btn-sm btn-outline-success">
                    <i class="bi bi-file-excel"></i> <?= __("download_excel") ?>
                </a>
            </div>
        </div>
        <hr>

        <div class="card shadow-sm mb-4">
             <div class="card-header">
                 <a class="text-decoration-none" data-bs-toggle="collapse" href="#collapseFilter" role="button" aria-expanded="false" aria-controls="collapseFilter">
                    <i class="bi bi-funnel me-2"></i> <?= __("filter") ?>
                </a>
             </div>
            <div class="collapse" id="collapseFilter">
                <div class="card-body">
                    <form method="GET" class="row g-3">
                        <div class="col-md-3">
                            <label for="baslangic" class="form-label"><?= __("start_date") ?></label>
                            <input type="date" id="baslangic" name="baslangic" class="form-control form-control-sm" value="<?= htmlspecialchars($filtre_baslangic) ?>">
                        </div>
                        <div class="col-md-3">
                            <label for="bitis" class="form-label"><?= __("end_date") ?></label>
                            <input type="date" id="bitis" name="bitis" class="form-control form-control-sm" value="<?= htmlspecialchars($filtre_bitis) ?>">
                        </div>
                        <div class="col-md-3">
                            <label for="hesap_id" class="form-label"><?= __("account") ?></label>
                            <select id="hesap_id" name="hesap_id" class="form-select form-select-sm">
                                <option value=""><?= __("all_accounts") ?></option>
                                <?php foreach($hesaplar as $hesap): ?>
                                <option value="<?= $hesap['id'] ?>" <?= ($filtre_hesap_id == $hesap['id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($hesap['hesap_adi']) ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                         <div class="col-md-3">
                            <label for="cari_id" class="form-label"><?= __("customer") ?></label>
                            <select id="cari_id" name="cari_id" class="form-select form-select-sm">
                                <option value=""><?= __("all_customers") ?></option>
                                <?php foreach($cariler as $cari): ?>
                                <option value="<?= $cari['id'] ?>" <?= ($filtre_cari_id == $cari['id']) ? 'selected' : '' ?>>
                                    <?= htmlspecialchars($cari['ad_soyad']) ?>
                                </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                         <div class="col-md-3">
                            <label for="tur" class="form-label"><?= __("transaction_type") ?></label>
                            <select id="tur" name="tur" class="form-select form-select-sm">
                                <option value=""><?= __("all_types") ?></option>
                                <option value="giris" <?= ($filtre_tur == 'giris') ? 'selected' : '' ?>><?= __("entry_collection") ?></option>
                                <option value="cikis" <?= ($filtre_tur == 'cikis') ? 'selected' : '' ?>><?= __("exit_payment") ?></option>
                                <option value="transfer" <?= ($filtre_tur == 'transfer') ? 'selected' : '' ?>><?= __("transfer") ?></option>
                            </select>
                        </div>
                        <div class="col-md-9 d-flex align-items-end">
                            <button type="submit" class="btn btn-primary btn-sm me-2">
                                <i class="bi bi-filter"></i> <?= __("apply_filter") ?>
                            </button>
                             <a href="hesap_hareketleri.php" class="btn btn-secondary btn-sm">
                                <i class="bi bi-x-lg"></i> <?= __("clear_filter") ?>
                             </a>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <div class="card shadow-sm">
             <div class="card-body p-0">
                <div class="table-responsive">
                    <table class="table table-hover table-striped mb-0"> <?php // table-striped eklendi ?>
                        <thead class="table-light">
                            <tr>
                                <th><?= __("date") ?></th>
                                <th><?= __("account") ?></th>
                                <th><?= __("type") ?></th>
                                <th><?= __("amount") ?></th>
                                <th><?= __("customer") ?></th>
                                <th><?= __("description") ?></th>
                                <th><?= __("related_transaction") ?></th>
                                <th><?= __("actions") ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($hareketler)): ?>
                                <tr>
                                    <td colspan="8" class="text-center text-muted py-4"><?= __("no_transactions_found") ?></td>
                                </tr>
                            <?php else: ?>
                                <?php foreach($hareketler as $hareket): ?>
                                <tr>
                                    <td><small><?= date('d.m.Y H:i', strtotime($hareket['tarih'])) ?></small></td>
                                    <td><?= htmlspecialchars($hareket['hesap_adi']) ?></td>
                                    <td>
                                        <?php if ($hareket['tur'] == 'giris'): ?>
                                            <span class="badge bg-success"><?= __("entry") ?></span>
                                        <?php elseif ($hareket['tur'] == 'cikis'): ?>
                                            <span class="badge bg-danger"><?= __("exit") ?></span>
                                         <?php elseif ($hareket['tur'] == 'transfer'): ?>
                                            <span class="badge bg-info"><?= __("transfer") ?></span>
                                        <?php endif; ?>
                                    </td>
                                    <td class="text-end fw-bold <?= $hareket['tur'] == 'giris' ? 'text-success' : ($hareket['tur'] == 'cikis' ? 'text-danger' : 'text-info') ?>">
                                        <?= $hareket['tur'] == 'giris' ? '+' : ($hareket['tur'] == 'cikis' ? '-' : '') ?>
                                        <?= number_format($hareket['tutar'], 2, ',', '.') ?>
<?php if (!empty($hareket['hesap_para_birimi'])): ?>
    <?= htmlspecialchars($hareket['hesap_para_birimi']) ?>
<?php else: ?>
    <?= getParaBirimiSembolu() ?>
<?php endif; ?>
                                    </td>
                                    <td><?= $hareket['cari_ad_soyad'] ? htmlspecialchars($hareket['cari_ad_soyad']) : '-' ?></td>
                                    <td>
                                        <?= htmlspecialchars($hareket['aciklama']) ?>
                                        <?php if($hareket['tur'] == 'transfer' && $hareket['transfer_hedef_hesap']): ?>
                                             <small class="text-muted d-block">(<?= __("target") ?>: <?= htmlspecialchars($hareket['transfer_hedef_hesap']) ?>)</small>
                                        <?php endif; ?>
                                        <?php if (!empty($hareket['borc_kayit_id'])): ?>
                                             <small class="text-muted d-block"><?= __("debt_id") ?>: <?= $hareket['borc_kayit_id'] ?></small>
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <?php if (!empty($hareket['fatura_id'])): ?>
                                            <a href="fatura_goruntule.php?id=<?= htmlspecialchars($hareket['fatura_id']) ?>" class="btn btn-outline-primary btn-sm"><?= __("invoice") ?> #<?= htmlspecialchars($hareket['fatura_id']) ?></a>
                                        <?php elseif (!empty($hareket['musteri_id'])): ?>
                                            <a href="borc_detay.php?id=<?= htmlspecialchars($hareket['musteri_id']) ?>" class="btn btn-outline-info btn-sm"><?= __("customer") ?> #<?= htmlspecialchars($hareket['musteri_id']) ?></a>
                                        <?php elseif ($hareket['tur'] == 'cikis'): ?>
                                            <a href="kasa_gider_pdf.php?id=<?= $hareket['id'] ?>" target="_blank" class="btn btn-outline-danger btn-sm" title="<?= __("download_receipt") ?>"><i class="bi bi-file-earmark-pdf"></i></a>
                                        <?php else: ?>
                                            -
                                        <?php endif; ?>
                                    </td>
                                    <td>
                                        <div class="btn-group btn-group-sm" role="group">
                                            <button type="button" class="btn btn-outline-warning btn-sm" 
                                                    onclick="hareketDuzenle(<?= $hareket['id'] ?>, '<?= htmlspecialchars($hareket['aciklama']) ?>', '<?= $hareket['tutar'] ?>', '<?= $hareket['tarih'] ?>', '<?= $hareket['tur'] ?>')" 
                                                    title="<?= __("edit") ?>">
                                                <i class="bi bi-pencil"></i>
                                            </button>
                                            <button type="button" class="btn btn-outline-danger btn-sm" 
                                                    onclick="hareketSil(<?= $hareket['id'] ?>, '<?= htmlspecialchars($hareket['aciklama']) ?>', '<?= $hareket['tutar'] ?>')" 
                                                    title="<?= __("delete") ?>">
                                                <i class="bi bi-trash"></i>
                                            </button>
                                        </div>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                        <tfoot class="table-light">
                             <tr>
                                <th colspan="3" class="text-end"><?= __("period_totals") ?>:</th>
                                <th class="text-end text-success">+<?= number_format($toplam_giris, 2, ',', '.') ?>
<?php if ($filtre_hesap_id && !empty($hareketler[0]['hesap_para_birimi'])): ?>
    <?= htmlspecialchars($hareketler[0]['hesap_para_birimi']) ?>
<?php else: ?>
    <span class="text-muted">(<?= __("multiple") ?>)</span>
<?php endif; ?></th>
<th class="text-end text-danger">-<?= number_format($toplam_cikis, 2, ',', '.') ?>
<?php if ($filtre_hesap_id && !empty($hareketler[0]['hesap_para_birimi'])): ?>
    <?= htmlspecialchars($hareketler[0]['hesap_para_birimi']) ?>
<?php else: ?>
    <span class="text-muted">(<?= __("multiple") ?>)</span>
<?php endif; ?></th>
                                <th colspan="2"></th>
                            </tr>
                            <tr>
                                <th colspan="3" class="text-end border-top-0"><?= __("period_net_balance") ?>:</th>
                                <th colspan="2" class="text-end border-top-0 fs-5 <?= $genel_bakiye >= 0 ? 'text-success' : 'text-danger' ?>">
    <?= number_format($genel_bakiye, 2, ',', '.') ?>
    <?php if ($filtre_hesap_id && !empty($hareketler[0]['hesap_para_birimi'])): ?>
        <?= htmlspecialchars($hareketler[0]['hesap_para_birimi']) ?>
    <?php else: ?>
        <span class="text-muted">(<?= __("multiple") ?>)</span>
    <?php endif; ?>
</th>                                </th>
                                <th colspan="2"></th>
                            </tr>
                        </tfoot>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <!-- Hesap Hareketi Düzenleme Modal -->
    <div class="modal fade" id="hareketDuzenleModal" tabindex="-1" aria-labelledby="hareketDuzenleModalLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="hareketDuzenleModalLabel"><?= __("edit_transaction") ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="hareketDuzenleForm" method="POST" action="hesap_hareketi_duzenle.php">
                    <div class="modal-body">
                        <input type="hidden" name="csrf_token" value="<?= $csrf_token ?>">
                        <input type="hidden" id="hareket_id" name="hareket_id">
                        
                        <div class="mb-3">
                            <label for="duzenle_tarih" class="form-label"><?= __("date") ?></label>
                            <input type="date" class="form-control" id="duzenle_tarih" name="tarih" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="duzenle_tutar" class="form-label"><?= __("amount") ?></label>
                            <input type="number" class="form-control" id="duzenle_tutar" name="tutar" step="0.01" min="0" required>
                        </div>
                        
                        <div class="mb-3">
                            <label for="duzenle_aciklama" class="form-label"><?= __("description") ?></label>
                            <textarea class="form-control" id="duzenle_aciklama" name="aciklama" rows="3" required></textarea>
                        </div>
                        
                        <div class="mb-3">
                            <label for="duzenle_tur" class="form-label"><?= __("transaction_type") ?></label>
                            <select class="form-select" id="duzenle_tur" name="tur" required>
                                <option value="giris"><?= __("entry_collection") ?></option>
                                <option value="cikis"><?= __("exit_payment") ?></option>
                                <option value="transfer"><?= __("transfer") ?></option>
                            </select>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= __("cancel") ?></button>
                        <button type="submit" class="btn btn-primary"><?= __("update") ?></button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- Hesap Hareketi Detay Modal -->
    <div class="modal fade" id="hareketDetayModal" tabindex="-1" aria-labelledby="hareketDetayModalLabel" aria-hidden="true">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="hareketDetayModalLabel"><?= __("transaction_details") ?></h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="row">
                        <div class="col-md-6">
                            <table class="table table-borderless">
                                <tr><th><?= __("transaction_id") ?>:</th><td id="detay_hareket_id">-</td></tr>
                                <tr><th><?= __("date") ?>:</th><td id="detay_tarih">-</td></tr>
                                <tr><th><?= __("account") ?>:</th><td id="detay_hesap_adi">-</td></tr>
                                <tr><th><?= __("type") ?>:</th><td id="detay_tur">-</td></tr>
                                <tr><th><?= __("amount") ?>:</th><td id="detay_tutar">-</td></tr>
                            </table>
                        </div>
                        <div class="col-md-6">
                            <table class="table table-borderless">
                                <tr><th><?= __("description") ?>:</th><td id="detay_aciklama">-</td></tr>
                                <tr><th><?= __("customer") ?>:</th><td id="detay_cari_ad">-</td></tr>
                                <tr><th><?= __("debt_id") ?>:</th><td id="detay_baglan_id">-</td></tr>
                                <tr><th><?= __("invoice") ?> ID:</th><td id="detay_fatura_id">-</td></tr>
                                <tr><th><?= __("transfer_target") ?>:</th><td id="detay_transfer_hedef">-</td></tr>
                                <tr><th><?= __("connection_id") ?>:</th><td id="detay_baglanti_id">-</td></tr>
                            </table>
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal"><?= __("close") ?></button>
                </div>
            </div>
        </div>
    </div>

	<?php include __DIR__ . '/../includes/footer.php'; ?>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    
    <script>
        // Hesap hareketi detay gösterme fonksiyonu
        function hareketDetayGoster(id) {
            // Loading göster
            console.log('Hareket detayı getiriliyor... ID:', id);
            
            // AJAX ile detayları getir
            const url = new URL('hesap_hareketi_detay.php', window.location.origin);
            url.searchParams.append('hareket_id', id);
            console.log('Fetching from URL:', url.toString());
            
            fetch(url.toString(), {
                headers: {
                    'Accept': 'application/json',
                    'X-Requested-With': 'XMLHttpRequest'
                },
                credentials: 'same-origin' // Oturum çerezlerini gönder
            })
                .then(async response => {
                    console.log('Response status:', response.status);
                    
                    // Yanıtı klonla (birden fazla kez okumak için)
                    const responseClone = response.clone();
                    
                    try {
                        // Önce JSON olarak parse etmeyi dene
                        const data = await response.json();
                        return { data, response };
                    } catch (e) {
                        // JSON parse hatası durumunda ham yanıtı oku
                        const errorText = await responseClone.text();
                        console.error('JSON parse hatası:', errorText);
                        throw new Error(`Geçersiz yanıt: ${errorText.substring(0, 100)}...`);
                    }
                })
                .then(({data, response}) => {
                    console.log('Response data:', data);
                    
                    if (!response.ok) {
                        throw new Error(data?.message || `Sunucu hatası: ${response.status} ${response.statusText}`);
                    }
                    
                    if (!data) {
                        throw new Error('Boş yanıt alındı');
                    }
                    
                    if (data.success) {
                        // Debug için log ekle
                        console.log('Hareket detayı başarıyla alındı:', data.hareket);
                        
                        // Eğer fatura ID'si varsa fatura sayfasına yönlendir
                        if (data.hareket?.fatura_id) {
                            console.log('Fatura ID bulundu:', data.hareket.fatura_id);
                            console.log('Fatura Türü:', data.hareket.fatura_tur);
                            
                            // Fatura türüne göre doğru sayfayı belirle
                            let faturaSayfasi = 'satis_fatura_goruntule.php'; // Varsayılan olarak satış faturası
                            
                            if (data.hareket.fatura_tur === 'alis') {
                                faturaSayfasi = 'fatura_goruntule.php';
                            }
                            
                            console.log('Yönlendiriliyor:', `${faturaSayfasi}?id=${data.hareket.fatura_id}`);
                            
                            // Yönlendirmeyi yap
                            window.location.href = `${faturaSayfasi}?id=${data.hareket.fatura_id}`;
                            return; // İşlemi sonlandır
                        } else {
                            console.log('Bu işlem bir faturaya bağlı değil');
                        }
                        
                        // Fatura değilse modal göster
                        const fields = {
                            'detay_hareket_id': data.hareket?.id,
                            'detay_tarih': data.hareket?.tarih,
                            'detay_hesap_adi': data.hareket?.hesap_adi,
                            'detay_tur': data.hareket?.tur,
                            'detay_tutar': data.hareket?.tutar ? `${data.hareket.tutar} ${data.hareket.hesap_para_birimi || ''}` : '-',
                            'detay_aciklama': data.hareket?.aciklama,
                            'detay_cari_ad': data.hareket?.cari_ad_soyad,
                            'detay_baglan_id': data.hareket?.borc_kayit_id,
                            'detay_fatura_id': data.hareket?.fatura_id,
                            'detay_transfer_hedef': data.hareket?.transfer_hedef_hesap,
                            'detay_baglanti_id': data.hareket?.baglanti_id
                        };

                        // Her bir alanı güncelle
                        Object.entries(fields).forEach(([id, value]) => {
                            const element = document.getElementById(id);
                            if (element) {
                                element.textContent = value || '-';
                            }
                        });
                        
                        // Modal'ı göster
                        const modal = new bootstrap.Modal(document.getElementById('hareketDetayModal'));
                        modal.show();
                    } else {
                        throw new Error(data?.message || 'Bilinmeyen hata oluştu');
                    }
                })
                .catch(error => {
                    console.error('Hesap hareketi detayı alınırken hata:', error);
                    
                    // Daha detaylı hata mesajı göster
                    let errorMessage = 'İşlem detayları yüklenirken bir hata oluştu.\n\n';
                    errorMessage += `Hata: ${error.message || 'Bilinmeyen hata'}\n`;
                    errorMessage += 'Lütfen yöneticinizle iletişime geçin veya daha sonra tekrar deneyin.';
                    
                    alert(errorMessage);
                });
        }
        
        // Hesap hareketi düzenleme fonksiyonu
        function hareketDuzenle(id, aciklama, tutar, tarih, tur) {
            document.getElementById('hareket_id').value = id;
            document.getElementById('duzenle_aciklama').value = aciklama;
            document.getElementById('duzenle_tutar').value = tutar;
            
            // Tarih formatını düzelt (datetime'dan date'e)
            const tarihObj = new Date(tarih);
            const tarihStr = tarihObj.toISOString().split('T')[0];
            document.getElementById('duzenle_tarih').value = tarihStr;
            
            document.getElementById('duzenle_tur').value = tur;
            
            // Modal'ı aç
            new bootstrap.Modal(document.getElementById('hareketDuzenleModal')).show();
        }
        
        // Hesap hareketi silme fonksiyonu
        function hareketSil(id, aciklama, tutar) {
            if (confirm(`<?= __("confirm_delete_transaction") ?>\n\n<?= __("description") ?>: ${aciklama}\n<?= __("amount") ?>: ${tutar}`)) {
                // AJAX ile silme işlemi
                fetch('hesap_hareketi_sil.php', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                    },
                    body: `hareket_id=${id}&csrf_token=<?= $csrf_token ?>`
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        alert('<?= __("transaction_deleted_successfully") ?>');
                        location.reload(); // Sayfayı yenile
                    } else {
                        alert('Hata: ' + (data.message || 'Bilinmeyen hata'));
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('<?= __("error_deleting_transaction") ?>');
                });
            }
        }
        
        // Form submit işlemi
        document.getElementById('hareketDuzenleForm').addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            
            fetch('hesap_hareketi_duzenle.php', {
                method: 'POST',
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                return response.json();
            })
            .then(data => {
                if (data.success) {
                    alert('<?= __("transaction_updated_successfully") ?>');
                    location.reload(); // Sayfayı yenile
                } else {
                    alert('Hata: ' + (data.message || 'Bilinmeyen hata'));
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('<?= __("error_updating_transaction") ?>');
            });
        });
    </script>
</body>
</html>
