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

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

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

if (isset($_SESSION['rol']) && $_SESSION['rol'] === 'alt_kullanici') {
    $yetkiler = $_SESSION['yetkiler'] ?? [];
    if (!in_array('isletme_defteri', $yetkiler)) {
        die("Bu sayfaya erişim yetkiniz yok.");
    }
}

$basari = '';
$hata = '';
$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'];

// ====================== İÇE AKTARIM ======================
if (isset($_POST['ice_aktar']) && !empty($_POST['ay'])) {
    $secilen_ay = $_POST['ay'];
    list($yil, $ay) = explode('-', $secilen_ay);
    try {
        $kontrol = $pdo->prepare("SELECT COUNT(*) FROM isletme_defteri WHERE site_id = ? AND YEAR(tarih) = ? AND MONTH(tarih) = ?");
        $kontrol->execute([$site_id, (int)$yil, (int)$ay]);
        if ($kontrol->fetchColumn() > 0) {
            throw new Exception("Bu aya ait kayıtlar zaten işletme defterinde mevcut.");
        }
        $stmt_select = $pdo->prepare("SELECT tip, tutar, aciklama, tarih FROM gelir_gider WHERE site_id = ? AND YEAR(tarih) = ? AND MONTH(tarih) = ?");
        $stmt_select->execute([$site_id, (int)$yil, (int)$ay]);
        $kayitlar = $stmt_select->fetchAll();

        if (empty($kayitlar)) {
            $hata = "Seçilen ayda kayıt bulunamadı.";
        } else {
            $stmt_insert = $pdo->prepare("INSERT INTO isletme_defteri (site_id, tip, tutar, aciklama, tarih) VALUES (?, ?, ?, ?, ?)");
            $eklenen = 0;
            foreach ($kayitlar as $k) {
                $stmt_insert->execute([$site_id, $k['tip'], $k['tutar'], $k['aciklama'], $k['tarih']]);
                $eklenen++;
            }
            $basari = "{$secilen_ay} ayı başarıyla kopyalandı. Toplam {$eklenen} kayıt aktarıldı.";
        }
    } catch (Exception $e) {
        $hata = "Aktarım sırasında hata oluştu: " . $e->getMessage();
    }
}

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

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

// ====================== GÜNCELLE ======================
if (isset($_POST['guncelle'])) {
    $stmt = $pdo->prepare("UPDATE isletme_defteri SET tip = ?, tutar = ?, aciklama = ?, tarih = ? WHERE id = ? AND site_id = ?");
    $stmt->execute([
        $_POST['tip'], $_POST['tutar'],
        !empty($_POST['aciklama']) ? trim($_POST['aciklama']) : null,
        $_POST['tarih'],
        (int)$_POST['id'], $site_id
    ]);
    $basari = "Kayıt başarıyla güncellendi.";
}

// ====================== SİL ======================
if (isset($_GET['sil']) && is_numeric($_GET['sil'])) {
    $stmt = $pdo->prepare("DELETE FROM isletme_defteri WHERE id = ? AND site_id = ?");
    $stmt->execute([(int)$_GET['sil'], $site_id]);
    $basari = "Kayıt başarıyla silindi.";
}

