<?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('gelir_gider', $yetkiler)) {
        die("Bu sayfaya erişim yetkiniz yok.");
    }
}

$basari = '';

// EKLE
if (isset($_POST['ekle'])) {
    $stmt = $pdo->prepare("INSERT INTO gelir_gider (site_id, tip, tutar, aciklama, tarih) VALUES (?, ?, ?, ?, ?)");
    $stmt->execute([
        $site_id,
        $_POST['tip'],
        $_POST['tutar'],
        $_POST['aciklama'] ?: null,
        $_POST['tarih'] ?: date('Y-m-d')
    ]);
    $basari = "Kayıt eklendi!";
}

// DÜZENLE (GET)
$duzenle = null;
if (isset($_GET['duzenle']) && is_numeric($_GET['duzenle'])) {
    $stmt = $pdo->prepare("SELECT * FROM gelir_gider WHERE id = ? AND site_id = ?");
    $stmt->execute([$_GET['duzenle'], $site_id]);
    $duzenle = $stmt->fetch();
}

// DÜZENLE (POST)
if (isset($_POST['guncelle'])) {
    $stmt = $pdo->prepare("UPDATE gelir_gider SET tip = ?, tutar = ?, aciklama = ?, tarih = ? WHERE id = ? AND site_id = ?");
    $stmt->execute([
        $_POST['tip'],
        $_POST['tutar'],
        $_POST['aciklama'] ?: null,
        $_POST['tarih'],
        $_POST['id'],
        $site_id
    ]);
    $basari = "Kayıt güncellendi!";
}

// SİL
if (isset($_GET['sil']) && is_numeric($_GET['sil'])) {
    $pdo->prepare("DELETE FROM gelir_gider WHERE id=? AND site_id=?")->execute([(int)$_GET['sil'], $site_id]);
    $basari = "Silindi!";
}

