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

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

$site_id = (int)$_SESSION['site_id'];
$basari = $hata = '';
$yil = isset($_GET['yil']) ? (int)$_GET['yil'] : date('Y');

// Yıl seçenekleri (son 5 yıl)
$years = [];
for ($i = date('Y') + 1; $i >= date('Y') - 4; $i--) {
    $years[] = $i;
}

// Veri Çekme - Yıllık Borç Defteri
$stmt = $pdo->prepare("
    SELECT 
        u.id,
        u.blok_adi,
        u.daire_no,
        u.ad_soyad,
        a.ay,
        COALESCE(a.miktar, 0) as miktar,
        a.odendi
    FROM uyeler u
    LEFT JOIN aidatlar a ON u.id = a.uye_id AND a.ay LIKE ?
    WHERE u.site_id = ? AND u.aktif = 1
    ORDER BY u.blok_adi ASC, CAST(u.daire_no AS UNSIGNED) ASC, a.ay ASC
");

$stmt->execute(["$yil-%", $site_id]);
$veriler = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Veriyi üye bazında grupla
$uyeler = [];
foreach ($veriler as $v) {
    $uye_id = $v['id'];
    if (!isset($uyeler[$uye_id])) {
        $uyeler[$uye_id] = [
            'id' => $v['id'],
            'blok_adi' => $v['blok_adi'],
            'daire_no' => $v['daire_no'],
            'ad_soyad' => $v['ad_soyad'],
            'aylar' => []
        ];
    }
    $ay = substr($v['ay'], 5, 2); // 01, 02...
    $uyeler[$uye_id]['aylar'][$ay] = [
        'miktar' => $v['miktar'],
        'odendi' => $v['odendi']
    ];
}
?>
<?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-file-invoice"></i> Yıllık Borç Defteri</h1>
        </div>
    </div>

    <section class="content">
        <div class="container-fluid">
            <!-- Yıl Seçimi -->
            <div class="card mb-4">
                <div class="card-body">
                    <form method="get" class="form-inline">
                        <label class="mr-2">Yıl Seçiniz:</label>
                        <select name="yil" class="form-control mr-3" onchange="this.form.submit()">
                            <?php foreach ($years as $y): ?>
                                <option value="<?= $y ?>" <?= $y == $yil ? 'selected' : '' ?>><?= $y ?></option>
                            <?php endforeach; ?>
                        </select>
                    </form>
                </div>
            </div>

            <div class="card">
                <div class="card-header bg-info text-white">
                    <h3 class="card-title"><?= $yil ?> Yılı Borç Defteri</h3>
                </div>
                <div class="card-body table-responsive p-0">
                    <table class="table table-bordered table-hover text-center">
                        <thead class="bg-light">
                            <tr>
                                <th>Blok</th>
                                <th>Daire No</th>
                                <th>Ad Soyad</th>
                                <?php for ($m=1; $m<=12; $m++): ?>
                                    <th><?= str_pad($m, 2, '0', STR_PAD_LEFT) ?></th>
                                <?php endfor; ?>
                                <th>Toplam Borç</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if (empty($uyeler)): ?>
                                <tr><td colspan="16" class="text-center">Kayıt bulunamadı.</td></tr>
                            <?php else: ?>
                                <?php 
                                $genel_toplam = 0;
                                foreach ($uyeler as $u): 
                                    $toplam = 0;
                                ?>
                                <tr>
                                    <td><?= htmlspecialchars($u['blok_adi'] ?: '-') ?></td>
                                    <td><?= htmlspecialchars($u['daire_no']) ?></td>
                                    <td><?= htmlspecialchars($u['ad_soyad']) ?></td>
                                    <?php for ($m=1; $m<=12; $m++): 
                                        $ay = str_pad($m, 2, '0', STR_PAD_LEFT);
                                        $borc = $u['aylar'][$ay]['miktar'] ?? 0;
                                        $odendi = $u['aylar'][$ay]['odendi'] ?? 0;
                                        $toplam += $borc;
                                    ?>
                                        <td class="<?= $odendi ? 'table-success' : ($borc > 0 ? 'table-warning' : '') ?>">
                                            <?= $borc > 0 ? number_format($borc, 2) : '-' ?>
                                        </td>
                                    <?php endfor; ?>
                                    <td><strong>₺<?= number_format($toplam, 2) ?></strong></td>
                                </tr>
                                <?php 
                                $genel_toplam += $toplam;
                                endforeach; 
                                ?>
                                <tr class="table-danger font-weight-bold">
                                    <td colspan="15">GENEL TOPLAM BORÇ (<?= $yil ?>)</td>
                                    <td>₺<?= number_format($genel_toplam, 2) ?></td>
                                </tr>
                            <?php endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </section>
</div>

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