<?php
require_once '../config/database.php';
session_start();
if (!isset($_SESSION['admin'])) header('Location: login.php');

$basari = $hata = '';

// EKLE
if (isset($_POST['ekle'])) {
    try {
        $stmt = $pdo->prepare("INSERT INTO admin_gelir_gider (tip, tutar, aciklama, tarih) VALUES (?, ?, ?, ?)");
        $stmt->execute([
            $_POST['tip'],
            $_POST['tutar'],
            $_POST['aciklama'] ?: null,
            $_POST['tarih'] ?: date('Y-m-d')
        ]);
        header("Location: gelir_gider.php?ok=1");
        exit;
    } catch (Exception $e) {
        $hata = "Ekleme hatası: " . $e->getMessage();
    }
}

// DÜZENLE
if (isset($_POST['duzenle'])) {
    try {
        $stmt = $pdo->prepare("UPDATE admin_gelir_gider SET tip=?, tutar=?, aciklama=?, tarih=? WHERE id=?");
        $stmt->execute([
            $_POST['tip'],
            $_POST['tutar'],
            $_POST['aciklama'] ?: null,
            $_POST['tarih'],
            $_POST['id']
        ]);
        header("Location: gelir_gider.php?guncelle=1");
        exit;
    } catch (Exception $e) {
        $hata = "Güncelleme hatası: " . $e->getMessage();
    }
}

// SİL
if (isset($_GET['sil']) && is_numeric($_GET['sil'])) {
    try {
        $pdo->prepare("DELETE FROM admin_gelir_gider WHERE id=?")->execute([(int)$_GET['sil']]);
        header("Location: gelir_gider.php?sil=1");
        exit;
    } catch (Exception $e) {
        $hata = "Silme hatası: " . $e->getMessage();
    }
}

// FİLTRELEME
$where = "1=1";
$params = [];
$selectedTip = $_GET['tip'] ?? '';
$baslangic = $_GET['baslangic'] ?? '';
$bitis = $_GET['bitis'] ?? '';

if ($selectedTip !== '') { $where .= " AND tip = ?"; $params[] = $selectedTip; }
if ($baslangic !== '') { $where .= " AND tarih >= ?"; $params[] = $baslangic; }
if ($bitis !== '') { $where .= " AND tarih <= ?"; $params[] = $bitis; }

$stmt = $pdo->prepare("SELECT * FROM admin_gelir_gider WHERE $where ORDER BY tarih DESC, id DESC");
$stmt->execute($params);
$islem = $stmt->fetchAll();