// ====================== TOPLAMLAR ======================
$stmt_toplam = $pdo->prepare("
    SELECT SUM(CASE WHEN tip='gelir' THEN tutar ELSE 0 END) as toplam_gelir,
           SUM(CASE WHEN tip='gider' THEN tutar ELSE 0 END) as toplam_gider
    FROM isletme_defteri WHERE site_id = ?
");
$stmt_toplam->execute([$site_id]);
$toplamlar = $stmt_toplam->fetch();
$toplam_gelir = (float)($toplamlar['toplam_gelir'] ?? 0);
$toplam_gider = (float)($toplamlar['toplam_gider'] ?? 0);

// ====================== AYLIK VERİLER + DÜZELTİLMİŞ DEVİR BAKİYE ======================
$aylik_veriler = [];
$stmt = $pdo->prepare("
    SELECT DATE_FORMAT(tarih, '%Y-%m') AS ay, tip, SUM(tutar) AS toplam 
    FROM isletme_defteri WHERE site_id = ? 
    GROUP BY ay, tip ORDER BY ay ASC
");
$stmt->execute([$site_id]);
$sonuclar = $stmt->fetchAll();

$kumulatif = 0.0;

// Önce tüm ayları oluştur ve gelir/giderleri topla
foreach ($sonuclar as $row) {
    $ay = $row['ay'];
    if (!isset($aylik_veriler[$ay])) {
        $aylik_veriler[$ay] = [
            'gelir' => 0,
            'gider' => 0,
            'devir_bakiye' => 0
        ];
    }
    $aylik_veriler[$ay][$row['tip']] = (float)$row['toplam'];
}

// Şimdi devir bakiyeleri ve kümülatif bakiyeleri doğru şekilde hesapla
foreach ($aylik_veriler as $ay => &$veri) {
    $veri['devir_bakiye'] = $kumulatif;                    // Önceki aydan devreden
    $veri['ay_bakiye']   = $veri['gelir'] - $veri['gider'];
    $kumulatif          += $veri['ay_bakiye'];
    $veri['toplam_kasa'] = $kumulatif;
}
unset($veri);

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

<?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">
            <div class="row mb-2">
                <div class="col-sm-6">
                    <h1 class="m-0"><i class="fas fa-book"></i> İşletme Defteri</h1>
                </div>
            </div>
        </div>
    </div>

    <section class="content">
        <div class="container-fluid">
            <?php if ($basari): ?><div class="alert alert-success"><?= htmlspecialchars($basari) ?></div><?php endif; ?>
            <?php if ($hata): ?><div class="alert alert-danger"><?= htmlspecialchars($hata) ?></div><?php endif; ?>

            <!-- İÇE AKTAR -->
            <div class="card mb-4">
                <div class="card-header bg-info">
                    <h3 class="card-title text-white">Gelir-Gider'den Ay Seçerek Kopyala</h3>
                </div>
                <div class="card-body">
                    <form method="post" class="row align-items-center">
                        <div class="col-md-5">
                            <select name="ay" class="form-control" required>
                                <option value="">— Ay Seçiniz —</option>
                                <?php
                                $ay_listesi = $pdo->prepare("SELECT DISTINCT DATE_FORMAT(tarih, '%Y-%m') as ay FROM gelir_gider WHERE site_id = ? ORDER BY ay DESC");
                                $ay_listesi->execute([$site_id]);
                                $mevcut_aylar = $ay_listesi->fetchAll(PDO::FETCH_COLUMN);
                                foreach ($mevcut_aylar as $ay_item):
                                    list($y, $m) = explode('-', $ay_item);
                                ?>
                                    <option value="<?= $ay_item ?>"><?= $turkce_aylar[$m] . ' ' . $y ?></option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <button type="submit" name="ice_aktar" class="btn btn-info btn-block" onclick="return confirm('Seçilen ay kopyalanacak. Emin misiniz?')">
                                <i class="fas fa-copy"></i> Seçili Ayı Kopyala
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- ÖZET KARTLARI -->
            <div class="row">
                <div class="col-lg-4 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-4 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-4 col-6">
                    <div class="small-box bg-info">
                        <div class="inner"><h3>₺<?= number_format($kumulatif, 2) ?></h3><p>Toplam Kasa</p></div>
                        <div class="icon"><i class="fas fa-wallet"></i></div>
                    </div>
                </div>
            </div>

            <!-- EKLE / DÜZENLE -->
            <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-4 col-sm-6">
                                <input name="aciklama" class="form-control mb-2" placeholder="Açıklama" 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-1 col-sm-12">
                                <button name="<?= $duzenle ? 'guncelle' : 'ekle' ?>" class="btn btn-warning btn-block"><?= $duzenle ? 'Güncelle' : 'Ekle' ?></button>
                            </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;
                ?>
                    <div class="card mb-5">
                        <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
                            <h3><?= $ay_adi ?> Ayı İşletme Defteri</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">
                            <h5 class="text-success"><strong>GELİRLER</strong></h5>
                            <table class="table table-hover text-nowrap" id="table-<?= $ay ?>-gelir">
                                <thead><tr><th>Sıra</th><th>Tarih</th><th>Açıklama</th><th>Tutar</th><th>İş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><?= $sira++ ?></td>
                                            <td><?= date('d.m.Y', strtotime($i['tarih'])) ?></td>
                                            <td><?= htmlspecialchars($i['uye_bilgisi']) ?></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>

                            <h5 class="text-danger mt-4"><strong>GİDERLER</strong></h5>
                            <table class="table table-hover text-nowrap" id="table-<?= $ay ?>-gider">
                                <thead><tr><th>Sıra</th><th>Tarih</th><th>Açıklama</th><th>Tutar</th><th>İş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><?= $sira++ ?></td>
                                            <td><?= date('d.m.Y', strtotime($i['tarih'])) ?></td>
                                            <td><?= htmlspecialchars($i['uye_bilgisi']) ?></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 bg-light">
                            <div class="row text-center">
                                <div class="col-md-3">
                                    <strong>Devir Eden Bakiye</strong><br>
                                    ₺<?= number_format($veri['devir_bakiye'], 2) ?>
                                </div>
                                <div class="col-md-3">
                                    <strong>Toplam Gelir</strong><br>
                                    ₺<?= number_format($veri['gelir'], 2) ?>
                                </div>
                                <div class="col-md-3">
                                    <strong>Toplam Gider</strong><br>
                                    ₺<?= number_format($veri['gider'], 2) ?>
                                </div>
                                <div class="col-md-3">
                                    <strong>Ay Bakiyesi</strong><br>
                                    <span class="<?= $veri['ay_bakiye'] >= 0 ? 'text-success' : 'text-danger' ?>">₺<?= number_format($veri['ay_bakiye'], 2) ?></span>
                                </div>
                            </div>
                            <hr>
                            <h5 class="text-right">
                                <strong>Toplam Kasa Bakiyesi: ₺<?= number_format($veri['toplam_kasa'], 2) ?></strong>
                            </h5>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?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>
// PDF (Dikey + Düzeltilmiş Devir Bakiye)
document.querySelectorAll('.exportPdf').forEach(btn => {
    btn.addEventListener('click', function () {
        const ay = this.dataset.ay;
        const gelirTable = document.getElementById(`table-${ay}-gelir`);
        const giderTable = document.getElementById(`table-${ay}-gider`);
        const footer = gelirTable.closest('.card').querySelector('.card-footer');
        const cols = footer.querySelectorAll('.col-md-3');

        const devirTutar = cols[0]?.innerText.split('\n').pop().trim() || '₺0.00';

        const docDefinition = {
            pageOrientation: 'portrait',
            pageSize: 'A4',
            content: [
                { text: `İŞLETME DEFTERİ - ${ay}`, style: 'header' },
                { text: 'ÖNCEKİ AY DEVİR BAKİYESİ', style: 'devirHeader' },
                { text: devirTutar, style: 'devirValue' },
                // Gelir, Gider ve Özet tabloları (kısaltıldı)
                { text: 'GELİRLER', style: 'sectionGreen', margin: [0,15,0,8] },
                { table: { widths: ['auto','auto','*','auto'], body: getTableBody(gelirTable) }, layout: 'lightHorizontalLines' },
                { text: `Toplam Gelir: ${cols[1]?.innerText.split('\n').pop().trim()}`, style: 'summaryGreen' },
                { text: 'GİDERLER', style: 'sectionRed', margin: [0,20,0,8] },
                { table: { widths: ['auto','auto','*','auto'], body: getTableBody(giderTable) }, layout: 'lightHorizontalLines' },
                { text: `Toplam Gider: ${cols[2]?.innerText.split('\n').pop().trim()}`, style: 'summaryRed' },
                { text: 'AYLIK ÖZET', style: 'sectionBlue', margin: [0,25,0,10] },
                { table: { widths: ['*','*'], body: [
                    [{text: 'Devir Bakiye: ' + devirTutar, margin:[5,8,5,8]}, {text: cols[1]?.innerText.split('\n').pop().trim(), margin:[5,8,5,8]}],
                    [{text: cols[2]?.innerText.split('\n').pop().trim(), margin:[5,8,5,8]}, {text: cols[3]?.innerText.split('\n').pop().trim(), margin:[5,8,5,8]}],
                    [{text: footer.querySelector('h5')?.innerText.trim(), colSpan:2, alignment:'center', bold:true, fontSize:13, margin:[0,12,0,8]}, {}]
                ]}}
            ],
            styles: {
                header: {fontSize:16, bold:true, alignment:'center', margin:[0,0,0,15]},
                devirHeader: {fontSize:13, bold:true, color:'#0066cc', margin:[0,8,0,5]},
                devirValue: {fontSize:15, bold:true, margin:[0,0,0,15]},
                sectionGreen: {fontSize:14, bold:true, color:'#fff', fillColor:'#28a745', alignment:'center'},
                sectionRed: {fontSize:14, bold:true, color:'#fff', fillColor:'#dc3545', alignment:'center'},
                sectionBlue: {fontSize:14, bold:true, color:'#fff', fillColor:'#007bff', alignment:'center'},
                summaryGreen: {bold:true, fontSize:12, color:'#28a745', margin:[0,5,0,8]},
                summaryRed: {bold:true, fontSize:12, color:'#dc3545', margin:[0,5,0,8]}
            }
        };
        pdfMake.createPdf(docDefinition).download(`isletme_defteri_${ay}.pdf`);
    });
});

function getTableBody(table) {
    const body = [[{text:'Sıra', bold:true}, {text:'Tarih', bold:true}, {text:'Açıklama', bold:true}, {text:'Tutar', bold:true}]];
    table.querySelectorAll('tbody tr').forEach(row => {
        const cells = row.querySelectorAll('td');
        body.push([cells[0]?.innerText.trim()||'', cells[1]?.innerText.trim()||'', cells[2]?.innerText.trim()||'', cells[3]?.innerText.trim()||'']);
    });
    return body;
}
</script>

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