<?php
require_once '../config/database.php';
session_start();
if (!isset($_SESSION['yonetici'])) header('Location: login.php');
$site_id = (int)$_SESSION['site_id'];
$basari = $hata = '';
$makbuz_indir_id = null;

// Tahsilat Ekle
if (isset($_POST['ekle'])) {
    $uye_id = (int)$_POST['uye_id'];
    $miktar = (float)$_POST['miktar'];
    $tarih = $_POST['tarih'] ?: date('Y-m-d');
    $aciklama = trim($_POST['aciklama'] ?? 'Aidat Ödemesi');
    $ay = $_POST['ay'] ?? null; // Opsiyonel aidat ayı

    // Makbuz No Oluştur
    $ym = date('Ym', strtotime($tarih));
    $count_stmt = $pdo->prepare("SELECT COUNT(*) FROM tahsilatlar WHERE makbuz_no LIKE ?");
    $count_stmt->execute(["MK-$ym-%"]);
    $sira = $count_stmt->fetchColumn() + 1;
    $makbuz_no = "MK-$ym-" . str_pad($sira, 3, '0', STR_PAD_LEFT);

    // Tahsilat Kaydet
    $stmt = $pdo->prepare("INSERT INTO tahsilatlar (uye_id, tarih, miktar, aciklama, makbuz_no) VALUES (?, ?, ?, ?, ?)");
    if ($stmt->execute([$uye_id, $tarih, $miktar, $aciklama, $makbuz_no])) {
        $tahsilat_id = $pdo->lastInsertId();

        // Aidat Borcundan Otomatik Düşüm (kısmi ödeme destekli)
        if ($ay) {
            $aidat_stmt = $pdo->prepare("SELECT id, miktar FROM aidatlar WHERE uye_id = ? AND ay = ? AND odendi = 0 LIMIT 1");
            $aidat_stmt->execute([$uye_id, $ay]);
            $aidat = $aidat_stmt->fetch();
            if ($aidat) {
                $kalan = $aidat['miktar'] - $miktar;
                if ($kalan <= 0) {
                    // Tam ödendi
                    $pdo->prepare("UPDATE aidatlar SET odendi = 1, odeme_tarihi = ?, tahsilat_id = ? WHERE id = ?")->execute([$tarih, $tahsilat_id, $aidat['id']]);
                } else {
                    // Kısmi ödendi
                    $pdo->prepare("UPDATE aidatlar SET miktar = ? WHERE id = ?")->execute([$kalan, $aidat['id']]);
                }
            }
        }

        // Gelir-Gider Kaydı
        $stmt_gg = $pdo->prepare("INSERT INTO gelir_gider (site_id, tip, tutar, aciklama, tarih) VALUES (?, 'gelir', ?, ?, ?)");
        $stmt_gg->execute([$site_id, $miktar, "Üye ID: $uye_id Aidat Ödemesi (Makbuz: $makbuz_no)", $tarih]);

        $basari = "Tahsilat başarıyla kaydedildi! Makbuz No: <strong>$makbuz_no</strong>";
        $makbuz_indir_id = $tahsilat_id;
    } else {
        $hata = "Tahsilat kaydedilemedi!";
    }
}

// Düzenle (GET ile veri çek)
$duzenle = null;
if (isset($_GET['duzenle']) && is_numeric($_GET['duzenle'])) {
    $stmt = $pdo->prepare("SELECT t.*, u.ad_soyad, u.daire_no, u.blok_adi FROM tahsilatlar t INNER JOIN uyeler u ON t.uye_id = u.id WHERE t.id = ? AND u.site_id = ?");
    $stmt->execute([$_GET['duzenle'], $site_id]);
    $duzenle = $stmt->fetch();
}

// Düzenle (POST ile kaydet)
if (isset($_POST['guncelle'])) {
    $stmt = $pdo->prepare("UPDATE tahsilatlar SET miktar = ?, aciklama = ?, tarih = ? WHERE id = ?");
    $stmt->execute([$_POST['miktar'], $_POST['aciklama'], $_POST['tarih'], $_POST['id']]);
    $basari = "Tahsilat güncellendi!";
}

// Sil
if (isset($_GET['sil']) && is_numeric($_GET['sil'])) {
    $stmt_tah = $pdo->prepare("SELECT uye_id, miktar, makbuz_no FROM tahsilatlar WHERE id = ?");
    $stmt_tah->execute([$_GET['sil']]);
    $tah = $stmt_tah->fetch();
    if ($tah) {
        // Aidat'ı geri al (tahsilat_id ile bağlantılı)
        $pdo->prepare("UPDATE aidatlar SET odendi = 0, odeme_tarihi = NULL, tahsilat_id = NULL WHERE tahsilat_id = ?")->execute([$_GET['sil']]);
        // Gelir-gider'den sil
        $pdo->prepare("DELETE FROM gelir_gider WHERE aciklama LIKE ?")->execute(["%Makbuz: {$tah['makbuz_no']}%"]);
    }
    $pdo->prepare("DELETE FROM tahsilatlar WHERE id = ?")->execute([$_GET['sil']]);
    $basari = "Tahsilat silindi ve bağlantılar güncellendi!";
}

