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

// Giriş yoksa
if (!isset($_SESSION['rol'])) {
    header('Location: login.php');
    exit;
}

// ALT KULLANICIYI ENGELLE
if ($_SESSION['rol'] === 'alt_kullanici') {
    header('Location: alt_dashboard.php');
    exit;
}

// Sadece yönetici rollerine izin ver
if (!in_array($_SESSION['rol'], ['superadmin', 'yonetici'])) {
    header('Location: login.php');
    exit;
}

$site_id  = (int)($_SESSION['site_id'] ?? 0);
$site_adi = $_SESSION['site_adi'] ?? 'Site';
$errors   = [];

// Helper
function safeFetchColumn($pdo, $sql, $params = [], $default = 0) {
    try {
        $stmt = $pdo->prepare($sql);
        $stmt->execute($params);
        $res = $stmt->fetchColumn();
        return $res === false ? $default : $res;
    } catch (Exception $e) {
        return $default;
    }
}

// İSTATİSTİKLER (site_id ile filtreli)
$toplam_daire = safeFetchColumn($pdo, "SELECT COUNT(*) FROM uyeler WHERE site_id = ?", [$site_id], 0);
$gelir_aylik = safeFetchColumn($pdo,
    "SELECT COALESCE(SUM(tutar),0) FROM gelir_gider WHERE site_id = ? AND tip='gelir' AND MONTH(tarih) = MONTH(NOW()) AND YEAR(tarih) = YEAR(NOW())",
    [$site_id], 0);
$gider_aylik = safeFetchColumn($pdo,
    "SELECT COALESCE(SUM(tutar),0) FROM gelir_gider WHERE site_id = ? AND tip='gider' AND MONTH(tarih) = MONTH(NOW()) AND YEAR(tarih) = YEAR(NOW())",
    [$site_id], 0);
$bakiye_aylik = $gelir_aylik - $gider_aylik;
$odeyen = safeFetchColumn($pdo,
    "SELECT COUNT(DISTINCT uye_id) FROM aidatlar WHERE site_id = ? AND odeme_durumu = 'odendi' AND MONTH(tarih) = MONTH(NOW()) AND YEAR(tarih) = YEAR(NOW())",
    [$site_id], 0);
$odemeyen = max(0, $toplam_daire - (int)$odeyen);
$banka_bakiye = safeFetchColumn($pdo, "SELECT COALESCE(SUM(bakiye),0) FROM banka_hesap WHERE site_id = ?", [$site_id], 0);
$toplam_kasa = safeFetchColumn($pdo,
    "SELECT COALESCE(SUM(CASE WHEN tip='gelir' THEN tutar ELSE -tutar END),0) FROM gelir_gider WHERE site_id = ?",
    [$site_id], 0);
