<?php
require_once '../config/database.php';
session_start();
if (!isset($_SESSION['yonetici'])) header('Location: login.php');
$site_id = (int)$_SESSION['site_id'];
$basari = $hata = '';

// EKLE
if (isset($_POST['kaydet'])) {
    $stmt = $pdo->prepare("INSERT INTO guvenlik_kayitlari (site_id, tur, ad_soyad, plaka, daire_no, aciklama) VALUES (?, ?, ?, ?, ?, ?)");
    $stmt->execute([$site_id, $_POST['tur'], $_POST['ad_soyad'], $_POST['plaka'], $_POST['daire_no'], $_POST['aciklama']]);
    $basari = "Kayıt eklendi!";
}

// TESLİM ET
if (isset($_GET['teslim']) && is_numeric($_GET['teslim'])) {
    $pdo->prepare("UPDATE guvenlik_kayitlari SET teslim_edildi=1 WHERE id=? AND site_id=?")->execute([(int)$_GET['teslim'], $site_id]);
    $basari = "Teslim edildi!";
}

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

// LİSTE (Aylık gruplama ile)
try {
    $stmt = $pdo->prepare("SELECT * FROM guvenlik_kayitlari WHERE site_id = ? ORDER BY tarih DESC");
    $stmt->execute([$site_id]);
    $tum_kayitlar = $stmt->fetchAll(PDO::FETCH_ASSOC);

    // Aylık gruplama
    $kayitlar_aylik = [];
    foreach ($tum_kayitlar as $k) {
        $ay = date('Y-m', strtotime($k['tarih']));
        $kayitlar_aylik[$ay][] = $k;
    }
} catch (Exception $e) {
    $kayitlar_aylik = [];
    $hata = "Kayıtlar yüklenemedi: " . $e->getMessage();
}

// Türkçe ay isimleri
$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 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>Güvenlik Takip</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İ KAYIT -->
    <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">
          <div class="row">
            <div class="col-md-3">
              <select name="tur" class="form-control mb-2" required>
                <option value="giris">Giriş</option>
                <option value="cikis">Çıkış</option>
                <option value="misafir">Misafir</option>
                <option value="kargo">Kargo</option>
                <option value="vukaat">Vukuat</option>
                <option value="not">Not</option>
              </select>
            </div>
            <div class="col-md-3"><input name="ad_soyad" class="form-control mb-2" placeholder="Ad Soyad"></div>
            <div class="col-md-2"><input name="plaka" class="form-control mb-2" placeholder="Plaka"></div>
            <div class="col-md-2"><input name="daire_no" class="form-control mb-2" placeholder="Daire No"></div>
            <div class="col-md-2"><textarea name="aciklama" class="form-control mb-2" rows="1" placeholder="Açıklama"></textarea></div>
            <div class="col-md-12 text-right mt-2">
              <button name="kaydet" class="btn btn-primary btn-lg">Ekle</button>
            </div>
          </div>
        </form>
      </div>
    </div>

    <!-- AYLIK LİSTE -->
    <?php if (empty($kayitlar_aylik)): ?>
      <div class="alert alert-info">Henüz güvenlik kaydı bulunmamaktadır.</div>
    <?php else: ?>
      <?php foreach ($kayitlar_aylik as $ay => $kayitlar): ?>
        <?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 ?> Kayıtları</h3>
          </div>
          <div class="card-body table-responsive p-0">
            <table class="table table-hover">
              <thead>
                <tr>
                  <th>Tür</th>
                  <th>Ad Soyad</th>
                  <th>Plaka - Daire</th>
                  <th>Açıklama</th>
                  <th>Tarih</th>
                  <th>İşlem</th>
                </tr>
              </thead>
              <tbody>
                <?php foreach($kayitlar as $k): ?>
                <tr>
                  <td><span class="badge bg-info"><?= ucfirst($k['tur']) ?></span></td>
                  <td><?= htmlspecialchars($k['ad_soyad'] ?: '-') ?></td>
                  <td><?= htmlspecialchars($k['plaka'] ?: '-') ?> - <?= htmlspecialchars($k['daire_no'] ?: '-') ?></td>
                  <td><?= htmlspecialchars($k['aciklama'] ?: '-') ?></td>
                  <td><?= date('d.m.Y H:i', strtotime($k['tarih'])) ?></td>
                  <td>
                    <?php if($k['tur']=='kargo' && !$k['teslim_edildi']): ?>
                      <a href="?teslim=<?= $k['id'] ?>" class="btn btn-success btn-sm mr-1">Teslim Et</a>
                    <?php endif; ?>
                    <a href="?sil=<?= $k['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Bu kaydı 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'; ?>