<?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;

    $ym = date('Ym', strtotime($tarih));
    $stmt_max = $pdo->prepare("SELECT MAX(CAST(SUBSTRING_INDEX(makbuz_no, '-', -1) AS UNSIGNED)) FROM tahsilatlar WHERE makbuz_no LIKE ?");
    $stmt_max->execute(["MK-$ym-%"]);
    $max_no = $stmt_max->fetchColumn();
    $sira = ($max_no === null || $max_no === false) ? 1 : (int)$max_no + 1;
    $makbuz_no = "MK-$ym-" . str_pad($sira, 3, '0', STR_PAD_LEFT);

    $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();

        if (!empty($ay) && $miktar > 0) {
            $ay = date('Y-m', strtotime($ay . '-01'));
            $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 = (float)$aidat['miktar'] - $miktar;
                if ($kalan <= 0) {
                    $pdo->prepare("UPDATE aidatlar SET odendi = 1, odeme_tarihi = ?, tahsilat_id = ? WHERE id = ?")
                         ->execute([$tarih, $tahsilat_id, $aidat['id']]);
                } else {
                    $pdo->prepare("UPDATE aidatlar SET miktar = ? WHERE id = ?")
                         ->execute([$kalan, $aidat['id']]);
                }
            }
        }

        $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)
$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)
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) {
        $pdo->prepare("UPDATE aidatlar SET odendi = 0, odeme_tarihi = NULL, tahsilat_id = NULL WHERE tahsilat_id = ?")->execute([$_GET['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 d-flex justify-content-between align-items-center">
                    <h3 class="card-title">Tahsilat Listesi</h3>
                    <div>
                        <button class="copyTable btn btn-sm btn-info" data-table="tahsilatTable"><i class="fas fa-copy"></i> Kopyala</button>
                        <button class="exportExcel btn btn-sm btn-success" data-table="tahsilatTable"><i class="fas fa-file-excel"></i> Excel</button>
                        <button class="exportPdf btn btn-sm btn-danger" data-table="tahsilatTable"><i class="fas fa-file-pdf"></i> PDF</button>
                    </div>
                </div>
                <div class="card-body table-responsive p-0">
                    <table class="table table-hover text-nowrap" id="tahsilatTable">
                        <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?');"><i class="fas fa-trash"></i></a>
                                    </td>
                                </tr>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </section>
</div>

<script src="https://cdn.sheetjs.com/xlsx-0.20.3/package/dist/xlsx.full.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>
// Kopyala
document.querySelectorAll('.copyTable').forEach(btn => {
    btn.addEventListener('click', function() {
        const tableId = this.getAttribute('data-table');
        const table = document.getElementById(tableId);
        const range = document.createRange();
        range.selectNode(table);
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
        document.execCommand('copy');
        window.getSelection().removeAllRanges();
        alert('Tablo kopyalandı!');
    });
});

// Excel
document.querySelectorAll('.exportExcel').forEach(btn => {
    btn.addEventListener('click', function() {
        const tableId = this.getAttribute('data-table');
        const table = document.getElementById(tableId);
        const wb = XLSX.utils.table_to_book(table, {sheet: "Tahsilat"});
        XLSX.writeFile(wb, 'tahsilat_listesi.xlsx');
    });
});

// PDF (Telefon gizli)
document.querySelectorAll('.exportPdf').forEach(btn => {
    btn.addEventListener('click', function() {
        const tableId = this.getAttribute('data-table');
        const table = document.getElementById(tableId);
        
        const headers = [['Blok', 'Daire No', 'Ad Soyad', 'Tarih', 'Miktar', 'Makbuz No', 'Açıklama']];
        const data = [];
        
        table.querySelectorAll('tbody tr').forEach(row => {
            const rowData = [];
            row.querySelectorAll('td').forEach((cell, index) => {
                if (index === 0 || index === 1 || index === 2) { // Blok, Daire, Ad Soyad
                    rowData.push(cell.innerText.trim());
                } else if (index === 4) { // Tarih
                    rowData.push(cell.innerText.trim());
                } else if (index === 5) { // Miktar
                    rowData.push(cell.innerText.trim());
                } else if (index === 6) { // Makbuz
                    rowData.push(cell.innerText.trim());
                } else if (index === 7) { // Açıklama
                    rowData.push(cell.innerText.trim());
                }
            });
            data.push(rowData);
        });

        const docDefinition = {
            content: [
                { text: 'Tahsilat Listesi', style: 'header' },
                { table: { headerRows: 1, body: headers.concat(data) } }
            ],
            styles: { header: { fontSize: 18, bold: true, margin: [0, 0, 0, 10] } },
            pageOrientation: 'landscape'
        };
        pdfMake.createPdf(docDefinition).download('tahsilat_listesi.pdf');
    });
});
</script>

<?php include '../inc/footer.php'; ?>