<?php
// Affiliate Dashboard
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (empty($_SESSION['affiliate_loggedin'])) { header('Location: /affiliate/login.php'); exit; }

$affiliateUserId = (int)($_SESSION['affiliate_user_id'] ?? 0);
$affiliateUsername = $_SESSION['affiliate_username'] ?? '';
$affiliateRefCode = $_SESSION['affiliate_ref_code'] ?? '';

// DB bağlan
require_once __DIR__ . '/../woohdd/dblive.php';
try {
    $pdo = new PDO("mysql:host=$user_db_servername;dbname=$user_db_name;charset=utf8", $user_db_username, $user_db_password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (Throwable $e) {
    http_response_code(500);
    echo 'Veritabanı hatası: ' . htmlspecialchars($e->getMessage());
    exit;
}

// Kullanıcıyı doğrula ve güncel bilgileri al (tüm sütunlar; commission_rate var/yok güvenli)
$stmt = $pdo->prepare('SELECT * FROM kullanici2 WHERE id = ? LIMIT 1');
$stmt->execute([$affiliateUserId]);
$aff = $stmt->fetch(PDO::FETCH_ASSOC);
if (!$aff) {
    // oturumu temizle
    $_SESSION = [];
    session_destroy();
    header('Location: /affiliate/login.php');
    exit;
}

$affiliateRefCode = $aff['referans_kodu'] ?: $affiliateRefCode;

// Metrixler
$clicks = 0; $regs_total = 0; $regs_30d = 0;
// Komisyon oranı: kullanici2.commission_rate (0-1 arası) yoksa %10 varsayılan
$commissionRate = 0.10; // default %10
if (isset($aff['commission_rate']) && is_numeric($aff['commission_rate'])) {
    $cr = (float)$aff['commission_rate'];
    if ($cr > 0 && $cr <= 1) { $commissionRate = $cr; }
}
// Clicks
$q1 = $pdo->prepare('SELECT COUNT(*) FROM clicks WHERE referans_kodu = ?');
$q1->execute([$affiliateRefCode]);
$clicks = (int)$q1->fetchColumn();

// Kayıtlar (toplam)
$q2 = $pdo->prepare('SELECT COUNT(*) FROM kullanicilar WHERE referred_by = ?');
$q2->execute([$affiliateRefCode]);
$regs_total = (int)$q2->fetchColumn();

// Kayıtlar (son 30 gün)
$q3 = $pdo->prepare("SELECT COUNT(*) FROM kullanicilar WHERE referred_by = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)");
$q3->execute([$affiliateRefCode]);
$regs_30d = (int)$q3->fetchColumn();

// Son 10 referans
$recent = [];
$q4 = $pdo->prepare('SELECT username, email, created_at FROM kullanicilar WHERE referred_by = ? ORDER BY created_at DESC LIMIT 10');
$q4->execute([$affiliateRefCode]);
$recent = $q4->fetchAll(PDO::FETCH_ASSOC);

// Mevduat ve komisyon metrikleri
$deposit_sum_all = 0.0; $deposit_sum_30d = 0.0; $depositors_all = 0; $depositors_30d = 0;

// Toplam onaylı yatırım
$dq1 = $pdo->prepare("SELECT COALESCE(SUM(p.miktar),0) FROM kullanicilar u LEFT JOIN parayatir p ON p.user_id = u.id AND p.durum = '1' WHERE u.referred_by = ?");
$dq1->execute([$affiliateRefCode]);
$deposit_sum_all = (float)$dq1->fetchColumn();

// Son 30 gün onaylı yatırım
$dq2 = $pdo->prepare("SELECT COALESCE(SUM(p.miktar),0) FROM kullanicilar u LEFT JOIN parayatir p ON p.user_id = u.id AND p.durum = '1' AND p.tarih >= DATE_SUB(NOW(), INTERVAL 30 DAY) WHERE u.referred_by = ?");
$dq2->execute([$affiliateRefCode]);
$deposit_sum_30d = (float)$dq2->fetchColumn();

// Toplam benzersiz yatırımcı sayısı
$dq3 = $pdo->prepare("SELECT COUNT(DISTINCT p.user_id) FROM kullanicilar u LEFT JOIN parayatir p ON p.user_id = u.id AND p.durum = '1' WHERE u.referred_by = ?");
$dq3->execute([$affiliateRefCode]);
$depositors_all = (int)$dq3->fetchColumn();

// Son 30 gün benzersiz yatırımcı sayısı
$dq4 = $pdo->prepare("SELECT COUNT(DISTINCT p.user_id) FROM kullanicilar u LEFT JOIN parayatir p ON p.user_id = u.id AND p.durum = '1' AND p.tarih >= DATE_SUB(NOW(), INTERVAL 30 DAY) WHERE u.referred_by = ?");
$dq4->execute([$affiliateRefCode]);
$depositors_30d = (int)$dq4->fetchColumn();

$commission_total = $deposit_sum_all * $commissionRate;
$commission_30d = $deposit_sum_30d * $commissionRate;

$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$inviteLink = $affiliateRefCode ? ($scheme . '://' . $host . '/click_id.php?affid=' . urlencode($affiliateRefCode)) : '';
?>
<!DOCTYPE html>
<html lang="tr">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Affiliate Panel</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    body { background:#0b0b0b; color:#fff; }
    .card { background:#1a1a1a; border:1px solid #333; }
    .metric { border-left: 4px solid #FFD700; }
    .badge-gold { background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%); color:#000; }
    .btn-primary { background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%); color:#000; border:none; }
    .form-control { background:#2a2a2a; color:#fff; border-color:#444; }
    .form-control:focus { background:#2a2a2a; color:#fff; border-color:#FFD700; box-shadow: 0 0 0 .2rem rgba(255,215,0,.25); }
  </style>
  <meta name="robots" content="noindex,nofollow">
</head>
<body>
  <nav class="navbar navbar-dark" style="background:#111; border-bottom:1px solid #333;">
    <div class="container-fluid">
      <span class="navbar-brand">Affiliate Panel</span>
      <div>
        <span class="me-3 text-warning"><?php echo htmlspecialchars($aff['kullanici_adi']); ?></span>
        <a class="btn btn-sm btn-outline-warning" href="/affiliate/logout.php">Çıkış</a>
      </div>
    </div>
  </nav>

  <div class="container py-4">
    <div class="row g-3 mb-3">
      <div class="col-md-4">
        <div class="card p-3 metric">
          <div class="d-flex justify-content-between align-items-center">
            <div>
              <div class="text-muted">Tıklama</div>
              <div class="fs-3 fw-bold"><?php echo (int)$clicks; ?></div>
            </div>
            <span class="badge badge-gold">Link Trafiği</span>
          </div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="card p-3 metric">
          <div class="d-flex justify-content-between align-items-center">
            <div>
              <div class="text-muted">Kayıt (Toplam)</div>
              <div class="fs-3 fw-bold"><?php echo (int)$regs_total; ?></div>
            </div>
            <span class="badge badge-gold">Üyeler</span>
          </div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="card p-3 metric">
          <div class="d-flex justify-content-between align-items-center">
            <div>
              <div class="text-muted">Kayıt (Son 30 Gün)</div>
              <div class="fs-3 fw-bold"><?php echo (int)$regs_30d; ?></div>
            </div>
            <span class="badge badge-gold">Trend</span>
          </div>
        </div>
      </div>
    </div>

    <div class="row g-3 mb-3">
      <div class="col-md-4">
        <div class="card p-3 metric">
          <div class="d-flex justify-content-between align-items-center">
            <div>
              <div class="text-muted">Toplam Yatırım</div>
              <div class="fs-3 fw-bold"><?php echo number_format($deposit_sum_all, 2); ?> ₺</div>
              <small class="text-muted">Yatırımcı: <?php echo (int)$depositors_all; ?></small>
            </div>
            <span class="badge badge-gold">Onaylı</span>
          </div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="card p-3 metric">
          <div class="d-flex justify-content-between align-items-center">
            <div>
              <div class="text-muted">Son 30 Gün Yatırım</div>
              <div class="fs-3 fw-bold"><?php echo number_format($deposit_sum_30d, 2); ?> ₺</div>
              <small class="text-muted">Yatırımcı: <?php echo (int)$depositors_30d; ?></small>
            </div>
            <span class="badge badge-gold">Onaylı</span>
          </div>
        </div>
      </div>
      <div class="col-md-4">
        <div class="card p-3 metric">
          <div class="d-flex justify-content-between align-items-center">
            <div>
              <div class="text-muted">Tahmini Komisyon (Toplam)</div>
              <div class="fs-3 fw-bold"><?php echo number_format($commission_total, 2); ?> ₺</div>
              <small class="text-muted">Oran: %<?php echo (int)round($commissionRate*100); ?></small>
            </div>
            <span class="badge badge-gold">Öngörü</span>
          </div>
        </div>
      </div>
    </div>

    <div class="card p-3 mb-3">
      <h5 class="mb-3">Referans Kodun ve Linkin</h5>
      <div class="row g-2">
        <div class="col-md-4">
          <label class="form-label">Referans Kodun</label>
          <input class="form-control" type="text" value="<?php echo htmlspecialchars($affiliateRefCode); ?>" readonly>
        </div>
        <div class="col-md-8">
          <label class="form-label">Davet Linkin</label>
          <div class="input-group">
            <input id="inviteLink" class="form-control" type="text" value="<?php echo htmlspecialchars($inviteLink); ?>" readonly>
            <button class="btn btn-primary" onclick="copyLink()">Kopyala</button>
          </div>
        </div>
      </div>
    </div>

    <div class="card p-3">
      <h5 class="mb-3">Son Kayıtlar</h5>
      <div class="table-responsive">
        <table class="table table-dark table-sm align-middle">
          <thead>
            <tr><th>Kullanıcı Adı</th><th>E‑posta</th><th>Kayıt Tarihi</th></tr>
          </thead>
          <tbody>
          <?php if (!empty($recent)): foreach ($recent as $r): ?>
            <tr>
              <td><?php echo htmlspecialchars($r['username']); ?></td>
              <td><?php echo htmlspecialchars($r['email']); ?></td>
              <td><?php echo htmlspecialchars($r['created_at']); ?></td>
            </tr>
          <?php endforeach; else: ?>
            <tr><td colspan="3" class="text-center text-muted">Kayıt bulunamadı.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>

    <?php
    // Son yatırımlar (onaylı) — ilk 10
    $recentDeps = [];
    $dq5 = $pdo->prepare("SELECT u.username, p.miktar, p.tarih FROM parayatir p JOIN kullanicilar u ON p.user_id = u.id WHERE u.referred_by = ? AND p.durum = '1' ORDER BY p.tarih DESC LIMIT 10");
    $dq5->execute([$affiliateRefCode]);
    $recentDeps = $dq5->fetchAll(PDO::FETCH_ASSOC);
    ?>

    <div class="card p-3 mt-3">
      <h5 class="mb-3">Son Yatırımlar</h5>
      <div class="table-responsive">
        <table class="table table-dark table-sm align-middle">
          <thead>
            <tr><th>Kullanıcı Adı</th><th>Tutar</th><th>Tarih</th></tr>
          </thead>
          <tbody>
          <?php if (!empty($recentDeps)): foreach ($recentDeps as $d): ?>
            <tr>
              <td><?php echo htmlspecialchars($d['username']); ?></td>
              <td><?php echo number_format((float)$d['miktar'], 2); ?> ₺</td>
              <td><?php echo htmlspecialchars($d['tarih']); ?></td>
            </tr>
          <?php endforeach; else: ?>
            <tr><td colspan="3" class="text-center text-muted">Yatırım bulunamadı.</td></tr>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>

  <script>
    function copyLink(){
      var el = document.getElementById('inviteLink');
      el.select();
      document.execCommand('copy');
    }
  </script>
</body>
</html>