// Son tahsilatlar (istenen sütunlarla)
$son_tahsilatlar = [];
try {
    $stmt = $pdo->prepare("SELECT t.miktar, t.tarih, t.aciklama, u.blok_adi, u.daire_no, u.ad_soyad
        FROM tahsilatlar t
        LEFT JOIN uyeler u ON t.uye_id = u.id
        WHERE u.site_id = ?
        ORDER BY t.tarih DESC
        LIMIT 10");
    $stmt->execute([$site_id]);
    $son_tahsilatlar = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (Exception $e) {
    $errors[] = 'Tahsilatlar yüklenemedi.';
}
// Grafik verileri
$grafik = ['haftalik'=>['labels'=>[],'gelir'=>[],'gider'=>[]],
           'aylik'=>['labels'=>[],'gelir'=>[],'gider'=>[]],
           'yillik'=>['labels'=>[],'gelir'=>[],'gider'=>[]]];
// Haftalık
for ($d = 6; $d >= 0; $d--) {
    $day = date('Y-m-d', strtotime("-$d days"));
    $label = date('d M', strtotime($day));
    $grafik['haftalik']['labels'][] = $label;
    $g = safeFetchColumn($pdo,
        "SELECT COALESCE(SUM(tutar),0) FROM gelir_gider WHERE site_id = ? AND tip='gelir' AND DATE(tarih)=?",
        [$site_id, $day], 0);
    $x = safeFetchColumn($pdo,
        "SELECT COALESCE(SUM(tutar),0) FROM gelir_gider WHERE site_id = ? AND tip='gider' AND DATE(tarih)=?",
        [$site_id, $day], 0);
    $grafik['haftalik']['gelir'][] = (float)$g;
    $grafik['haftalik']['gider'][] = (float)$x;
}
// Aylık (son 12 ay)
for ($m = 11; $m >= 0; $m--) {
    $dt = strtotime("-$m month");
    $label = date('M Y', $dt);
    $t = date('Y-m', $dt);
    $grafik['aylik']['labels'][] = $label;
    $g = safeFetchColumn($pdo,
        "SELECT COALESCE(SUM(tutar),0) FROM gelir_gider WHERE site_id = ? AND tip='gelir' AND DATE_FORMAT(tarih,'%Y-%m') = ?",
        [$site_id, $t], 0);
    $x = safeFetchColumn($pdo,
        "SELECT COALESCE(SUM(tutar),0) FROM gelir_gider WHERE site_id = ? AND tip='gider' AND DATE_FORMAT(tarih,'%Y-%m') = ?",
        [$site_id, $t], 0);
    $grafik['aylik']['gelir'][] = (float)$g;
    $grafik['aylik']['gider'][] = (float)$x;
}
// Yıllık (son 5 yıl)
$currentYear = (int)date('Y');
for ($y = $currentYear - 4; $y <= $currentYear; $y++) {
    $grafik['yillik']['labels'][] = (string)$y;
    $g = safeFetchColumn($pdo,
        "SELECT COALESCE(SUM(tutar),0) FROM gelir_gider WHERE site_id = ? AND tip='gelir' AND YEAR(tarih) = ?",
        [$site_id, $y], 0);
    $x = safeFetchColumn($pdo,
        "SELECT COALESCE(SUM(tutar),0) FROM gelir_gider WHERE site_id = ? AND tip='gider' AND YEAR(tarih) = ?",
        [$site_id, $y], 0);
    $grafik['yillik']['gelir'][] = (float)$g;
    $grafik['yillik']['gider'][] = (float)$x;
}
// Pie: bu ay gelir/gider (aylık)
$pie_gelir = (float)$gelir_aylik;
$pie_gider = (float)$gider_aylik;
// Güvenlik: JSON encode safe
$grafik_json = json_encode($grafik, JSON_NUMERIC_CHECK);
$pie_data_json = json_encode([$pie_gelir, $pie_gider], JSON_NUMERIC_CHECK);
$labels_hafta = json_encode($grafik['haftalik']['labels']);
$labels_ay = json_encode($grafik['aylik']['labels']);
$labels_yil = json_encode($grafik['yillik']['labels']);
?>
<?php include '../inc/header.php'; ?>
<?php include '../inc/sidebar.php'; ?>
<?php include '../inc/navbar.php'; ?>
<div class="content-wrapper pb-5">
  <div class="content-header">
    <div class="container-fluid">
      <h1 class="m-0 text-center text-lg-left">
        <i class="fas fa-tachometer-alt text-primary"></i> <?= htmlspecialchars($site_adi) ?> Kontrol Paneli
      </h1>
    </div>
  </div>
  <section class="content">
    <div class="container-fluid">
      <?php if (!empty($errors)): ?>
        <div class="alert alert-warning">
          <?php foreach ($errors as $er) echo htmlspecialchars($er) . '<br>'; ?>
        </div>
      <?php endif; ?>
      <!-- 8 KART -->
      <div class="row">
        <div class="col-lg-3 col-6 mb-3">
          <div class="small-box bg-info">
            <div class="inner text-center">
              <h3><?= (int)$toplam_daire ?></h3>
              <p>Toplam Daire</p>
            </div>
            <div class="icon"><i class="fas fa-home"></i></div>
          </div>
        </div>
        <div class="col-lg-3 col-6 mb-3">
          <div class="small-box bg-success">
            <div class="inner text-center">
              <h3>₺<?= number_format($gelir_aylik, 2, ',', '.') ?></h3>
              <p>Gelir (Aylık)</p>
            </div>
            <div class="icon"><i class="fas fa-arrow-up"></i></div>
          </div>
        </div>
        <div class="col-lg-3 col-6 mb-3">
          <div class="small-box bg-danger">
            <div class="inner text-center">
              <h3>₺<?= number_format($gider_aylik, 2, ',', '.') ?></h3>
              <p>Gider (Aylık)</p>
            </div>
            <div class="icon"><i class="fas fa-arrow-down"></i></div>
          </div>
        </div>
        <div class="col-lg-3 col-6 mb-3">
          <div class="small-box bg-warning">
            <div class="inner text-center">
              <h3>₺<?= number_format($bakiye_aylik, 2, ',', '.') ?></h3>
              <p>Bakiye (Aylık)</p>
            </div>
            <div class="icon"><i class="fas fa-wallet"></i></div>
          </div>
        </div>
        <div class="col-lg-3 col-6 mb-3">
          <div class="small-box bg-primary">
            <div class="inner text-center">
              <h3><?= (int)$odeyen ?></h3>
              <p>Aidat Ödeyen</p>
            </div>
            <div class="icon"><i class="fas fa-check"></i></div>
          </div>
        </div>
        <div class="col-lg-3 col-6 mb-3">
          <div class="small-box bg-secondary">
            <div class="inner text-center">
              <h3><?= (int)$odemeyen ?></h3>
              <p>Aidat Ödemeyen</p>
            </div>
            <div class="icon"><i class="fas fa-times"></i></div>
          </div>
        </div>
        <div class="col-lg-3 col-6 mb-3">
          <div class="small-box bg-info">
            <div class="inner text-center">
              <h3>₺<?= number_format($banka_bakiye, 2, ',', '.') ?></h3>
              <p>Banka Bakiyesi</p>
            </div>
            <div class="icon"><i class="fas fa-university"></i></div>
          </div>
        </div>
        <div class="col-lg-3 col-6 mb-3">
          <div class="small-box bg-dark">
            <div class="inner text-center">
              <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>
      <!-- HIZLI ERİŞİM -->
      <div class="card mb-4">
        <div class="card-header bg-gradient-navy">
          <h3 class="card-title"><i class="fas fa-rocket"></i> Hızlı Erişim</h3>
        </div>
        <div class="card-body">
          <div class="row text-center">
            <div class="col-lg-3 col-md-4 col-6 mb-3"><a href="uye_kayit.php" class="btn btn-primary btn-block btn-lg">Üye Ekle</a></div>
            <div class="col-lg-3 col-md-4 col-6 mb-3"><a href="tahsilat.php" class="btn btn-success btn-block btn-lg">Tahsilat</a></div>
            <div class="col-lg-3 col-md-4 col-6 mb-3"><a href="gelir_gider.php" class="btn btn-warning btn-block btn-lg">Gelir Gider</a></div>
            <div class="col-lg-3 col-md-4 col-6 mb-3"><a href="duyuru.php" class="btn btn-info btn-block btn-lg">Duyuru</a></div>
            <div class="col-lg-3 col-md-4 col-6 mb-3"><a href="anket.php" class="btn btn-danger btn-block btn-lg">Anket</a></div>
            <div class="col-lg-3 col-md-4 col-6 mb-3"><a href="guvenlik_takip.php" class="btn btn-dark btn-block btn-lg">Güvenlik</a></div>
            <div class="col-lg-3 col-md-4 col-6 mb-3"><a href="rapor_merkezi.php" class="btn btn-secondary btn-block btn-lg">Raporlar</a></div>
            <div class="col-lg-3 col-md-4 col-6 mb-3"><a href="aidat_yonetimi.php" class="btn btn-warning btn-block btn-lg">Aidat</a></div>
          </div>
        </div>
      </div>
      <!-- GRAFİKLER -->
      <div class="row">
        <div class="col-lg-8 mb-4">
          <div class="card">
            <div class="card-header bg-gradient-info d-flex justify-content-between align-items-center">
              <h3 class="card-title"><i class="fas fa-chart-line"></i> Gelir & Gider</h3>
              <div>
                <button class="btn btn-sm btn-outline-secondary mr-1" id="btn_hafta">Haftalık</button>
                <button class="btn btn-sm btn-outline-secondary mr-1 active" id="btn_ay">Aylık</button>
                <button class="btn btn-sm btn-outline-secondary" id="btn_yil">Yıllık</button>
              </div>
            </div>
            <div class="card-body">
              <canvas id="lineChart" height="120"></canvas>
            </div>
          </div>
        </div>
        <div class="col-lg-4 mb-4">
          <div class="card">
            <div class="card-header bg-gradient-warning">
              <h3 class="card-title"><i class="fas fa-chart-pie"></i> Aylık Pay Dağılımı</h3>
            </div>
            <div class="card-body">
              <canvas id="pieChart" height="200"></canvas>
              <div class="mt-3 text-center">
                <span class="badge badge-success">Gelir: ₺<?= number_format($pie_gelir,2,',','.') ?></span>
                <span class="badge badge-danger">Gider: ₺<?= number_format($pie_gider,2,',','.') ?></span>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- SON TAHSİLATLAR -->
      <div class="card">
        <div class="card-header bg-gradient-dark">
          <h3 class="card-title"><i class="fas fa-hand-holding-dollar"></i> Son Tahsilatlar</h3>
        </div>
        <div class="card-body table-responsive p-0">
          <table class="table table-striped">
            <thead>
              <tr>
                <th>Blok</th>
                <th>Daire No</th>
                <th>Ad Soyad</th>
                <th>Tarih</th>
                <th>Miktar</th>
                <th>Açıklama</th>
              </tr>
            </thead>
            <tbody>
              <?php if (empty($son_tahsilatlar)): ?>
                <tr><td colspan="6" class="text-center text-muted">Henüz tahsilat bulunmuyor.</td></tr>
              <?php else: ?>
                <?php foreach ($son_tahsilatlar as $t): ?>
                  <tr>
                    <td><?= htmlspecialchars($t['blok_adi'] ?? '-') ?></td>
                    <td><?= htmlspecialchars($t['daire_no'] ?? '-') ?></td>
                    <td><?= htmlspecialchars($t['ad_soyad'] ?? '-') ?></td>
                    <td><?= date('d.m.Y', strtotime($t['tarih'])) ?></td>
                    <td class="text-success font-weight-bold">₺<?= number_format($t['miktar'],2,',','.') ?></td>
                    <td><?= htmlspecialchars($t['aciklama'] ?? '-') ?></td>
                  </tr>
                <?php endforeach; ?>
              <?php endif; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </section>
</div>
<!-- MOBİL İÇİN RAKAM TAŞMASINI ÖNLEYEN CSS -->
<style>
    @media (max-width: 991.98px) {
        .small-box h3 { font-size: 2rem !important; margin-bottom: 5px !important; }
        .small-box p { font-size: 0.9rem !important; }
    }
    @media (max-width: 767.98px) {
        .small-box h3 { font-size: 1.8rem !important; line-height: 1.2; }
        .small-box .inner { padding: 15px !important; }
        .small-box .icon { font-size: 3rem !important; top: 10px; }
    }
    @media (max-width: 575.98px) {
        .small-box h3 { font-size: 1.5rem !important; }
        .small-box p { font-size: 0.85rem !important; }
        .small-box .inner { padding: 10px !important; }
    }
    .small-box h3 { word-wrap: break-word; overflow-wrap: break-word; white-space: normal; }
</style>
<!-- Chart.js -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script>
<script>
const grafik = <?= $grafik_json ?>;
const pieData = <?= $pie_data_json ?>;
const labelsH = <?= $labels_hafta ?>;
const labelsM = <?= $labels_ay ?>;
const labelsY = <?= $labels_yil ?>;
const ctxLine = document.getElementById('lineChart').getContext('2d');
let currentMode = 'aylik'; // default
let lineChart = new Chart(ctxLine, {
    type: 'line',
    data: {
        labels: grafik['aylik']['labels'],
        datasets: [
            {
                label: 'Gelir',
                data: grafik['aylik']['gelir'],
                borderColor: '#007bff',
                backgroundColor: 'rgba(0,123,255,0.15)',
                tension: 0.3,
                fill: true
            },
            {
                label: 'Gider',
                data: grafik['aylik']['gider'],
                borderColor: '#dc3545',
                backgroundColor: 'rgba(220,53,69,0.15)',
                tension: 0.3,
                fill: true
            }
        ]
    },
    options: {
        responsive: true,
        plugins: { legend: { position: 'top' } },
        scales: { y: { beginAtZero: true } }
    }
});
// Pie
const ctxPie = document.getElementById('pieChart').getContext('2d');
let pieChart = new Chart(ctxPie, {
    type: 'pie',
    data: {
        labels: ['Gelir','Gider'],
        datasets: [{ data: pieData, backgroundColor: ['#28a745','#dc3545'] }]
    },
    options: { responsive: true }
});
// Buttons
document.getElementById('btn_hafta').addEventListener('click', function(){
    updateLine('haftalik');
});
document.getElementById('btn_ay').addEventListener('click', function(){
    updateLine('aylik');
});
document.getElementById('btn_yil').addEventListener('click', function(){
    updateLine('yillik');
});
function updateLine(mode){
    currentMode = mode;
    lineChart.data.labels = grafik[mode]['labels'];
    lineChart.data.datasets[0].data = grafik[mode]['gelir'];
    lineChart.data.datasets[1].data = grafik[mode]['gider'];
    lineChart.update();
    // active button styling
    document.getElementById('btn_hafta').classList.remove('active');
    document.getElementById('btn_ay').classList.remove('active');
    document.getElementById('btn_yil').classList.remove('active');
    if(mode==='haftalik') document.getElementById('btn_hafta').classList.add('active');
    if(mode==='aylik') document.getElementById('btn_ay').classList.add('active');
    if(mode==='yillik') document.getElementById('btn_yil').classList.add('active');
}
</script>
<?php include '../inc/footer.php'; ?>