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

// EKLE
if (isset($_POST['kaydet'])) {
    $blok_adi = trim($_POST['blok_adi'] ?? '');
    $daire_no = trim($_POST['daire_no'] ?? '');
    $ay_yil = $_POST['ay_yil'] ?? '';
    $onceki_endeks = (float)($_POST['onceki_endeks'] ?? 0);
    $son_endeks = (float)($_POST['son_endeks'] ?? 0);
    $fatura_tutar = (float)($_POST['fatura_tutar'] ?? 0);

    if ($blok_adi === '' || $daire_no === '' || $ay_yil === '' || $son_endeks < $onceki_endeks || $fatura_tutar <= 0) {
        $hata = 'Geçersiz veya eksik bilgi girdiniz. Son endeks önceki endeksten büyük olmalı.';
    } else {
        try {
            $stmt = $pdo->prepare("INSERT INTO sayac_okumalari (site_id, blok_adi, daire_no, ay_yil, onceki_endeks, son_endeks, fatura_tutar, odendi) VALUES (?, ?, ?, ?, ?, ?, ?, 0)");
            $stmt->execute([$site_id, $blok_adi, $daire_no, $ay_yil, $onceki_endeks, $son_endeks, $fatura_tutar]);
            $basari = "Sayaç okuma başarıyla kaydedildi!";
        } catch (Exception $e) {
            $hata = "Veritabanı hatası: " . $e->getMessage();
        }
    }
}

// SİL
if (isset($_GET['sil']) && is_numeric($_GET['sil'])) {
    $id = (int)$_GET['sil'];
    try {
        $stmt = $pdo->prepare("DELETE FROM sayac_okumalari WHERE id = ? AND site_id = ?");
        $stmt->execute([$id, $site_id]);
        $basari = "Okuma kaydı silindi!";
        header('Location: sayac_okuma.php');
        exit;
    } catch (Exception $e) {
        $hata = "Silme hatası: " . $e->getMessage();
    }
}

// ÖDEME YAP
if (isset($_POST['odeme_yap'])) {
    $id = (int)$_POST['id'];
    try {
        $stmt = $pdo->prepare("UPDATE sayac_okumalari SET odendi = 1 WHERE id = ? AND site_id = ?");
        $stmt->execute([$id, $site_id]);
        $basari = "Ödeme işaretlendi!";
    } catch (Exception $e) {
        $hata = "İşlem hatası: " . $e->getMessage();
    }
}

