<?php
require_once '../../config.php';
require_once ROOT . 'app/db.php';
require_once ROOT . 'layout/header.php';
require_once ROOT . 'layout/sidebar.php';

// Ay ve Yıl
$ay  = $_GET['ay'] ?? date('m');
$yil = $_GET['yil'] ?? date('Y');

// Aidatları tb_borc üzerinden çek
$aidatlar = db::execAll("
    SELECT 
        b.ID AS aidatID,
        d.ID AS daireID,
        d.daire_no,
        d.malik_adi,
        b.tutar,
        b.durum,
        b.odeme_tarihi,
        b.gercek_odeme_tarihi
    FROM tb_borc b
    INNER JOIN tb_daire d ON d.ID = b.daireID
    WHERE b.kategori='Aidat' AND MONTH(b.odeme_tarihi)=? AND YEAR(b.odeme_tarihi)=?
    ORDER BY d.daire_no ASC
", [$ay, $yil]);
?>

<div class="flex-fill p-4">
    <h4>Aidat Takibi (<?= $ay ?>/<?= $yil ?>)</h4>

    <!-- Ay/Yıl Seçimi -->
    <form class="row g-2 mb-3" method="get">
        <div class="col-md-2">
            <select name="ay" class="form-select">
                <?php for ($i = 1; $i <= 12; $i++): ?>
                    <option value="<?= $i ?>" <?= $i == $ay ? 'selected' : '' ?>><?= $i ?></option>
                <?php endfor; ?>
            </select>
        </div>
        <div class="col-md-2">
            <select name="yil" class="form-select">
                <?php for ($y = 2023; $y <= date('Y') + 1; $y++): ?>
                    <option value="<?= $y ?>" <?= $y == $yil ? 'selected' : '' ?>><?= $y ?></option>
                <?php endfor; ?>
            </select>
        </div>
        <div class="col-md-2">
            <button class="btn btn-primary">Göster</button>
        </div>
        <div class="col-md-3">
            <button type="button" class="btn btn-success" data-bs-toggle="modal" data-bs-target="#uretModal">
                Aidat Üret
            </button>
        </div>
    </form>

    <!-- Tablo -->
    <table id="daireTable" class="table table-bordered table-hover align-middle">
        <thead class="table-dark">
            <tr>
                <th>#</th>
                <th>Daire</th>
                <th>Malik</th>
                <th>Tutar</th>
                <th>Durum</th>
                <th>Planlanan Tarih</th>
                <th>Ödeme Tarihi</th>
                <th>İşlem</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($aidatlar as $a): ?>
                <tr id="row-<?= $a->aidatID ?>" class="<?= $a->durum === 'BORÇ' ? 'table-danger' : 'table-success' ?>">
                    <td><?= $a->aidatID ?></td>
                    <td><?= $a->daire_no ?></td>
                    <td><?= $a->malik_adi ?></td>
                    <td><?= number_format($a->tutar, 2, ',', '.') ?> ₺</td>
                    <td class="durum"><?= $a->durum ?></td>
                    <td><?= $a->odeme_tarihi ?></td>
                    <td class="gercek_odeme"><?= $a->gercek_odeme_tarihi ?: '-' ?></td>
                    <td>
                        <?php if ($a->durum === 'BORÇ'): ?>
                            <button class="btn btn-sm btn-success odemeBtn"
                                data-id="<?= $a->aidatID ?>"
                                data-tutar="<?= $a->tutar ?>">
                                💳 Öde
                            </button>
                        <?php else: ?>
                            <button class="btn btn-sm btn-warning iptalBtn"
                                data-id="<?= $a->aidatID ?>">
                                ↩️ İptal
                            </button>
                            <a href="odeme_fis.php?borcID=<?= $a->aidatID ?>" class="btn btn-sm btn-outline-secondary">
                                🧾 Fiş
                            </a>
                        <?php endif; ?>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>
</div>

<!-- Aidat Üret Modal -->
<div class="modal fade" id="uretModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" action="toplu_aidat.php">
                <div class="modal-header">
                    <h5 class="modal-title">Aidat Üret</h5>
                </div>
                <div class="modal-body">
                    <p><strong><?= $ay ?>/<?= $yil ?></strong> için aidat üretilecek.</p>
                    <input type="number" step="0.01" name="tutar" class="form-control" placeholder="Aidat Tutarı" required>
                    <input type="hidden" name="ay" value="<?= $ay ?>">
                    <input type="hidden" name="yil" value="<?= $yil ?>">
                    <div class="alert alert-warning mt-2">
                        Emin misiniz? Aynı ay için tekrar üretilmez.
                    </div>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                    <button class="btn btn-success">Üret</button>
                </div>
            </form>
        </div>
    </div>
</div>

<script src="<?= BASE_URL ?>assets/js/jquery.min.js"></script>
<script src="<?= BASE_URL ?>assets/bootstrap/js/bootstrap.bundle.min.js"></script>
<link rel="stylesheet" href="<?= BASE_URL ?>assets/datatables/datatables.min.css" />
<script src="<?= BASE_URL ?>assets/datatables/datatables.min.js"></script>
<script>
    $(document).ready(function() {
        $('#daireTable').DataTable({
            "paging": false,
            "lengthChange": false,
            "searching": true,
            "ordering": true,
            "info": true,
            "autoWidth": false,
            "language": {
                "url": "//cdn.datatables.net/plug-ins/1.13.6/i18n/tr.json"
            }
        });
    });
</script>
<script>
    $(function() {

        // Ödeme al
        $('.odemeBtn').click(function() {
            let id = $(this).data('id');
            $.post('../odeme/odeme_yap.php', {
                borcID: id,
                odeme: 1
            }, function(res) {
                if (res.success) {
                    let row = $('#row-' + id);
                    row.find('.durum').text('ÖDENDİ');
                    row.find('.gercek_odeme').text(new Date().toISOString().slice(0, 10));
                    row.find('td:last').html(
                        '<button class="btn btn-sm btn-warning iptalBtn" data-id="' + id + '">↩️ İptal</button> ' +
                        '<a href="odeme_fis.php?borcID=' + id + '" class="btn btn-sm btn-outline-secondary">🧾 Fiş</a>'
                    );
                } else alert(res.error || 'Ödeme yapılamadı');
            }, 'json');
        });

        // Ödeme iptal
        $(document).on('click', '.iptalBtn', function() {
            let id = $(this).data('id');
            $.post('../odeme/odeme_yap.php', {
                odemeID: id,
                iptal: 1
            }, function(res) {
                if (res.success) {
                    let row = $('#row-' + id);
                    row.find('.durum').text('BORÇ');
                    row.find('.gercek_odeme').text('-');
                    row.find('td:last').html('<button class="btn btn-sm btn-success odemeBtn" data-id="' + id + '" data-tutar="">💳 Öde</button>');
                } else alert(res.error || 'İptal yapılamadı');
            }, 'json');
        });

    });
</script>

<?php require_once ROOT . 'layout/footer.php'; ?>