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

/* ----------------------------
   PARAMETRE KONTROLÜ
----------------------------- */
if (!isset($_GET['daireID']) || !is_numeric($_GET['daireID'])) {
    die("Geçersiz daire.");
}
$daireID = (int)$_GET['daireID'];

/* ----------------------------
   DAİRE BİLGİSİ
----------------------------- */
$daire = db::getId("tb_daire", $daireID);
if (!$daire) die("Daire bulunamadı.");

/* ----------------------------
   BORÇ LİSTESİ
----------------------------- */
$liste = db::execAll("
    SELECT *
    FROM tb_borc
    WHERE daireID = ?
    ORDER BY ID DESC
", [$daireID]);

/* ----------------------------
   TOPLAM BORÇ
----------------------------- */
$sonuc = db::execOne("
    SELECT COALESCE(SUM(tutar),0) AS toplam
    FROM tb_borc
    WHERE daireID = ? AND durum='BORÇ'
", [$daireID]);
$toplamBorc = $sonuc->toplam;
?>

<div class="flex-fill p-4">

    <h4>🏠 Daire <?= htmlspecialchars($daire->daire_no) ?> – <?= htmlspecialchars($daire->malik_adi) ?></h4>

    <div class="alert alert-danger mt-3">
        💰 <strong>Toplam Borç:</strong> <?= number_format($toplamBorc, 2, ',', '.') ?> ₺
    </div>

    <table id="borcTable" class="table table-bordered table-hover mt-3">
        <thead class="table-light">
            <tr>
                <th>#</th>
                <th>Kategori</th>
                <th>Tutar</th>
                <th>Durum</th>
                <th>Planlanan Tarih</th>
                <th>Gerçek Ödeme</th>
                <th>İşlem</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($liste as $r): ?>
                <tr id="row-<?= $r->ID ?>" class="<?= $r->durum === 'BORÇ' ? 'table-danger' : 'table-success' ?>">
                    <td><?= $r->ID ?></td>
                    <td><?= htmlspecialchars($r->kategori) ?></td>
                    <td><?= number_format($r->tutar, 2, ',', '.') ?> ₺</td>
                    <td class="durum"><?= $r->durum ?></td>
                    <td><?= $r->odeme_tarihi ?></td>
                    <td><?= $r->gercek_odeme_tarihi ?: '-' ?></td>
                    <td>
                        <?php if ($r->durum === 'BORÇ'): ?>
                            <button class="btn btn-sm btn-success odemeBtn"
                                data-borc="<?= $r->ID ?>"
                                data-tutar="<?= $r->tutar ?>"
                                data-kategori="<?= htmlspecialchars($r->kategori) ?>">
                                &#128179; Öde
                            </button>
                        <?php else: ?>
                            <button class="btn btn-sm btn-warning iptalBtn"
                                data-odeme="<?= $r->ID ?>">
                                &#8629; İptal
                            </button>
                        <?php endif; ?>
                        <button class="btn btn-sm btn-primary guncelleBtn"
                            data-borc="<?= $r->ID ?>"
                            data-tutar="<?= $r->tutar ?>">
                            ✏️ Güncelle
                        </button>
                    </td>
                </tr>
            <?php endforeach; ?>
        </tbody>
    </table>

    <a href="index.php" class="btn btn-secondary mt-2">← Daire Listesine Dön</a>

</div>

<!-- ÖDEME MODAL -->
<div class="modal fade" id="odemeModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="odemeForm">
                <input type="hidden" name="borcID" id="borcID">
                <input type="hidden" name="odeme" value="1">

                <div class="modal-header">
                    <h5>Ödeme Onayı</h5>
                </div>
                <div class="modal-body">
                    <p>Tutar: <b id="mTutar"></b> ₺</p>
                    <p>Kategori: <b id="mKategori"></b></p>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-success">Evet, Öde</button>
                    <button class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- GÜNCELLE MODAL -->
<div class="modal fade" id="guncelleModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <form id="guncelleForm">
                <input type="hidden" name="borcID" id="gBorcID">

                <div class="modal-header">
                    <h5>Borç Tutarı Güncelle</h5>
                </div>
                <div class="modal-body">
                    <input type="number" step="0.01" name="tutar" id="gTutar" class="form-control" required>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-primary">Güncelle</button>
                    <button class="btn btn-secondary" data-bs-dismiss="modal">İptal</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>

<script>
    $(function() {

        // ÖDEME BUTONU
        $('.odemeBtn').click(function() {
            $('#borcID').val($(this).data('borc'));
            $('#mTutar').text($(this).data('tutar'));
            $('#mKategori').text($(this).data('kategori'));
            new bootstrap.Modal(document.getElementById('odemeModal')).show();
        });

        $('#odemeForm').submit(function(e) {
            e.preventDefault();
            $.post('../odeme/odeme_yap.php', $(this).serialize(), function(res) {
                if (res.success) {
                    location.reload(); // satır ve renk güncellensin
                } else {
                    alert(res.error || 'Ödeme yapılamadı');
                }
            }, 'json');
        });

        // İPTAL BUTONU
        $('.iptalBtn').click(function() {
            if (!confirm('Ödeme iptal edilsin mi?')) return;
            $.post('../odeme/odeme_yap.php', {
                odemeID: $(this).data('odeme'),
                iptal: 1
            }, function(res) {
                if (res.success) {
                    location.reload(); // satır ve renk güncellensin
                } else {
                    alert(res.error || 'İptal yapılamadı');
                }
            }, 'json');
        });

        // TUTAR GÜNCELLE
        $('.guncelleBtn').click(function() {
            $('#gBorcID').val($(this).data('borc'));
            $('#gTutar').val($(this).data('tutar'));
            new bootstrap.Modal(document.getElementById('guncelleModal')).show();
        });

        $('#guncelleForm').submit(function(e) {
            e.preventDefault();
            $.post('../odeme/guncelle_borc.php', {
                borcID: $('#gBorcID').val(),
                tutar: $('#gTutar').val()
            }, function(res) {
                if (res.success) {
                    location.reload();
                } else {
                    alert(res.error || 'Güncelleme yapılamadı');
                }
            }, 'json');
        });

    });
</script>

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