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

$basari = $hata = '';

// DÜZENLEME KAYDET
if (isset($_POST['site_duzenle'])) {
    $id = (int)$_POST['id'];
    $tenant_id = preg_replace('/[^a-z0-9]/', '', strtolower($_POST['tenant_id']));
    $sifre = $_POST['yonetici_sifre'] ?: null; // boş bırakılırsa değiştirme seçeneği

    try {
        if ($sifre === null) {
            $stmt = $pdo->prepare("UPDATE siteler SET
                tenant_id = ?,
                site_adi = ?,
                il = ?,
                ilce = ?,
                adres = ?,
                yonetici_adi = ?,
                yonetici_tel = ?,
                yonetici_email = ?
            WHERE id = ?");
            $stmt->execute([
                $tenant_id,
                $_POST['site_adi'],
                $_POST['il'],
                $_POST['ilce'],
                $_POST['adres'],
                $_POST['yonetici_adi'],
                $_POST['yonetici_tel'],
                $_POST['yonetici_email'],
                $id
            ]);
        } else {
            $stmt = $pdo->prepare("UPDATE siteler SET
                tenant_id = ?,
                site_adi = ?,
                il = ?,
                ilce = ?,
                adres = ?,
                yonetici_adi = ?,
                yonetici_tel = ?,
                yonetici_email = ?,
                yonetici_sifre = ?
            WHERE id = ?");
            $stmt->execute([
                $tenant_id,
                $_POST['site_adi'],
                $_POST['il'],
                $_POST['ilce'],
                $_POST['adres'],
                $_POST['yonetici_adi'],
                $_POST['yonetici_tel'],
                $_POST['yonetici_email'],
                $sifre,
                $id
            ]);
        }

        $basari = "Site güncellendi!";
        // Avoid resubmission
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    } catch (Exception $e) {
        $hata = "Hata: " . $e->getMessage();
    }
}

// YENİ SİTE EKLE
if (isset($_POST['site_ekle'])) {
    $tenant_id = preg_replace('/[^a-z0-9]/', '', strtolower($_POST['tenant_id']));
    $sifre = $_POST['yonetici_sifre'] ?: '123456'; // plain

    try {
        $stmt = $pdo->prepare("INSERT INTO siteler 
            (tenant_id, site_adi, il, ilce, adres, yonetici_adi, yonetici_tel, yonetici_email, yonetici_sifre, paket_bitis_tarihi) 
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, DATE_ADD(CURDATE(), INTERVAL 365 DAY))");
        $stmt->execute([
            $tenant_id, $_POST['site_adi'], $_POST['il'], $_POST['ilce'], $_POST['adres'],
            $_POST['yonetici_adi'], $_POST['yonetici_tel'], $_POST['yonetici_email'], $sifre
        ]);
        $basari = "Site eklendi!";
    } catch (Exception $e) {
        $hata = "Hata: " . $e->getMessage();
    }
}

// SİL
if (isset($_GET['sil']) && is_numeric($_GET['sil'])) {
    $pdo->prepare("DELETE FROM siteler WHERE id=?")->execute([(int)$_GET['sil']]);
    $basari = "Site silindi!";
}

// GÖZLEM
if (isset($_GET['gozlem']) && is_numeric($_GET['gozlem'])) {
    $stmt = $pdo->prepare("SELECT * FROM siteler WHERE id=?");
    $stmt->execute([(int)$_GET['gozlem']]);
    $site = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($site) {
        $_SESSION['yonetici'] = true;
        $_SESSION['site_id'] = $site['id'];
        $_SESSION['tenant_id'] = $site['tenant_id'];
        $_SESSION['site_adi'] = $site['site_adi'];
        $_SESSION['rol'] = 'yonetici';
        header('Location: ../site/dashboard.php');
        exit;
    }
}

// DUZENLEME VERİSİ (modal için)
$duzenleData = null;
if (isset($_GET['duzenle']) && is_numeric($_GET['duzenle'])) {
    $stmt = $pdo->prepare("SELECT * FROM siteler WHERE id=?");
    $stmt->execute([(int)$_GET['duzenle']]);
    $duzenleData = $stmt->fetch(PDO::FETCH_ASSOC);
}

$siteler = $pdo->query("SELECT *, DATEDIFF(paket_bitis_tarihi, CURDATE()) AS kalan_gun FROM siteler ORDER BY id DESC")->fetchAll();
?>
<?php include '../inc/header.php'; ?>
<?php include '../inc/sidebar.php'; ?>
<?php include '../inc/navbar.php'; ?>

<div class="content-wrapper">
  <section class="content-header">
    <div class="container-fluid">
      <div class="row mb-2">
        <div class="col-sm-6">
          <h1>Siteler (<?= count($siteler) ?>)</h1>
        </div>
        <div class="col-sm-6 text-right">
          <button class="btn btn-success btn-lg" data-toggle="modal" data-target="#siteEkle">
            <i class="fas fa-plus"></i> Yeni Site Ekle
          </button>
        </div>
      </div>
    </div>
  </section>

  <section class="content">
    <div class="container-fluid">
      <?php if($basari) echo '<div class="alert alert-success">'.$basari.'</div>'; ?>
      <?php if($hata) echo '<div class="alert alert-danger">'.$hata.'</div>'; ?>

      <div class="card">
        <div class="card-header bg-primary">
          <h3 class="card-title">Tüm Siteler</h3>
        </div>
        <div class="card-body table-responsive p-0">
          <table class="table table-striped table-bordered">
            <thead class="bg-primary text-white">
              <tr>
                <th>#</th>
                <th>Site Adı</th>
                <th>İl / İlçe</th>
                <th>Adres</th>
                <th>Yönetici Adı</th>
                <th>Telefon</th>
                <th>E-posta</th>
                <th>Kalan Gün</th>
                <th>Tenant ID</th>
                <th>Şifre</th>
                <th>İşlem</th>
              </tr>
            </thead>
            <tbody>
              <?php foreach($siteler as $i => $s): ?>
              <tr>
                <td><?= $i+1 ?></td>
                <td><strong><?= htmlspecialchars($s['site_adi']) ?></strong></td>
                <td><?= htmlspecialchars($s['il']) ?> / <?= htmlspecialchars($s['ilce']) ?></td>
                <td><?= htmlspecialchars($s['adres']) ?></td>
                <td><?= htmlspecialchars($s['yonetici_adi']) ?></td>
                <td><?= htmlspecialchars($s['yonetici_tel']) ?></td>
                <td><?= htmlspecialchars($s['yonetici_email']) ?></td>
                <td><span class="badge <?= $s['kalan_gun'] < 30 ? 'bg-danger' : 'bg-success' ?>"><?= $s['kalan_gun'] ?> gün</span></td>
                <td><code><?= $s['tenant_id'] ?></code></td>
                <td>******</td>
                <td>
                  <a href="?gozlem=<?= $s['id'] ?>" class="btn btn-info btn-sm"><i class="fas fa-eye"></i> Gözlem</a>

                  <!-- SADECE DÜZENLE BUTONU EKLENDİ -->
                  <a href="?duzenle=<?= $s['id'] ?>" class="btn btn-warning btn-sm"><i class="fas fa-edit"></i> Düzenle</a>

                  <a href="?sil=<?= $s['id'] ?>" class="btn btn-danger btn-sm" onclick="return confirm('Silinsin mi?')"><i class="fas fa-trash"></i></a>
                </td>
              </tr>
              <?php endforeach; ?>
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </section>
</div>

<!-- EKLE MODAL -->
<div class="modal fade" id="siteEkle">
  <div class="modal-dialog modal-lg">
    <form method="post">
      <div class="modal-content">
        <div class="modal-header bg-success">
          <h4 class="modal-title">Yeni Site Ekle</h4>
          <button type="button" class="close" data-dismiss="modal">×</button>
        </div>
        <div class="modal-body">
          <div class="row">
            <div class="col-md-6"><input name="tenant_id" class="form-control mb-2" placeholder="Tenant ID" required></div>
            <div class="col-md-6"><input name="site_adi" class="form-control mb-2" placeholder="Site Adı" required></div>
            <div class="col-md-4"><input name="il" class="form-control mb-2" placeholder="İl" required></div>
            <div class="col-md-4"><input name="ilce" class="form-control mb-2" placeholder="İlçe" required></div>
            <div class="col-md-4"><input name="adres" class="form-control mb-2" placeholder="Adres" required></div>
            <div class="col-md-4"><input name="yonetici_adi" class="form-control mb-2" placeholder="Yönetici Adı" required></div>
            <div class="col-md-4"><input name="yonetici_tel" class="form-control mb-2" placeholder="Telefon" required></div>
            <div class="col-md-4"><input name="yonetici_email" class="form-control mb-2" type="email" placeholder="E-posta" required></div>
            <div class="col-md-6"><input name="yonetici_sifre" type="password" class="form-control mb-2" placeholder="Şifre (boş bırak = 123456)"></div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" name="site_ekle" class="btn btn-success">EKLE</button>
        </div>
      </div>
    </form>
  </div>
</div>

<!-- DÜZENLE MODAL (only shown when ?duzenle=ID) -->
<?php if ($duzenleData): ?>
<div class="modal fade show" id="siteDuzenle" style="display:block; background:rgba(0,0,0,.5)">
  <div class="modal-dialog modal-lg">
    <form method="post">
      <input type="hidden" name="id" value="<?= htmlspecialchars($duzenleData['id']) ?>">
      <div class="modal-content">
        <div class="modal-header bg-warning">
          <h4 class="modal-title">Site Düzenle</h4>
          <a href="<?= $_SERVER['PHP_SELF'] ?>" class="close">×</a>
        </div>
        <div class="modal-body">
          <div class="row">
            <div class="col-md-6"><input name="tenant_id" class="form-control mb-2" value="<?= htmlspecialchars($duzenleData['tenant_id']) ?>" required></div>
            <div class="col-md-6"><input name="site_adi" class="form-control mb-2" value="<?= htmlspecialchars($duzenleData['site_adi']) ?>" required></div>
            <div class="col-md-4"><input name="il" class="form-control mb-2" value="<?= htmlspecialchars($duzenleData['il']) ?>" required></div>
            <div class="col-md-4"><input name="ilce" class="form-control mb-2" value="<?= htmlspecialchars($duzenleData['ilce']) ?>" required></div>
            <div class="col-md-4"><input name="adres" class="form-control mb-2" value="<?= htmlspecialchars($duzenleData['adres']) ?>" required></div>
            <div class="col-md-4"><input name="yonetici_adi" class="form-control mb-2" value="<?= htmlspecialchars($duzenleData['yonetici_adi']) ?>" required></div>
            <div class="col-md-4"><input name="yonetici_tel" class="form-control mb-2" value="<?= htmlspecialchars($duzenleData['yonetici_tel']) ?>" required></div>
            <div class="col-md-4"><input name="yonetici_email" class="form-control mb-2" type="email" value="<?= htmlspecialchars($duzenleData['yonetici_email']) ?>" required></div>
            <div class="col-md-6"><input name="yonetici_sifre" type="text" class="form-control mb-2" placeholder="Değiştirmek için yeni şifre girin"></div>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" name="site_duzenle" class="btn btn-warning">Kaydet</button>
        </div>
      </div>
    </form>
  </div>
</div>
<script>
  // provide a way for bootstrap/js to init if needed: keep modal visible until user closes via X link
  document.body.classList.add('modal-open');
</script>
<?php endif; ?>

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