<?php
// Session kontrolü - eğer session zaten başlatılmışsa tekrar başlatma
if (session_status() == PHP_SESSION_NONE) {
    session_start();
}

include '../inc/database.php';

$isLoggedIn = isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true;
if (!$isLoggedIn) { 
    header('Location: /'); 
    exit(); 
}

$username = $_SESSION['username'];

// Kullanıcı bilgileri
$email = '';
$firstName = '';
$surname = '';
$referansKodu = '';
$inviteCount = 0;
$totalEarnings = 0;
$activeReferrals = 0;

// Kullanıcı bilgilerini al
$stmt = $conn->prepare('SELECT id, email, first_name, surname, referans_kodu FROM kullanicilar WHERE username = ?');
if ($stmt) {
    $stmt->bind_param('s', $username);
    $stmt->execute();
    $stmt->bind_result($user_id, $email, $firstName, $surname, $referansKodu);
    $stmt->fetch();
    $stmt->close();
} else {
    $referansKodu = '';
}

if ($referansKodu) {
    // Toplam davet sayısı
    $cstmt = $conn->prepare('SELECT COUNT(*) FROM kullanicilar WHERE referred_by = ?');
    if ($cstmt) {
        $cstmt->bind_param('s', $referansKodu);
        $cstmt->execute();
        $cstmt->bind_result($inviteCount);
        $cstmt->fetch();
        $cstmt->close();
    }
    
    // Aktif referanslar (son 30 gün)
    $astmt = $conn->prepare('SELECT COUNT(*) FROM kullanicilar WHERE referred_by = ? AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)');
    if ($astmt) {
        $astmt->bind_param('s', $referansKodu);
        $astmt->execute();
        $astmt->bind_result($activeReferrals);
        $astmt->fetch();
        $astmt->close();
    }
}

$host = $_SERVER['HTTP_HOST'] ?? 'localhost';
$scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
$inviteLink = $referansKodu ? ($scheme . '://' . $host . '/click_id.php?affid=' . urlencode($referansKodu)) : '';

?>
<?php include '../inc/head.php'; ?>
<?php include '../inc/header.php'; ?>
<style>#menu-toggle{display:none !important}</style>

<style>
/* Genel arka plan siyah */
body {
    background-color: #000000 !important;
}

.centerWrap.porfileWrap {
    background-color: #000000 !important;
    padding-left: 0 !important;
    margin-top: 0 !important;
    padding-top: 0 !important;
    display: flex;
    align-items: flex-start;
}

.sidebarMain.playersidebarMain { margin-left: 0 !important; left: 0; }
.centerWrap.porfileWrap > .sidebarMain.playersidebarMain { width: 260px; flex: 0 0 260px; margin: 0 !important; }

.container-fluid {
    background-color: #000000 !important;
    flex: 1 1 auto;
    max-width: 100%;
    margin: 0;
    padding: 0 12px;
    overflow-x: hidden;
}

.profileRow {
    background-color: #000000 !important;
}

.referral-stats {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(160px, 1fr));
    gap: 10px;
    margin-bottom: 20px;
}

.stat-card {
    background: #1a1a1a;
    border-radius: 8px;
    padding: 14px;
    box-shadow: 0 3px 12px rgba(255,215,0,0.3);
    border: 2px solid #FFD700;
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.stat-card::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
    transform: scaleX(0);
    transition: transform 0.3s ease;
}

.stat-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 25px rgba(255,215,0,0.5);
    border-color: #FFA500;
}

.stat-card:hover::before {
    transform: scaleX(1);
}

.stat-card .icon {
    width: 36px;
    height: 36px;
    border-radius: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 10px;
    font-size: 18px;
    position: relative;
}

.stat-card.users .icon {
    background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
    color: #000;
}

.stat-card.earnings .icon {
    background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
    color: #000;
}

.stat-card.active .icon {
    background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
    color: #000;
}

.stat-card.code .icon {
    background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
    color: #000;
}