// LİSTE (Aylık gruplama ile)
try {
    $stmt = $pdo->prepare("
        SELECT s.*, u.ad_soyad, u.blok_adi AS uye_blok, (s.son_endeks - s.onceki_endeks) AS tuketim
        FROM sayac_okumalari s
        LEFT JOIN uyeler u ON s.daire_no = u.daire_no AND s.blok_adi = u.blok_adi AND u.site_id = ?
        WHERE s.site_id = ?
        ORDER BY s.ay_yil DESC, s.blok_adi, s.daire_no
    ");
    $stmt->execute([$site_id, $site_id]);
    $tum_okumalar = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Aylık gruplama
    $okumalar_aylik = [];
    foreach ($tum_okumalar as $o) {
        $ay = $o['ay_yil'];
        $okumalar_aylik[$ay][] = $o;
    }
} catch (Exception $e) {
    $okumalar_aylik = [];
    $hata = "Veriler yüklenemedi: " . $e->getMessage();
}
?>
<?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>Sayaç Okuma ve Faturalandırma</h1>
    </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; ?>

      <!-- YENİ OKUMA EKLE -->
      <div class="card card-primary mb-4">
        <div class="card-header">
          <h3 class="card-title">Yeni Sayaç Okuma Ekle</h3>
        </div>
        <div class="card-body">
          <form method="post">
            <div class="row">
              <div class="col-md-2">
                <label>Blok</label>
                <input name="blok_adi" class="form-control mb-2" placeholder="A, B, C..." required>
              </div>
              <div class="col-md-2">
                <label>Daire No</label>
                <input name="daire_no" class="form-control mb-2" placeholder="Daire No" required>
              </div>
              <div class="col-md-2">
                <label>Ay/Yıl</label>
                <input name="ay_yil" type="month" class="form-control mb-2" value="<?= date('Y-m') ?>" required>
              </div>
              <div class="col-md-2">
                <label>Önceki Endeks</label>
                <input name="onceki_endeks" type="number" step="0.01" class="form-control mb-2" placeholder="Önceki" required>
              </div>
              <div class="col-md-2">
                <label>Son Endeks</label>
                <input name="son_endeks" type="number" step="0.01" class="form-control mb-2" placeholder="Son" required>
              </div>
              <div class="col-md-2">
                <label>Fatura Tutarı</label>
                <input name="fatura_tutar" type="number" step="0.01" class="form-control mb-2" placeholder="Tutar" required>
              </div>
              <div class="col-md-12 text-right mt-3">
                <button name="kaydet" class="btn btn-primary btn-lg">Kaydet</button>
              </div>
            </div>
          </form>
        </div>
      </div>

<!-- AYLIK LİSTE -->
<?php if (empty($okumalar_aylik)): ?>
  <div class="alert alert-info">Henüz sayaç okuma kaydı bulunmamaktadır.</div>
<?php else: ?>
  <?php 
  $turkce_aylar = [
      'January' => 'Ocak', 'February' => 'Şubat', 'March' => 'Mart', 'April' => 'Nisan',
      'May' => 'Mayıs', 'June' => 'Haziran', 'July' => 'Temmuz', 'August' => 'Ağustos',
      'September' => 'Eylül', 'October' => 'Ekim', 'November' => 'Kasım', 'December' => 'Aralık'
  ];
  ?>
  <?php foreach ($okumalar_aylik as $ay => $okumalar): ?>
    <?php 
    $ingilizce_ay = date('F', strtotime($ay . '-01'));
    $turkce_ay = $turkce_aylar[$ingilizce_ay] ?? $ingilizce_ay;
    $yil = date('Y', strtotime($ay . '-01'));
    ?>
    <div class="card mb-4">
      <div class="card-header bg-secondary text-white">
        <h3 class="card-title"><?= $turkce_ay ?> <?= $yil ?> Okumaları</h3>
      </div>
            <div class="card-body table-responsive p-0">
              <table class="table table-hover table-bordered">
                <thead class="bg-light">
                  <tr>
                    <th>Blok</th>
                    <th>Daire No</th>
                    <th>Ad Soyad</th>
                    <th>Tüketim</th>
                    <th>Fatura Tutarı</th>
                    <th>Durum</th>
                    <th>İşlem</th>
                  </tr>
                </thead>
                <tbody>
                  <?php foreach ($okumalar as $o): ?>
                    <tr>
                      <td><?= htmlspecialchars($o['blok_adi'] ?? $o['uye_blok'] ?? '-') ?></td>
                      <td><?= htmlspecialchars($o['daire_no']) ?></td>
                      <td><?= htmlspecialchars($o['ad_soyad'] ?? 'Bilinmiyor') ?></td>
                      <td><?= number_format($o['tuketim'], 2, ',', '.') ?></td>
                      <td>₺<?= number_format($o['fatura_tutar'], 2, ',', '.') ?></td>
                      <td>
                        <span class="badge <?= $o['odendi'] ? 'bg-success' : 'bg-danger' ?>">
                          <?= $o['odendi'] ? 'Ödendi' : 'Ödenmedi' ?>
                        </span>
                      </td>
                      <td>
                        <?php if (!$o['odendi']): ?>
                          <form method="post" class="d-inline">
                            <input type="hidden" name="id" value="<?= (int)$o['id'] ?>">
                            <button name="odeme_yap" class="btn btn-success btn-sm" onclick="return confirm('Bu fatura ödendi olarak işaretlensin mi?')">
                              Ödendi
                            </button>
                          </form>
                        <?php endif; ?>
                        <a href="?sil=<?= $o['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Bu okuma kaydını silmek istediğinize emin misiniz?')">
                          Sil
                        </a>
                      </td>
                    </tr>
                  <?php endforeach; ?>
                </tbody>
              </table>
            </div>
          </div>
        <?php endforeach; ?>
      <?php endif; ?>
    </div>
  </section>
</div>
<?php include '../inc/footer.php'; ?>