<?php
require_once '../config/database.php';
session_start();

// Oturum kontrolü
if (!isset($_SESSION['yonetici'])) {
    header('Location: login.php');
    exit;
}

$site_id = (int)$_SESSION['site_id'];

// Alt kullanıcıysa yetki kontrolü
if (isset($_SESSION['rol']) && $_SESSION['rol'] === 'alt_kullanici') {
    $yetkiler = $_SESSION['yetkiler'] ?? [];
    
    if (!in_array('aidat_yonetimi', $yetkiler)) {
        die("Bu sayfaya erişim yetkiniz yok.");
    }
}

$basari = $hata = '';

// Aylık Aidat Ekle
if (isset($_POST['aylik_aidat_ekle'])) {
    $ay = $_POST['ay'] ?: date('Y-m');
    $miktar = (float)$_POST['miktar'] ?: 500.00;
    $stmt_uye = $pdo->prepare("SELECT id FROM uyeler WHERE site_id = ? AND aktif = 1");
    $stmt_uye->execute([$site_id]);
    $aktif_uyeler = $stmt_uye->fetchAll(PDO::FETCH_COLUMN);
    $eklenen = 0;
    foreach ($aktif_uyeler as $uye_id) {
        $check = $pdo->prepare("SELECT id FROM aidatlar WHERE uye_id = ? AND ay = ?");
        $check->execute([$uye_id, $ay]);
        if (!$check->fetch()) {
            $stmt = $pdo->prepare("INSERT INTO aidatlar (uye_id, ay, miktar) VALUES (?, ?, ?)");
            $stmt->execute([$uye_id, $ay, $miktar]);
            $eklenen++;
        }
    }
    $basari = "$eklenen üye için aylık aidat eklendi!";
}

// Düzenle (GET ile veri çek)
$duzenle = null;
if (isset($_GET['duzenle']) && is_numeric($_GET['duzenle'])) {
    $stmt = $pdo->prepare("SELECT a.*, u.blok_adi, u.daire_no, u.ad_soyad FROM aidatlar a INNER JOIN uyeler u ON a.uye_id = u.id WHERE a.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 aidatlar SET miktar = ?, odendi = ? WHERE id = ?");
    $stmt->execute([$_POST['miktar'], $_POST['odendi'], $_POST['id']]);
    $basari = "Aidat güncellendi!";
}

// Sil
if (isset($_GET['sil']) && is_numeric($_GET['sil'])) {
    $pdo->prepare("DELETE FROM aidatlar WHERE id = ?")->execute([$_GET['sil']]);
    $basari = "Aidat silindi!";
}

// Filtreleme
$where = "u.site_id = ?";
$params = [$site_id];
if (!empty($_GET['ad'])) {
    $where .= " AND u.ad_soyad LIKE ?";
    $params[] = '%' . $_GET['ad'] . '%';
}
if (!empty($_GET['ay'])) {
    $where .= " AND a.ay LIKE ?";
    $params[] = $_GET['ay'] . '%';
}
if (isset($_GET['odendi']) && $_GET['odendi'] !== '') {
    $where .= " AND a.odendi = ?";
    $params[] = (int)$_GET['odendi'];
}