.stat-card h3 {
    font-size: 18px;
    font-weight: 700;
    margin: 0 0 4px 0;
    color: #FFD700;
}

.stat-card p {
    margin: 0;
    color: #FFFFFF;
    font-size: 12px;
    font-weight: 500;
}

.referral-card {
    background: #1a1a1a;
    border-radius: 10px;
    padding: 18px;
    box-shadow: 0 3px 12px rgba(255,215,0,0.3);
    border: 2px solid #FFD700;
    margin-bottom: 20px;
}

.referral-card h5 {
    color: #FFD700;
    font-weight: 600;
    margin-bottom: 18px;
    display: flex;
    align-items: center;
    gap: 10px;
    font-size: 18px;
}

.referral-card h5 i {
    color: #FFD700;
    font-size: 24px;
}

.form-group {
    margin-bottom: 16px;
}

.form-group label {
    font-weight: 600;
    color: #FFFFFF;
    margin-bottom: 10px;
    display: block;
    font-size: 14px;
}

.form-control {
    border: 2px solid #FFD700;
    border-radius: 10px;
    padding: 12px 14px;
    font-size: 14px;
    transition: all 0.3s ease;
    background: #2a2a2a;
    color: #FFFFFF;
}

.form-control:focus {
    border-color: #FFA500;
    box-shadow: 0 0 0 0.2rem rgba(255, 215, 0, 0.25);
    background: #2a2a2a;
    color: #FFFFFF;
}

.btn-group {
    display: flex;
    gap: 10px;
    flex-wrap: wrap;
}

.btn {
    padding: 10px 18px;
    border-radius: 10px;
    font-weight: 600;
    text-decoration: none;
    transition: all 0.3s ease;
    border: none;
    cursor: pointer;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
}