// Filtreleme
$where = "u.site_id = ?";
$params = [$site_id];
if (!empty($_GET['ad'])) {
    $where .= " AND u.ad_soyad LIKE ?";
    $params[] = '%' . $_GET['ad'] . '%';
}
if (!empty($_GET['tarih'])) {
    $where .= " AND t.tarih = ?";
    $params[] = $_GET['tarih'];
}

// Liste
$stmt = $pdo->prepare("SELECT t.*, u.blok_adi, u.daire_no, u.ad_soyad, u.telefon FROM tahsilatlar t INNER JOIN uyeler u ON t.uye_id = u.id WHERE $where ORDER BY t.tarih DESC");
$stmt->execute($params);
$tahsilatlar = $stmt->fetchAll();

// Üyeler
$stmt_uye = $pdo->prepare("SELECT id, ad_soyad, daire_no, blok_adi FROM uyeler WHERE site_id = ? AND aktif = 1 ORDER BY blok_adi, daire_no");
$stmt_uye->execute([$site_id]);
$uyeler = $stmt_uye->fetchAll();
?>
<?php include '../inc/header.php'; ?>
<?php include '../inc/sidebar.php'; ?>
<?php include '../inc/navbar.php'; ?>
<div class="content-wrapper">
    <div class="content-header">
        <div class="container-fluid">
            <h1><i class="fas fa-receipt"></i> Tahsilat Yönetimi</h1>
        </div>
    </div>
    <section class="content">
        <div class="container-fluid">
            <?php if($basari): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <?= $basari ?>
                    <?php if($makbuz_indir_id): ?>
                        <a href="makbuz_goruntule.php?id=<?= $makbuz_indir_id ?>" target="_blank" class="btn btn-sm btn-success ml-3">
                            <i class="fas fa-print"></i> Makbuzu Görüntüle ve İndir
                        </a>
                    <?php endif; ?>
                    <button type="button" class="close" data-dismiss="alert">×</button>
                </div>
            <?php endif; ?>
            <?php if($hata): ?>
                <div class="alert alert-danger alert-dismissible fade show">
                    <?= $hata ?>
                    <button type="button" class="close" data-dismiss="alert">×</button>
                </div>
            <?php endif; ?>

            <!-- Tahsilat Ekle Formu -->
            <div class="card card-success mb-4">
                <div class="card-header">
                    <h3 class="card-title">Yeni Tahsilat Ekle</h3>
                </div>
                <div class="card-body">
                    <form method="post">
                        <div class="row">
                            <div class="col-md-4">
                                <label>Üye</label>
                                <select name="uye_id" class="form-control" required>
                                    <option value="">Üye Seçiniz</option>
                                    <?php foreach ($uyeler as $u): ?>
                                        <option value="<?= $u['id'] ?>">
                                            <?= htmlspecialchars($u['ad_soyad']) ?> (<?= $u['blok_adi'] ?> Blok <?= $u['daire_no'] ?>)
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            <div class="col-md-2">
                                <label>Miktar (₺)</label>
                                <input name="miktar" type="number" step="0.01" class="form-control" required>
                            </div>
                            <div class="col-md-2">
                                <label>Tarih</label>
                                <input name="tarih" type="date" class="form-control" value="<?= date('Y-m-d') ?>" required>
                            </div>
                            <div class="col-md-2">
    <label>Aidat Ayı</label>
    <input name="ay" type="month" class="form-control" placeholder="Örn: 2025-12">
    <small class="text-muted d-block mt-1">Ödenen aidatın hangi aya ait olduğunu seçin</small>