// Aylık gruplama
$aylik_gruplar = [];
$stmt = $pdo->prepare("SELECT a.*, u.blok_adi, u.daire_no, u.ad_soyad, u.telefon 
                       FROM aidatlar a 
                       INNER JOIN uyeler u ON a.uye_id = u.id 
                       WHERE $where 
                       ORDER BY a.ay DESC, u.blok_adi ASC");
$stmt->execute($params);
$tum_aidatlar = $stmt->fetchAll();

foreach ($tum_aidatlar as $a) {
    $ay = $a['ay'];
    if (!isset($aylik_gruplar[$ay])) {
        $aylik_gruplar[$ay] = [];
    }
    $aylik_gruplar[$ay][] = $a;
}

// Türkçe ay isimleri
$turkce_aylar = [
    '01' => 'Ocak', '02' => 'Şubat', '03' => 'Mart', '04' => 'Nisan',
    '05' => 'Mayıs', '06' => 'Haziran', '07' => 'Temmuz', '08' => 'Ağustos',
    '09' => 'Eylül', '10' => 'Ekim', '11' => 'Kasım', '12' => 'Aralık'
];
?>

<?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-money-bill"></i> Aidat Yönetimi</h1>
        </div>
    </div>
    <section class="content">
        <div class="container-fluid">
            <?php if($basari): ?><div class="alert alert-success"><?= $basari ?></div><?php endif; ?>
            <?php if($hata): ?><div class="alert alert-danger"><?= $hata ?></div><?php endif; ?>

            <!-- Aylık Aidat Ekle Formu -->
            <div class="card card-primary mb-4">
                <div class="card-header">
                    <h3 class="card-title">Aylık Aidat Ekle (Aktif Üyelere)</h3>
                </div>
                <div class="card-body">
                    <form method="post">
                        <div class="row">
                            <div class="col-md-3"><input name="ay" type="month" class="form-control" value="<?= date('Y-m') ?>" required></div>
                            <div class="col-md-3"><input name="miktar" type="number" step="0.01" class="form-control" placeholder="Miktar (TL)" value="500.00" required></div>
                            <div class="col-md-3"><button name="aylik_aidat_ekle" class="btn btn-primary btn-block">Ekle</button></div>
                            <div class="col-md-3"><small class="text-muted">Zaten ekli ayları atlar.</small></div>
                        </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">Aidat Düzenle (<?= htmlspecialchars($duzenle['ad_soyad']) ?> - <?= $duzenle['daire_no'] ?>)</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"><input name="miktar" type="number" step="0.01" class="form-control" value="<?= $duzenle['miktar'] ?>" required></div>
                            <div class="col-md-3">
                                <select name="odendi" class="form-control">
                                    <option value="0" <?= $duzenle['odendi'] == 0 ? 'selected' : '' ?>>Ödenmedi</option>
                                    <option value="1" <?= $duzenle['odendi'] == 1 ? 'selected' : '' ?>>Ödendi</option>
                                </select>
                            </div>
                            <div class="col-md-3"><button name="guncelle" class="btn btn-warning btn-block">Güncelle</button></div>
                            <div class="col-md-3"><a href="aidat_yonetimi.php" class="btn btn-secondary btn-block">İptal</a></div>
                        </div>
                    </form>
                </div>
            </div>
            <?php endif; ?>

            <!-- Filtre Formu -->
            <form method="get" class="mb-4">
                <div class="row">
                    <div class="col-md-3"><input name="ad" class="form-control" placeholder="Ad Soyad" value="<?= htmlspecialchars($_GET['ad'] ?? '') ?>"></div>
                    <div class="col-md-3"><input name="ay" type="month" class="form-control" value="<?= htmlspecialchars($_GET['ay'] ?? '') ?>"></div>
                    <div class="col-md-3">
                        <select name="odendi" class="form-control">
                            <option value="">Ödeme Durumu</option>
                            <option value="1" <?= ($_GET['odendi'] ?? '') == '1' ? 'selected' : '' ?>>Ödendi</option>
                            <option value="0" <?= ($_GET['odendi'] ?? '') == '0' ? 'selected' : '' ?>>Ödenmedi</option>
                        </select>
                    </div>
                    <div class="col-md-3"><button type="submit" class="btn btn-primary btn-block">Filtrele</button></div>
                </div>
            </form>

            <!-- AYLIK LİSTELER -->
            <?php if (!empty($aylik_gruplar)): ?>
                <?php foreach ($aylik_gruplar as $ay => $aidat_listesi): 
                    list($yil, $ay_no) = explode('-', $ay);
                    $ay_adi = $turkce_aylar[$ay_no] . ' ' . $yil;
                ?>
                    <div class="card mb-4">
                        <div class="card-header d-flex justify-content-between align-items-center">
                            <h3 class="card-title"><?= $ay_adi ?> Aidatları</h3>
                            <div>
                                <button class="copyTable btn btn-sm btn-info" data-ay="<?= $ay ?>"><i class="fas fa-copy"></i> Kopyala</button>
                                <button class="exportExcel btn btn-sm btn-success" data-ay="<?= $ay ?>"><i class="fas fa-file-excel"></i> Excel</button>
                                <button class="exportPdf btn btn-sm btn-danger" data-ay="<?= $ay ?>"><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="table-<?= $ay ?>">
                                <thead>
                                    <tr>
                                        <th>Blok</th>
                                        <th>Daire No</th>
                                        <th>Ad Soyad</th>
                                        <th>Telefon</th>
                                        <th>Ay</th>
                                        <th>Miktar</th>
                                        <th>Durum</th>
                                        <th>İşlemler</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($aidat_listesi as $a): ?>
                                        <tr>
                                            <td><?= htmlspecialchars($a['blok_adi'] ?? '-') ?></td>
                                            <td><?= htmlspecialchars($a['daire_no']) ?></td>
                                            <td><?= htmlspecialchars($a['ad_soyad']) ?></td>
                                            <td><?= htmlspecialchars($a['telefon'] ?? '-') ?></td>
                                            <td><?= $a['ay'] ?></td>
                                            <td>₺<?= number_format($a['miktar'], 2) ?></td>
                                            <td><?= $a['odendi'] ? '<span class="badge badge-success">Ödendi</span>' : '<span class="badge badge-danger">Ödenmedi</span>' ?></td>
                                            <td>
                                                <a href="?duzenle=<?= $a['id'] ?>" class="btn btn-primary btn-sm"><i class="fas fa-edit"></i></a>
                                                <a href="?sil=<?= $a['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Silinsin mi?')"><i class="fas fa-trash"></i></a>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="card">
                    <div class="card-body text-center">
                        <p>Kayıt bulunmamaktadır.</p>
                    </div>
                </div>
            <?php endif; ?>
        </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>
document.querySelectorAll('.copyTable').forEach(btn => {
    btn.addEventListener('click', function() {
        const ay = this.getAttribute('data-ay');
        const table = document.querySelector('#table-' + ay);
        const range = document.createRange();
        range.selectNode(table);
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
        document.execCommand('copy');
        window.getSelection().removeAllRanges();
        alert('Tablo kopyalandı!');
    });
});

document.querySelectorAll('.exportExcel').forEach(btn => {
    btn.addEventListener('click', function() {
        const ay = this.getAttribute('data-ay');
        const table = document.querySelector('#table-' + ay);
        const wb = XLSX.utils.table_to_book(table, {sheet: "Aidat"});
        XLSX.writeFile(wb, 'aidat_' + ay + '.xlsx');
    });
});

document.querySelectorAll('.exportPdf').forEach(btn => {
    btn.addEventListener('click', function() {
        const ay = this.getAttribute('data-ay');
        const table = document.querySelector('#table-' + ay);
        const headers = [['Blok', 'Daire No', 'Ad Soyad', 'Telefon', 'Ay', 'Miktar', 'Durum', 'İşlemler']];
        const data = [];
        table.querySelectorAll('tbody tr').forEach(row => {
            const rowData = [];
            row.querySelectorAll('td').forEach((cell, index) => {
                if (index === 6) { // Durum badge
                    rowData.push(cell.querySelector('.badge').innerText.trim());
                } else if (index === 7) { // İşlemler
                    rowData.push('');
                } else {
                    rowData.push(cell.innerText.trim());
                }
            });
            data.push(rowData);
        });
        const docDefinition = {
            content: [
                { text: 'Aidat Listesi (' + ay + ')', 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('aidat_' + ay + '.pdf');
    });
});
</script>

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