// TOPLAMLAR
$toplam = $pdo->query("SELECT
    COALESCE(SUM(CASE WHEN tip='gelir' THEN tutar ELSE 0 END),0) as gelir,
    COALESCE(SUM(CASE WHEN tip='gider' THEN tutar ELSE 0 END),0) as gider
    FROM admin_gelir_gider")->fetch();

$bakiye = $toplam['gelir'] - $toplam['gider'];
?>

<?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 class="m-0"><i class="fas fa-money-bill-wave"></i> Şirket Gelir & Gider Yönetimi</h1>
    </div>
  </div>

  <section class="content">
    <div class="container-fluid">
      <?php if(isset($_GET['ok'])): ?><div class="alert alert-success">Kayıt eklendi.</div><?php endif; ?>
      <?php if(isset($_GET['guncelle'])): ?><div class="alert alert-success">Kayıt güncellendi.</div><?php endif; ?>
      <?php if(isset($_GET['sil'])): ?><div class="alert alert-success">Kayıt silindi.</div><?php endif; ?>
      <?php if($hata): ?><div class="alert alert-danger"><?= htmlspecialchars($hata) ?></div><?php endif; ?>

      <!-- TOPLAM KARTLAR -->
      <div class="row mb-4">
        <div class="col-lg-4 col-12">
          <div class="info-box bg-success">
            <span class="info-box-icon"><i class="fas fa-arrow-up"></i></span>
            <div class="info-box-content">
              <span class="info-box-text">Toplam Gelir</span>
              <span class="info-box-number">₺<?= number_format($toplam['gelir'],0,'','.') ?></span>
            </div>
          </div>
        </div>
        <div class="col-lg-4 col-12">
          <div class="info-box bg-danger">
            <span class="info-box-icon"><i class="fas fa-arrow-down"></i></span>
            <div class="info-box-content">
              <span class="info-box-text">Toplam Gider</span>
              <span class="info-box-number">₺<?= number_format($toplam['gider'],0,'','.') ?></span>
            </div>
          </div>
        </div>
        <div class="col-lg-4 col-12">
          <div class="info-box bg-warning">
            <span class="info-box-icon"><i class="fas fa-wallet"></i></span>
            <div class="info-box-content">
              <span class="info-box-text">Net Bakiye</span>
              <span class="info-box-number">₺<?= number_format($bakiye,0,'','.') ?></span>
            </div>
          </div>
        </div>
      </div>

      <!-- EKLE + FİLTRE -->
      <div class="card card-primary mb-4">
        <div class="card-header">
          <h3 class="card-title">Yeni Kayıt Ekle</h3>
        </div>
        <div class="card-body">
          <form method="post" class="row g-3">
            <div class="col-md-2">
              <select name="tip" class="form-control" required>
                <option value="gelir">Gelir</option>
                <option value="gider">Gider</option>
              </select>
            </div>
            <div class="col-md-3">
              <input name="tutar" type="number" step="0.01" class="form-control" placeholder="Tutar" required>
            </div>
            <div class="col-md-4">
              <input name="aciklama" class="form-control" placeholder="Açıklama">
            </div>
            <div class="col-md-2">
              <input name="tarih" type="date" class="form-control" value="<?= date('Y-m-d') ?>" required>
            </div>
            <div class="col-md-1">
              <button type="submit" name="ekle" class="btn btn-success btn-block">EKLE</button>
            </div>
          </form>

          <form method="get" class="row g-3 mt-4">
            <div class="col-md-3">
              <select name="tip" class="form-control">
                <option value="">Tümü</option>
                <option value="gelir" <?= $selectedTip=='gelir'?'selected':'' ?>>Gelir</option>
                <option value="gider" <?= $selectedTip=='gider'?'selected':'' ?>>Gider</option>
              </select>
            </div>
            <div class="col-md-3"><input name="baslangic" type="date" class="form-control" value="<?= htmlspecialchars($baslangic) ?>"></div>
            <div class="col-md-3"><input name="bitis" type="date" class="form-control" value="<?= htmlspecialchars($bitis) ?>"></div>
            <div class="col-md-3">
              <button type="submit" class="btn btn-info">Filtrele</button>
              <a href="gelir_gider.php" class="btn btn-secondary">Temizle</a>
            </div>
          </form>
        </div>
      </div>

      <!-- TABLO -->
      <div class="card">
        <div class="card-header bg-gradient-navy">
          <h3 class="card-title text-white">İşlem Geçmişi (<?= count($islem) ?> kayıt)</h3>
        </div>
        <div class="card-body table-responsive p-0">
          <table class="table table-striped table-hover" id="gelirGiderTablosu">
            <thead>
              <tr>
                <th>#</th>
                <th>Tarih</th>
                <th>Tip</th>
                <th>Tutar</th>
                <th>Açıklama</th>
                <th>İşlem</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach($islem as $index => $row): ?>
              <tr>
                <td><?= $index + 1 ?></td>
                <td><?= date('d.m.Y', strtotime($row['tarih'])) ?></td>
                <td><span class="badge <?= $row['tip']=='gelir' ? 'bg-success' : 'bg-danger' ?>"><?= ucfirst($row['tip']) ?></span></td>
                <td>₺<?= number_format($row['tutar'],2) ?></td>
                <td><?= htmlspecialchars($row['aciklama'] ?: '-') ?></td>
                <td>
                  <!-- DÜZENLE BUTONU -->
                  <button type="button" class="btn btn-warning btn-sm" data-toggle="modal" data-target="#duzenleModal<?= $row['id'] ?>">
                    <i class="fas fa-edit"></i>
                  </button>
                  <!-- SİL BUTONU -->
                  <a href="?sil=<?= $row['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Bu kaydı silmek istediğinize emin misiniz?')">
                    <i class="fas fa-trash"></i>
                  </a>
                </td>
              </tr>

              <!-- DÜZENLE MODAL (HER SATIR İÇİN TEK MODAL) -->
              <div class="modal fade" id="duzenleModal<?= $row['id'] ?>">
                <div class="modal-dialog">
                  <div class="modal-content">
                    <form method="post">
                      <input type="hidden" name="id" value="<?= $row['id'] ?>">
                      <div class="modal-header bg-warning">
                        <h5 class="modal-title">Kayıt Düzenle</h5>
                        <button type="button" class="close" data-dismiss="modal">×</button>
                      </div>
                      <div class="modal-body">
                        <div class="form-group">
                          <label>Tip</label>
                          <select name="tip" class="form-control" required>
                            <option value="gelir" <?= $row['tip']=='gelir' ? 'selected' : '' ?>>Gelir</option>
                            <option value="gider" <?= $row['tip']=='gider' ? 'selected' : '' ?>>Gider</option>
                          </select>
                        </div>
                        <div class="form-group">
                          <label>Tutar</label>
                          <input name="tutar" type="number" step="0.01" class="form-control" value="<?= $row['tutar'] ?>" required>
                        </div>
                        <div class="form-group">
                          <label>Açıklama</label>
                          <input name="aciklama" class="form-control" value="<?= htmlspecialchars($row['aciklama'] ?? '') ?>">
                        </div>
                        <div class="form-group">
                          <label>Tarih</label>
                          <input name="tarih" type="date" class="form-control" value="<?= $row['tarih'] ?>" required>
                        </div>
                      </div>
                      <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">İptal</button>
                        <button type="submit" name="duzenle" class="btn btn-warning">Güncelle</button>
                      </div>
                    </form>
                  </div>
                </div>
              </div>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </section>
</div>

<!-- DataTables -->
<script src="https://cdn.datatables.net/1.13.7/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.13.7/js/dataTables.bootstrap4.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/dataTables.buttons.min.js"></script>
<script src="https://cdn.datatables.net/buttons/2.4.2/js/buttons.bootstrap4.min.js"></script>
<script>
$(function () {
    $('#gelirGiderTablosu').DataTable({
        responsive: true,
        language: { url: "//cdn.datatables.net/plug-ins/1.13.7/i18n/tr.json" },
        dom: 'Bfrtip',
        buttons: ['copy', 'csv', 'excel', { extend: 'pdf', orientation: 'landscape' }, 'print'],
        order: [[1, 'desc']]
    });
});
</script>

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