.btn-primary {
    background: linear-gradient(135deg, #FFD700 0%, #FFA500 100%);
    color: #000000;
    border: 2px solid #FFD700;
}

.btn-primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(255, 215, 0, 0.4);
    color: #000000;
    background: linear-gradient(135deg, #FFA500 0%, #FFD700 100%);
}

.btn-outline {
    background: transparent;
    border: 2px solid #FFD700;
    color: #FFD700;
}

.btn-outline:hover {
    background: #FFD700;
    color: #000000;
    transform: translateY(-2px);
}

.info-box {
    background: linear-gradient(135deg, #1a1a1a 0%, #2a2a2a 100%);
    border-radius: 12px;
    padding: 30px;
    margin-top: 30px;
    border: 3px solid #FFD700;
    position: relative;
}

.info-box::before {
    content: '';
    position: absolute;
    top: 20px;
    right: 20px;
    width: 100px;
    height: 100px;
    background: rgba(255, 215, 0, 0.1);
    border-radius: 50%;
    z-index: 1;
}

.info-box h6 {
    color: #FFD700;
    font-weight: 600;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 18px;
    position: relative;
    z-index: 2;
}

.info-box ul {
    margin: 0;
    padding-left: 25px;
    position: relative;
    z-index: 2;
}

.info-box li {
    margin-bottom: 12px;
    color: #FFFFFF;
    font-size: 15px;
    line-height: 1.6;
}

.info-box li strong {
    color: #FFD700;
}

.alert {
    border-radius: 12px;
    padding: 25px;
    border: 3px solid #FFD700;
    margin-bottom: 30px;
    display: flex;
    align-items: center;
    gap: 15px;
}

.alert-warning {
    background: linear-gradient(135deg, #2a2a2a 0%, #1a1a1a 100%);
    color: #FFFFFF;
}

.alert-warning strong {
    color: #FFD700;
}

.referral-link-display {
    background: #2a2a2a;
    border: 2px dashed #FFD700;
    border-radius: 10px;
    padding: 12px;
    text-align: center;
    margin: 12px 0;
}

.referral-code-big {
    font-size: 18px;
    font-weight: 700;
    color: #FFD700;
    font-family: 'Courier New', monospace;
    letter-spacing: 2px;
}

.text-muted {
    color: #CCCCCC !important;
}

.breadcrumb { margin: 0 !important; padding: 10px 0 !important; }
.profileRow { margin-top: 0 !important; }

/* Breadcrumb için */
.breadcrumb {
    background-color: transparent !important;
}

.breadcrumb-item a {
    color: #FFD700 !important;
}

.breadcrumb-item {
    color: #FFFFFF !important;
}

@media (max-width: 768px) {
    .referral-stats {
        grid-template-columns: 1fr;
    }
    
    .btn-group {
        flex-direction: column;
    }
    
    .btn {
        justify-content: center;
    }
    
    .referral-card {
        padding: 20px;
    }
    
    .stat-card {
        padding: 20px;
    }
    
    .stat-card h3 {
        font-size: 28px;
    }
}
@media (max-width: 768px) { #menu-toggle { display: none !important; } }
.centerWrap.porfileWrap{padding-top:64px !important}
@media (max-width: 768px){ .centerWrap.porfileWrap{padding-top:25px !important} }
#menu-toggle{display:none !important}
.mobile-menu-toggle{display:none !important}
</style>

<div class="centerWrap porfileWrap">
  <?php include 'sidebar.php'; ?>
  <div class="container-fluid">
    <ul class="breadcrumb">
      <li class="breadcrumb-item"><a href="/">Ana Sayfa</a></li>
      <li class="breadcrumb-item" aria-current="page">Referans Programı</li>
    </ul>
    <div class="row">
      <div class="col-lg-9 col-xl-7">
        <div class="profileRow" style="margin-top:0 !important;">
          
          <?php if ($referansKodu): ?>
          <!-- İstatistik Kartları -->
          <div class="referral-stats">
            <div class="stat-card users">
              <div class="icon">
                <i class="fas fa-users"></i>
              </div>
              <h3><?php echo (int)$inviteCount; ?></h3>
              <p>Toplam Davet</p>
            </div>
            <div class="stat-card active">
              <div class="icon">
                <i class="fas fa-user-plus"></i>
              </div>
              <h3><?php echo (int)$activeReferrals; ?></h3>
              <p>Son 30 Gün</p>
            </div>
            <div class="stat-card earnings">
              <div class="icon">
                <i class="fas fa-coins"></i>
              </div>
              <h3><?php echo number_format($totalEarnings, 2); ?> ₺</h3>
              <p>Toplam Kazanç</p>
            </div>
            <div class="stat-card code">
              <div class="icon">
                <i class="fas fa-qrcode"></i>
              </div>
              <h3><?php echo htmlspecialchars($referansKodu); ?></h3>
              <p>Referans Kodun</p>
            </div>
          </div>

          <!-- Referans Kodu Kartı -->
          <div class="referral-card">
            <h5><i class="fas fa-share-alt"></i> Referans Kodun ve Davet Linkin</h5>
            
            <div class="referral-link-display">
              <div class="referral-code-big"><?php echo htmlspecialchars($referansKodu); ?></div>
              <small class="text-muted">Referans Kodun</small>
            </div>
            
            <div class="form-group">
              <label class="col-form-label">Referans Kodu</label>
              <input class="form-control" type="text" value="<?php echo htmlspecialchars($referansKodu); ?>" readonly id="refCode">
            </div>
            
            <div class="form-group">
              <label class="col-form-label">Davet Linki</label>
              <input class="form-control" type="text" value="<?php echo htmlspecialchars($inviteLink); ?>" readonly id="inviteLink">
            </div>
            
            <div class="btn-group">
              <button class="btn btn-primary" type="button" onclick="copyVal('inviteLink')">
                <i class="fas fa-copy"></i> Linki Kopyala
              </button>
              <button class="btn btn-outline" type="button" onclick="shareLink()">
                <i class="fas fa-share"></i> Paylaş
              </button>
              <button class="btn btn-outline" type="button" onclick="copyVal('refCode')">
                <i class="fas fa-tag"></i> Kodu Kopyala
              </button>
            </div>
          </div>

          <!-- Bilgi Kutusu -->
          <div class="info-box">
            <h6><i class="fas fa-info-circle"></i> Referans Programı Nasıl Çalışır?</h6>
            <ul>
              <li><strong>Arkadaşlarını Davet Et:</strong> Referans kodunu veya linki paylaşarak arkadaşlarını siteye davet et</li>
              <li><strong>Kayıt Bonusu:</strong> Davet ettiğin her kişi için kayıt bonusu kazan</li>
              <li><strong>Para Yatırma Bonusu:</strong> Davet ettiğin kişiler ilk para yatırma işleminde sen de bonus kazanırsın</li>
              <li><strong>Sürekli Kazanç:</strong> Davet ettiğin kişilerin oyun aktivitelerinden sürekli komisyon al</li>
              <li><strong>Sınırsız Davet:</strong> İstediğin kadar kişiyi davet edebilir, kazancını artırabilirsin</li>
              <li><strong>Anında Ödeme:</strong> Kazançların otomatik olarak hesabına yansıtılır</li>
            </ul>
          </div>

          <?php else: ?>
          <div class="alert alert-warning">
            <i class="fas fa-exclamation-triangle"></i>
            <div>
              <strong>Referans Kodu Bulunamadı!</strong><br>
              Referans kodun henüz oluşturulmamış. Lütfen destek ekibiyle iletişime geç.
            </div>
          </div>
          <?php endif; ?>
          
        </div>
      </div>
    </div>
  </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
function copyVal(id){
  var el = document.getElementById(id); 
  if (!el) return;
  var val = el.value || '';
  if (!val) return;
  
  if (navigator.clipboard) { 
    navigator.clipboard.writeText(val).then(() => {
      Swal.fire({
        icon: 'success',
        title: 'Başarılı!',
        text: 'Metin başarıyla kopyalandı',
        timer: 2000,
        showConfirmButton: false,
        toast: true,
        position: 'top-end'
      });
    });
  } else {
    el.select(); 
    document.execCommand('copy'); 
    Swal.fire({
      icon: 'success',
      title: 'Başarılı!',
      text: 'Metin başarıyla kopyalandı',
      timer: 2000,
      showConfirmButton: false,
      toast: true,
      position: 'top-end'
    });
  }
}

function shareLink(){
  var link = document.getElementById('inviteLink').value;
  if (navigator.share) { 
    navigator.share({
      title: 'BlackBet Davet Linkim',
      text: 'Sana özel davet linki ile BlackBet\'e katıl!',
      url: link
    });
  } else { 
    copyVal('inviteLink'); 
  }
}

// Sayfa yüklendiğinde animasyonlar
document.addEventListener('DOMContentLoaded', function() {
  const cards = document.querySelectorAll('.stat-card');
  cards.forEach((card, index) => {
    card.style.opacity = '0';
    card.style.transform = 'translateY(30px)';
    
    setTimeout(() => {
      card.style.transition = 'all 0.6s ease';
      card.style.opacity = '1';
      card.style.transform = 'translateY(0)';
    }, index * 150);
  });
  
  // Referral card animasyonu
  setTimeout(() => {
    const referralCard = document.querySelector('.referral-card');
    if (referralCard) {
      referralCard.style.opacity = '0';
      referralCard.style.transform = 'translateY(20px)';
      referralCard.style.transition = 'all 0.6s ease';
      
      setTimeout(() => {
        referralCard.style.opacity = '1';
        referralCard.style.transform = 'translateY(0)';
      }, 100);
    }
  }, 600);
});
</script>
<script>document.addEventListener('DOMContentLoaded',function(){var mt=document.getElementById('menu-toggle');if(mt){mt.style.display='none';}});</script>

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