// ====================== AYLIK VERİLER ======================
$aylik_veriler = [];
$stmt = $pdo->prepare("
    SELECT DATE_FORMAT(tarih, '%Y-%m') AS ay, tip, SUM(tutar) AS toplam
    FROM gelir_gider WHERE site_id = ?
    GROUP BY ay, tip ORDER BY ay DESC
");
$stmt->execute([$site_id]);
$sonuclar = $stmt->fetchAll();

foreach ($sonuclar as $row) {
    $ay = $row['ay'];
    if (!isset($aylik_veriler[$ay])) {
        $aylik_veriler[$ay] = ['gelir' => 0, 'gider' => 0, 'bakiye' => 0];
    }
    $aylik_veriler[$ay][$row['tip']] = $row['toplam'];
    $aylik_veriler[$ay]['bakiye'] = $aylik_veriler[$ay]['gelir'] - $aylik_veriler[$ay]['gider'];
}

// ====================== TÜM İŞLEMLER - ÜYE BİLGİSİYLE ======================
$islem = $pdo->prepare("
    SELECT g.*, 
           u.blok_adi,
           u.daire_no,
           u.ad_soyad,
           CONCAT(COALESCE(u.blok_adi, ''), ' Blok - ', COALESCE(u.daire_no, ''), ' - ', COALESCE(u.ad_soyad, '')) as uye_bilgisi
    FROM gelir_gider g
    LEFT JOIN uyeler u ON g.aciklama LIKE CONCAT('%Üye ID: ', u.id, '%')
    WHERE g.site_id = ?
    ORDER BY g.tarih ASC, g.id ASC
");
$islem->execute([$site_id]);
$tum_islemler = $islem->fetchAll();

// Genel toplamlar
$toplam_gelir = $pdo->query("SELECT COALESCE(SUM(tutar),0) FROM gelir_gider WHERE site_id = $site_id AND tip='gelir'")->fetchColumn();
$toplam_gider = $pdo->query("SELECT COALESCE(SUM(tutar),0) FROM gelir_gider WHERE site_id = $site_id AND tip='gider'")->fetchColumn();
$toplam_bakiye = $toplam_gelir - $toplam_gider;
$toplam_kasa = $toplam_bakiye;

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

<style>
@media (max-width: 768px) {
    .small-box h3 { font-size: 1.6rem !important; }
    .small-box p { font-size: 0.85rem !important; }
}
</style>

<div class="content-wrapper">
    <div class="content-header">
        <div class="container-fluid">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0"><i class="fas fa-exchange-alt"></i> Gelir - Gider Yönetimi</h1>
                </div>
            </div>
        </div>
    </div>

    <section class="content">
        <div class="container-fluid">
            <?php if($basari): ?>
                <div class="alert alert-success alert-dismissible fade show">
                    <?= $basari ?>
                    <button type="button" class="close" data-dismiss="alert">&times;</button>
                </div>
            <?php endif; ?>

            <!-- 4 ADET KART -->
            <div class="row">
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-success">
                        <div class="inner">
                            <h3>₺<?= number_format($toplam_gelir, 2) ?></h3>
                            <p>Toplam Gelir</p>
                        </div>
                        <div class="icon"><i class="fas fa-arrow-up"></i></div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-danger">
                        <div class="inner">
                            <h3>₺<?= number_format($toplam_gider, 2) ?></h3>
                            <p>Toplam Gider</p>
                        </div>
                        <div class="icon"><i class="fas fa-arrow-down"></i></div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-info">
                        <div class="inner">
                            <h3>₺<?= number_format($toplam_bakiye, 2) ?></h3>
                            <p>Toplam Bakiye</p>
                        </div>
                        <div class="icon"><i class="fas fa-wallet"></i></div>
                    </div>
                </div>
                <div class="col-lg-3 col-6">
                    <div class="small-box bg-primary">
                        <div class="inner">
                            <h3>₺<?= number_format($toplam_kasa, 2) ?></h3>
                            <p>Toplam Kasa</p>
                        </div>
                        <div class="icon"><i class="fas fa-cash-register"></i></div>
                    </div>
                </div>
            </div>

            <!-- EKLE / DÜZENLE FORMU -->
            <div class="card card-warning mb-4">
                <div class="card-header">
                    <h3 class="card-title"><?= $duzenle ? 'Kayıt Düzenle' : 'Yeni Kayıt Ekle' ?></h3>
                </div>
                <div class="card-body">
                    <form method="post">
                        <?php if($duzenle): ?><input type="hidden" name="id" value="<?= $duzenle['id'] ?>"><?php endif; ?>
                        <div class="row">
                            <div class="col-md-2 col-sm-6">
                                <select name="tip" class="form-control mb-2" required>
                                    <option value="gelir" <?= ($duzenle && $duzenle['tip']=='gelir') ? 'selected' : '' ?>>Gelir</option>
                                    <option value="gider" <?= ($duzenle && $duzenle['tip']=='gider') ? 'selected' : '' ?>>Gider</option>
                                </select>
                            </div>
                            <div class="col-md-3 col-sm-6">
                                <input name="tutar" type="number" step="0.01" class="form-control mb-2" placeholder="Tutar" value="<?= $duzenle ? $duzenle['tutar'] : '' ?>" required>
                            </div>
                            <div class="col-md-3 col-sm-6">
                                <input name="aciklama" class="form-control mb-2" placeholder="Üye Bilgisi (Blok Daire No - İsim Soyisim)" value="<?= $duzenle ? htmlspecialchars($duzenle['aciklama']) : '' ?>">
                            </div>
                            <div class="col-md-2 col-sm-6">
                                <input name="tarih" type="date" class="form-control mb-2" value="<?= $duzenle ? $duzenle['tarih'] : date('Y-m-d') ?>" required>
                            </div>
                            <div class="col-md-2 col-sm-12">
                                <button name="<?= $duzenle ? 'guncelle' : 'ekle' ?>" class="btn btn-warning btn-block mb-2">
                                    <?= $duzenle ? 'Güncelle' : 'Ekle' ?>
                                </button>
                                <?php if($duzenle): ?>
                                    <a href="gelir_gider.php" class="btn btn-secondary btn-block">İptal</a>
                                <?php endif; ?>
                            </div>
                        </div>
                    </form>
                </div>
            </div>

            <!-- AYLIK LİSTELER -->
            <?php if (!empty($aylik_veriler)): ?>
                <?php foreach ($aylik_veriler as $ay => $veri):
                    list($yil, $ay_no) = explode('-', $ay);
                    $ay_adi = $turkce_aylar[$ay_no] . ' ' . $yil;
                ?>
                    <!-- GELİR TABLOSU -->
                    <div class="card mb-4">
                        <div class="card-header d-flex justify-content-between align-items-center bg-success">
                            <h3 class="card-title text-white"><?= $ay_adi ?> Ayı Gelirleri</h3>
                            <div>
                                <button class="copyTable btn btn-sm btn-info" data-ay="<?= $ay ?>" data-tip="gelir"><i class="fas fa-copy"></i> Kopyala</button>
                                <button class="exportExcel btn btn-sm btn-success" data-ay="<?= $ay ?>" data-tip="gelir"><i class="fas fa-file-excel"></i> Excel</button>
                                <button class="exportPdf btn btn-sm btn-danger" data-ay="<?= $ay ?>" data-tip="gelir"><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 ?>-gelir">
                                <thead>
                                    <tr>
                                        <th style="width:70px;">Sıra</th>
                                        <th style="width:110px;">Tarih</th>
                                        <th>Üye Bilgisi</th>
                                        <th style="width:140px;">Tutar</th>
                                        <th style="width:110px;">İşlemler</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $sira = 1;
                                    foreach ($tum_islemler as $i):
                                        if (substr($i['tarih'], 0, 7) !== $ay || $i['tip'] !== 'gelir') continue;
                                    ?>
                                        <tr>
                                            <td><strong><?= $sira++ ?></strong></td>
                                            <td><?= date('d.m.Y', strtotime($i['tarih'])) ?></td>
                                            <td><?= htmlspecialchars($i['uye_bilgisi'] ?: $i['aciklama']) ?></td>
                                            <td><strong>₺<?= number_format($i['tutar'], 2) ?></strong></td>
                                            <td>
                                                <a href="?duzenle=<?= $i['id'] ?>" class="btn btn-primary btn-sm"><i class="fas fa-edit"></i></a>
                                                <a href="?sil=<?= $i['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 class="card-footer">
                            <span class="badge badge-success">Toplam Gelir: ₺<?= number_format($veri['gelir'], 2) ?></span>
                        </div>
                    </div>

                    <!-- GİDER TABLOSU -->
                    <div class="card mb-4">
                        <div class="card-header d-flex justify-content-between align-items-center bg-danger">
                            <h3 class="card-title text-white"><?= $ay_adi ?> Ayı Giderleri</h3>
                            <div>
                                <button class="copyTable btn btn-sm btn-info" data-ay="<?= $ay ?>" data-tip="gider"><i class="fas fa-copy"></i> Kopyala</button>
                                <button class="exportExcel btn btn-sm btn-success" data-ay="<?= $ay ?>" data-tip="gider"><i class="fas fa-file-excel"></i> Excel</button>
                                <button class="exportPdf btn btn-sm btn-danger" data-ay="<?= $ay ?>" data-tip="gider"><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 ?>-gider">
                                <thead>
                                    <tr>
                                        <th style="width:70px;">Sıra</th>
                                        <th style="width:110px;">Tarih</th>
                                        <th>Üye Bilgisi / Açıklama</th>
                                        <th style="width:140px;">Tutar</th>
                                        <th style="width:110px;">İşlemler</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php
                                    $sira = 1;
                                    foreach ($tum_islemler as $i):
                                        if (substr($i['tarih'], 0, 7) !== $ay || $i['tip'] !== 'gider') continue;
                                    ?>
                                        <tr>
                                            <td><strong><?= $sira++ ?></strong></td>
                                            <td><?= date('d.m.Y', strtotime($i['tarih'])) ?></td>
                                            <td><?= htmlspecialchars($i['aciklama'] ?: '-') ?></td>
                                            <td><strong>₺<?= number_format($i['tutar'], 2) ?></strong></td>
                                            <td>
                                                <a href="?duzenle=<?= $i['id'] ?>" class="btn btn-primary btn-sm"><i class="fas fa-edit"></i></a>
                                                <a href="?sil=<?= $i['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 class="card-footer">
                            <span class="badge badge-danger">Toplam Gider: ₺<?= number_format($veri['gider'], 2) ?></span>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php else: ?>
                <div class="card">
                    <div class="card-body text-center">
                        <p>Henüz kayıt bulunmamaktadır.</p>
                    </div>
                </div>
            <?php endif; ?>
        </div>
    </section>
</div>

<!-- Export Scripts -->
<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, Excel, PDF scriptleri (orijinal ile aynı)
document.querySelectorAll('.copyTable').forEach(btn => {
    btn.addEventListener('click', function() {
        const ay = this.getAttribute('data-ay');
        const tip = this.getAttribute('data-tip');
        const table = document.querySelector(`#table-${ay}-${tip}`);
        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 tip = this.getAttribute('data-tip');
        const table = document.querySelector(`#table-${ay}-${tip}`);
        const wb = XLSX.utils.table_to_book(table, {sheet: tip.toUpperCase()});
        XLSX.writeFile(wb, `${tip}_${ay}.xlsx`);
    });
});

document.querySelectorAll('.exportPdf').forEach(btn => {
    btn.addEventListener('click', function() {
        const ay = this.getAttribute('data-ay');
        const tip = this.getAttribute('data-tip');
        const table = document.querySelector(`#table-${ay}-${tip}`);
        const headers = [['Sıra', 'Tarih', 'Üye Bilgisi', 'Tutar', 'İşlemler']];
        const data = [];
        table.querySelectorAll('tbody tr').forEach(row => {
            const rowData = [];
            row.querySelectorAll('td').forEach((cell, index) => {
                if (index === 4) rowData.push('');
                else rowData.push(cell.innerText.trim());
            });
            data.push(rowData);
        });
        const docDefinition = {
            content: [{ text: `${tip.toUpperCase()} 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(`${tip}_${ay}.pdf`);
    });
});
</script>

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