<?php
require_once '../config/database.php';
session_start();
if (!isset($_SESSION['yonetici'])) header('Location: login.php');
$site_id = (int)$_SESSION['site_id'];
$basari = $hata = '';
// DEMİRBAŞ EKLE / GÜNCELLE
if (isset($_POST['demirbas_ekle'])) {
    $stmt = $pdo->prepare("INSERT INTO demirbaslar (site_id, ad, adet, birim_fiyat, aciklama) VALUES (?,?,?,?,?)");
    $stmt->execute([$site_id, $_POST['ad'], $_POST['adet'], $_POST['birim_fiyat'], $_POST['aciklama']]);
    $basari = "Demirbaş eklendi!";
}
if (isset($_POST['demirbas_guncelle'])) {
    $stmt = $pdo->prepare("UPDATE demirbaslar SET ad=?, adet=?, birim_fiyat=?, aciklama=? WHERE id=? AND site_id=?");
    $stmt->execute([$_POST['ad'], $_POST['adet'], $_POST['birim_fiyat'], $_POST['aciklama'], $_POST['demirbas_id'], $site_id]);
    $basari = "Demirbaş güncellendi!";
}
// DEMİRBAŞ SİL
if (isset($_GET['sil_demirbas'])) {
    $pdo->prepare("DELETE FROM demirbaslar WHERE id=? AND site_id=?")->execute([$_GET['sil_demirbas'], $site_id]);
    $basari = "Demirbaş silindi!";
}
// BORÇLANDIR
if (isset($_POST['borclandir'])) {
    $stmt = $pdo->prepare("INSERT INTO demirbas_borclar (demirbas_id, uye_id, tutar) VALUES (?,?,?)");
    $stmt->execute([$_POST['demirbas_id'], $_POST['uye_id'], $_POST['tutar']]);
    // Üyenin toplam borcuna ekle
    $pdo->prepare("UPDATE uyeler SET borc = borc + ? WHERE id = ?")->execute([$_POST['tutar'], $_POST['uye_id']]);
    $basari = "Üye borçlandırıldı!";
}
// BORÇ GÜNCELLE
if (isset($_POST['borc_guncelle'])) {
    $eskiStmt = $pdo->prepare("SELECT tutar, uye_id FROM demirbas_borclar WHERE id = ?");
    $eskiStmt->execute([$_POST['borc_id']]);
    $eski = $eskiStmt->fetch();
    $fark = $_POST['yeni_tutar'] - $eski['tutar'];
    $pdo->prepare("UPDATE demirbas_borclar SET tutar = ? WHERE id = ?")->execute([$_POST['yeni_tutar'], $_POST['borc_id']]);
    // Üyenin toplam borcunu güncelle
    $pdo->prepare("UPDATE uyeler SET borc = borc + ? WHERE id = ?")->execute([$fark, $eski['uye_id']]);
    $basari = "Borç güncellendi!";
}
// BORÇ SİL
if (isset($_GET['sil_borc'])) {
    $eskiStmt = $pdo->prepare("SELECT tutar, uye_id FROM demirbas_borclar WHERE id = ?");
    $eskiStmt->execute([$_GET['sil_borc']]);
    $eski = $eskiStmt->fetch();
    $pdo->prepare("DELETE FROM demirbas_borclar WHERE id = ?")->execute([$_GET['sil_borc']]);
    // Üyenin toplam borcundan çıkar
    $pdo->prepare("UPDATE uyeler SET borc = borc - ? WHERE id = ?")->execute([$eski['tutar'], $eski['uye_id']]);
    $basari = "Borç silindi!";
}
// ÖDEME YAP
if (isset($_POST['odeme_yap'])) {
    $eskiStmt = $pdo->prepare("SELECT tutar, uye_id FROM demirbas_borclar WHERE id = ?");
    $eskiStmt->execute([$_POST['borc_id']]);
    $eski = $eskiStmt->fetch();
    $pdo->prepare("UPDATE demirbas_borclar SET odendi=1, odeme_tarihi=NOW() WHERE id=?")->execute([$_POST['borc_id']]);
    // Üyenin toplam borcundan çıkar
    $pdo->prepare("UPDATE uyeler SET borc = borc - ? WHERE id = ?")->execute([$eski['tutar'], $eski['uye_id']]);
    $basari = "Ödeme yapıldı!";
}
// LİSTELER
$demirbaslar = $pdo->prepare("SELECT * FROM demirbaslar WHERE site_id = ? ORDER BY id DESC");
$demirbaslar->execute([$site_id]);
$demirbaslar = $demirbaslar->fetchAll();
$borclar = $pdo->query("SELECT b.*, d.ad as demirbas_ad, u.ad_soyad, u.daire_no
                        FROM demirbas_borclar b
                        JOIN demirbaslar d ON b.demirbas_id = d.id
                        JOIN uyeler u ON b.uye_id = u.id
                        WHERE d.site_id = $site_id ORDER BY b.id DESC")->fetchAll();
$uyeler = $pdo->query("SELECT id, ad_soyad, daire_no FROM uyeler WHERE site_id = $site_id ORDER BY ad_soyad")->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"><h1>Demirbaş Yönetimi</h1></div></div>
  <section class="content"><div class="container-fluid">
    <?php if($basari): ?><div class="alert alert-success"><?= $basari ?></div><?php endif; ?>
    <!-- YENİ DEMİRBAŞ EKLE -->
    <div class="card card-primary mb-4">
      <div class="card-header"><h3 class="card-title">Yeni Demirbaş Ekle</h3></div>
      <div class="card-body">
        <form method="post">
          <div class="row">
            <div class="col-md-4"><input name="ad" class="form-control mb-2" placeholder="Demirbaş Adı (Klima, Jeneratör vb.)" required></div>
            <div class="col-md-2"><input name="adet" type="number" class="form-control mb-2" value="1" required></div>
            <div class="col-md-3"><input name="birim_fiyat" type="number" step="0.01" class="form-control mb-2" placeholder="Birim Fiyat" required></div>
            <div class="col-md-3"><textarea name="aciklama" class="form-control mb-2" placeholder="Açıklama"></textarea></div>
            <div class="col-12 text-right"><button name="demirbas_ekle" class="btn btn-success btn-lg">EKLE</button></div>
          </div>
        </form>
      </div>
    </div>
    <!-- DEMİRBAŞ LİSTESİ -->
    <div class="card mb-4">
      <div class="card-header">
        <h3 class="card-title">Demirbaşlar</h3>
        <div class="card-tools">
          <button class="btn btn-sm btn-success" onclick="exportToExcel('demirbasTable', 'demirbaslar')">Excel İndir</button>
          <button class="btn btn-sm btn-danger" onclick="window.print()">PDF Yazdır</button>
        </div>
      </div>
      <div class="card-body table-responsive p-0">
        <table class="table table-hover" id="demirbasTable">
          <thead>
            <tr>
              <th>Ad</th>
              <th>Adet</th>
              <th>Birim Fiyat</th>
              <th>Toplam</th>
              <th>Açıklama</th>
              <th>İşlem</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach($demirbaslar as $d): ?>
            <tr>
              <td><?= htmlspecialchars($d['ad']) ?></td>
              <td><?= $d['adet'] ?></td>
              <td>₺<?= number_format($d['birim_fiyat'],2) ?></td>
              <td>₺<?= number_format($d['adet'] * $d['birim_fiyat'],2) ?></td> <!-- Toplam hesaplandı -->
              <td><?= htmlspecialchars($d['aciklama'] ?: '-') ?></td>
              <td>
                <button class="btn btn-info btn-sm editDemirbasBtn" data-toggle="modal" data-target="#editDemirbasModal" data-id="<?= $d['id'] ?>" data-ad="<?= htmlspecialchars($d['ad']) ?>" data-adet="<?= $d['adet'] ?>" data-fiyat="<?= $d['birim_fiyat'] ?>" data-aciklama="<?= htmlspecialchars($d['aciklama']) ?>">Düzenle</button>
                <a href="?sil_demirbas=<?= $d['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Silmek istediğinize emin misiniz?')">Sil</a>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
    <!-- ÜYE BORÇLANDIR -->
    <div class="card card-warning mb-4">
      <div class="card-header"><h3 class="card-title">Üye Borçlandır</h3></div>
      <div class="card-body">
        <form method="post">
          <div class="row">
            <div class="col-md-4">
              <select name="demirbas_id" class="form-control mb-2" required>
                <option value="">Demirbaş Seç</option>
                <?php foreach($demirbaslar as $d): ?>
                  <option value="<?= $d['id'] ?>"><?= htmlspecialchars($d['ad']) ?> (₺<?= number_format($d['adet'] * $d['birim_fiyat']) ?>)</option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-4">
              <select name="uye_id" class="form-control mb-2" required>
                <option value="">Üye Seç</option>
                <?php foreach($uyeler as $u): ?>
                  <option value="<?= $u['id'] ?>"><?= htmlspecialchars($u['ad_soyad']) ?> - <?= $u['daire_no'] ?></option>
                <?php endforeach; ?>
              </select>
            </div>
            <div class="col-md-2"><input name="tutar" type="number" step="0.01" class="form-control mb-2" placeholder="Borç Tutarı" required></div>
            <div class="col-md-2"><button name="borclandir" class="btn btn-warning btn-block">Borçlandır</button></div>
          </div>
        </form>
      </div>
    </div>
    <!-- BORÇ LİSTESİ -->
    <div class="card">
      <div class="card-header">
        <h3 class="card-title">Demirbaş Borçları</h3>
        <div class="card-tools">
          <button class="btn btn-sm btn-success" onclick="exportToExcel('borcTable', 'demirbas_borclari')">Excel İndir</button>
          <button class="btn btn-sm btn-danger" onclick="window.print()">PDF Yazdır</button>
        </div>
      </div>
      <div class="card-body table-responsive p-0">
        <table class="table table-hover" id="borcTable">
          <thead>
            <tr>
              <th>Üye</th>
              <th>Demirbaş</th>
              <th>Tutar</th>
              <th>Durum</th>
              <th>İşlem</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach($borclar as $b): ?>
            <tr>
              <td><?= htmlspecialchars($b['ad_soyad']) ?> (<?= $b['daire_no'] ?>)</td>
              <td><?= htmlspecialchars($b['demirbas_ad']) ?></td>
              <td>₺<?= number_format($b['tutar']) ?></td>
              <td><span class="badge <?= $b['odendi'] ? 'bg-success' : 'bg-danger' ?>"><?= $b['odendi'] ? 'Ödendi' : 'Bekliyor' ?></span></td>
              <td>
                <?php if(!$b['odendi']): ?>
                  <form method="post" class="d-inline">
                    <input type="hidden" name="borc_id" value="<?= $b['id'] ?>">
                    <button name="odeme_yap" class="btn btn-success btn-sm"><i class="fas fa-check"></i></button>
                  </form>
                  <button class="btn btn-info btn-sm editBorcBtn" data-toggle="modal" data-target="#editBorcModal" data-id="<?= $b['id'] ?>" data-tutar="<?= $b['tutar'] ?>">Düzenle</button>
                <?php endif; ?>
                <a href="?sil_borc=<?= $b['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Silmek istediğinize emin misiniz?')">Sil</a>
              </td>
            </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div></section>
</div>
<!-- DEMİRBAŞ DÜZENLE MODAL -->
<div class="modal fade" id="editDemirbasModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Demirbaş Düzenle</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
        <form method="post">
          <input type="hidden" name="demirbas_id" value="">
          <input name="ad" class="form-control mb-2" placeholder="Ad" required>
          <input name="adet" type="number" class="form-control mb-2" required>
          <input name="birim_fiyat" type="number" step="0.01" class="form-control mb-2" placeholder="Birim Fiyat" required>
          <textarea name="aciklama" class="form-control mb-2" placeholder="Açıklama"></textarea>
          <button name="demirbas_guncelle" class="btn btn-primary">Güncelle</button>
        </form>
      </div>
    </div>
  </div>
</div>
<!-- BORÇ DÜZENLE MODAL -->
<div class="modal fade" id="editBorcModal">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h4 class="modal-title">Borç Düzenle</h4>
        <button type="button" class="close" data-dismiss="modal">&times;</button>
      </div>
      <div class="modal-body">
        <form method="post">
          <input type="hidden" name="borc_id" value="">
          <input name="yeni_tutar" type="number" step="0.01" class="form-control" placeholder="Yeni Tutar" required>
          <button name="borc_guncelle" class="btn btn-primary mt-2">Güncelle</button>
        </form>
      </div>
    </div>
  </div>
</div>
<?php include '../inc/footer.php'; ?>
<script>
$('.editDemirbasBtn').on('click', function() {
  var modal = $('#editDemirbasModal');
  modal.find('input[name="demirbas_id"]').val($(this).data('id'));
  modal.find('input[name="ad"]').val($(this).data('ad'));
  modal.find('input[name="adet"]').val($(this).data('adet'));
  modal.find('input[name="birim_fiyat"]').val($(this).data('fiyat'));
  modal.find('textarea[name="aciklama"]').val($(this).data('aciklama'));
});
$('.editBorcBtn').on('click', function() {
  var modal = $('#editBorcModal');
  modal.find('input[name="borc_id"]').val($(this).data('id'));
  modal.find('input[name="yeni_tutar"]').val($(this).data('tutar'));
});
function exportToExcel(tableId, filename = '') {
  var downloadLink;
  var dataType = 'application/vnd.ms-excel';
  var tableSelect = document.getElementById(tableId);
  var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
  filename = filename ? filename + '.xls' : 'excel_data.xls';
  downloadLink = document.createElement("a");
  document.body.appendChild(downloadLink);
  if (navigator.msSaveOrOpenBlob) {
    var blob = new Blob(['\ufeff', tableHTML], { type: dataType });
    navigator.msSaveOrOpenBlob(blob, filename);
  } else {
    downloadLink.href = 'data:' + dataType + ',' + tableHTML;
    downloadLink.download = filename;
    downloadLink.click();
  }
}
</script>