</div>
                            <div class="col-md-2">
                                <label>Açıklama</label>
                                <input name="aciklama" class="form-control" value="Aidat Ödemesi">
                            </div>
                        </div>
                        <div class="mt-3">
                            <button name="ekle" class="btn btn-success btn-block">Tahsil Et & Makbuz Kes</button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Düzenle Formu -->
            <?php if($duzenle): ?>
            <div class="card card-warning mb-4">
                <div class="card-header">
                    <h3 class="card-title">Tahsilat Düzenle - <?= htmlspecialchars($duzenle['ad_soyad']) ?></h3>
                </div>
                <div class="card-body">
                    <form method="post">
                        <input type="hidden" name="id" value="<?= $duzenle['id'] ?>">
                        <div class="row">
                            <div class="col-md-3">
                                <label>Miktar</label>
                                <input name="miktar" type="number" step="0.01" class="form-control" value="<?= $duzenle['miktar'] ?>" required>
                            </div>
                            <div class="col-md-3">
                                <label>Tarih</label>
                                <input name="tarih" type="date" class="form-control" value="<?= $duzenle['tarih'] ?>" required>
                            </div>
                            <div class="col-md-4">
                                <label>Açıklama</label>
                                <input name="aciklama" class="form-control" value="<?= htmlspecialchars($duzenle['aciklama'] ?? '') ?>">
                            </div>
                            <div class="col-md-2 mt-4">
                                <button name="guncelle" class="btn btn-warning btn-block">Güncelle</button>
                                <a href="tahsilat.php" class="btn btn-secondary btn-block mt-2">İptal</a>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
            <?php endif; ?>

            <!-- Filtre -->
            <form method="get" class="mb-4">
                <div class="row">
                    <div class="col-md-4">
                        <input name="ad" class="form-control" placeholder="Ad Soyad" value="<?= htmlspecialchars($_GET['ad'] ?? '') ?>">
                    </div>
                    <div class="col-md-3">
                        <input name="tarih" type="date" class="form-control" value="<?= htmlspecialchars($_GET['tarih'] ?? '') ?>">
                    </div>
                    <div class="col-md-3 offset-md-2">
                        <button type="submit" class="btn btn-primary btn-block">Filtrele</button>
                    </div>
                </div>
            </form>

            <!-- Tahsilat Listesi -->
            <div class="card">
                <div class="card-header bg-gradient-primary text-white">
                    <h3 class="card-title">Tahsilat Listesi</h3>
                    <div class="card-tools">
                        <div id="export_buttons" class="btn-group mr-2"></div>
                    </div>
                </div>
                <div class="card-body table-responsive p-0">
                    <table id="tahsilatTable" class="table table-hover text-nowrap">
                        <thead class="thead-light">
                            <tr>
                                <th>Blok</th>
                                <th>Daire No</th>
                                <th>Ad Soyad</th>
                                <th>Telefon</th>
                                <th>Tarih</th>
                                <th>Miktar</th>
                                <th>Makbuz No</th>
                                <th>Açıklama</th>
                                <th>İşlemler</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($tahsilatlar)): ?>
                                <tr><td colspan="9" class="text-center">Tahsilat kaydı bulunamadı.</td></tr>
                            <?php else: ?>
                                <?php foreach ($tahsilatlar as $t): ?>
                                <tr>
                                    <td><?= htmlspecialchars($t['blok_adi'] ?? '-') ?></td>
                                    <td><?= htmlspecialchars($t['daire_no']) ?></td>
                                    <td><?= htmlspecialchars($t['ad_soyad']) ?></td>
                                    <td><?= htmlspecialchars($t['telefon'] ?? '-') ?></td>
                                    <td><?= date('d.m.Y', strtotime($t['tarih'])) ?></td>
                                    <td>₺<?= number_format($t['miktar'], 2) ?></td>
                                    <td>
                                        <a href="makbuz_goruntule.php?id=<?= $t['id'] ?>" target="_blank" class="badge badge-info">
                                            <?= $t['makbuz_no'] ?>
                                        </a>
                                    </td>
                                    <td><?= htmlspecialchars($t['aciklama'] ?? '-') ?></td>
                                    <td>
                                        <a href="?duzenle=<?= $t['id'] ?>" class="btn btn-primary btn-sm"><i class="fas fa-edit"></i></a>
                                        <a href="?sil=<?= $t['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Silmek istediğinize emin misiniz? Aidat ve gelir-gider kaydı tersine dönecek.');"><i class="fas fa-trash"></i></a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </section>
</div>

<!-- DataTables ve Buttons -->
<link rel="stylesheet" href="https://cdn.datatables.net/1.13.7/css/dataTables.bootstrap4.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.4.2/css/buttons.bootstrap4.min.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/js/bootstrap.bundle.min.js"></script>
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.print.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.10.1/jszip.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
<script>
$(document).ready(function() {
    var table = $('#tahsilatTable').DataTable({
        dom: 'Bfrtip',
        buttons: [
            { extend: 'copy', text: 'Kopyala', className: 'btn btn-secondary btn-sm' },
            { extend: 'csv', text: 'CSV', className: 'btn btn-dark btn-sm' },
            { extend: 'excel', text: 'Excel', className: 'btn btn-success btn-sm' },
            { extend: 'pdf', text: 'PDF', className: 'btn btn-danger btn-sm' },
            { extend: 'print', text: 'Yazdır', className: 'btn btn-info btn-sm' }
        ],
        language: { url: '//cdn.datatables.net/plug-ins/1.13.7/i18n/tr.json' },
        responsive: true,
        pageLength: 25,
        lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Tümü"]],
        order: [[4, 'desc']],
        columnDefs: [{ targets: [8], orderable: false }]
    });
    table.buttons().container().appendTo('#export_buttons');
});
</script>
<?php include '../inc/footer.php'; ?>