<?php
session_start();

// Veritabanı bağlantısını yapın
include '../inc/database.php';

// Kullanıcının oturum açıp açmadığını kontrol edin
$isLoggedIn = isset($_SESSION['loggedin']) && $_SESSION['loggedin'] === true;
$username = $isLoggedIn ? $_SESSION['username'] : '';

// Kullanıcı giriş yapmamışsa yönlendirme yap
if (!$isLoggedIn) {
    header('Location: /');
    exit();
}

// Kullanıcı bilgilerini al
$sql = "SELECT id, email, first_name, surname FROM kullanicilar WHERE username = ?";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $username);
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();
$user_id = $user['id'];
$stmt->close();

// Tablo oluşturma ve AJAX işlemleri
$conn->query("CREATE TABLE IF NOT EXISTS user_limits (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  type VARCHAR(16) NOT NULL,
  amount INT NOT NULL,
  status VARCHAR(16) NOT NULL DEFAULT 'active',
  used INT NOT NULL DEFAULT 0,
  created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
  UNIQUE KEY uniq_user_type (user_id, type)
)");

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    header('Content-Type: application/json');
    $action = $_POST['action'];
    if ($action === 'update_limit') {
        $type = $_POST['type'] ?? '';
        $amount = isset($_POST['amount']) ? (int)$_POST['amount'] : 0;
        if (!$type || $amount <= 0) {
            echo json_encode(['status' => 'error', 'message' => 'Geçersiz veri']);
            exit;
        }
        $stmt = $conn->prepare("INSERT INTO user_limits (user_id, type, amount, status, used) VALUES (?,?,?,?,0) ON DUPLICATE KEY UPDATE amount=VALUES(amount), status='active', used=0");
        $status = 'active';
        $stmt->bind_param('isss', $user_id, $type, $amount, $status);
        $ok = $stmt->execute();
        $stmt->close();
        echo json_encode(['status' => $ok ? 'success' : 'error']);
        exit;
    }
    if ($action === 'remove_limit') {
        $type = $_POST['type'] ?? '';
        if (!$type) {
            echo json_encode(['status' => 'error', 'message' => 'Geçersiz veri']);
            exit;
        }
        $stmt = $conn->prepare("DELETE FROM user_limits WHERE user_id=? AND type=?");
        $stmt->bind_param('is', $user_id, $type);
        $ok = $stmt->execute();
        $stmt->close();
        echo json_encode(['status' => $ok ? 'success' : 'error']);
        exit;
    }
}

// Kullanıcının baş harfini al
$initial = strtoupper(substr($username, 0, 1));
?>

<?php include '../inc/head.php'; ?>
<?php include '../inc/header.php'; ?>

<div class="centerWrap porfileWrap">
<style>
.mt-theme{display:flex;align-items:center;gap:10px;padding:8px 0}
.mt-theme .breadcrumb{display:flex;flex-wrap:wrap;gap:6px;background:transparent !important;margin:0 !important;padding:0 !important}
.breadcrumb-item, .breadcrumb-item a{color:#fff !important;text-decoration:none}
.breadcrumb-item + .breadcrumb-item::before{color:rgba(255,255,255,.6) !important}
.backBtn{margin-right:8px;border:1px solid rgba(255,255,255,.2);border-radius:8px;padding:8px 12px;color:#fff;background:transparent}
 .centerWrap.porfileWrap{padding-top:64px !important}
 body{background:#000 !important;color:#fff}
 .centerWrap{background:#000 !important}
 .container-fluid{background:#000 !important}
 .profileRow{background:#000 !important;border:1px solid rgba(255,255,255,.08);border-radius:10px;color:#fff}
 .secTitle h5{color:var(--primary)}
 .card{background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.12);border-radius:12px;color:#e6e9ef}
 .card .card-header{background:var(--primary);color:var(--btntText);border-bottom:none}
 .nav-tabs .nav-link{background:transparent;border:1px solid rgba(255,255,255,.12);color:#e6e9ef;border-radius:10px;margin-right:8px;padding:6px 12px}
 .nav-tabs .nav-link.active{background:var(--primary);border-color:var(--primary);color:var(--btntText)}
 .table{background:#000;color:#fff}
 .table thead th{background:var(--primary);color:var(--btntText)}
 .badge{border:1px solid rgba(255,255,255,.12);border-radius:12px;font-weight:600}
 .badge-success{background:var(--primary);color:var(--btntText)}
 .badge-warning{background:rgba(229,182,69,.15);color:var(--primary)}
 .badge-danger{background:rgba(239,68,68,.15);color:#ef4444}
@media (max-width: 768px){
  .mt-theme{flex-wrap:wrap}
  .backBtn{width:36px;height:36px;padding:0;display:inline-flex;align-items:center;justify-content:center}
  .breadcrumb{font-size:14px}
  .centerWrap.porfileWrap{padding-top:56px !important}
}
</style>
    <aside class="sidebarMain playersidebarMain">
        <div class="profile-content">
            <div class="edit-user">
                <span class="avatar-holder ng-tns-c27-2 ng-star-inserted"><?php echo $initial; ?></span>
                <div class="user-right">
                    <span class="username ng-tns-c27-2 ng-star-inserted"><?php echo htmlspecialchars($username); ?></span>
                </div>
            </div>
            
            <script>
                document.addEventListener('DOMContentLoaded', function() {
                    const isLoggedIn = <?php echo json_encode($isLoggedIn); ?>;

                    if (isLoggedIn) {
                        fetch('../api/balanceapi')
                            .then(response => response.json())
                            .then(data => {
                                const balanceText = document.querySelector('.amount');

                                if (data.status === 'success') {
                                    balanceText.textContent = data.ana_bakiye + ' ₺';
                                } else {
                                    console.error(data.message);
                                }
                            })
                            .catch(error => {
                                console.error('Hata:', error);
                            });
                    }
                });
            </script>

            <div class="main-balance">
                <div class="total-balance">
                    <div class="user-balance">
                        <span class="balance-title">Ana Bakiye</span>
                        <span class="amount ng-tns-c27-2 ng-star-inserted">0 ₺</span>
                    </div>
                    <i class="fa-solid fa-eye eye-icon ng-tns-c27-2 ng-star-inserted"></i>
                </div>
                
                <div class="buttons-bottom">
                    <a class="btn deposit-bc" href="/profile/deposit-withdraw">
                        <i class="fa-solid fa-wallet"></i> Para Yatır
                    </a>
                    <a class="btn withdraw-bc" href="/profile/deposit-withdraw">
                        <img class="ng-tns-c27-2" alt="" src="/assets/images/withdraw-icon.png"> Para Çekme
                    </a>
                </div>
            </div>
            
            <div class="main-balance bonus">
                <div class="user-balance">
                    <span class="balance-title">Bonus Bakiyesi</span>
                    <span class="amount ng-tns-c27-2 ng-star-inserted">0 ₺</span>
                </div>
            </div>
        </div>
        
        <div class="sideSports">
            <ul class="ng-tns-c27-2">
                <li style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted">
                    <a class="ng-tns-c27-2" style="cursor: pointer" type="GROUP" href="/profile/account-details">Profilim</a>
                </li>
                <li style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted">
                    <a class="ng-tns-c27-2" style="cursor: pointer" type="GROUP" href="/profile/account-statement">İşlem Geçmişi</a>
                </li>
                <li style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted">
                    <a class="ng-tns-c27-2" style="cursor: pointer" type="GROUP" href="/profile/bet-history">Casino Geçmişi</a>
                </li>
                <li style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted">
                    <a class="ng-tns-c27-2" style="cursor: pointer" type="GROUP" href="/profile/invite">Davet Linki</a>
                </li>
                <li style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted">
                    <a class="ng-tns-c27-2" style="cursor: pointer" type="GROUP" href="/profile/referral">Referans Programı</a>
                </li>
                <li style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted">
                    <a class="ng-tns-c27-2 select active" style="cursor: pointer" type="GROUP" href="/profile/responsible_gaming">Sorumlu Oyun</a>
                </li>
                
                <li style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted">
                    <span class="ng-tns-c27-2" aria-disabled="true" style="cursor: default;" type="GROUP"></span>
                </li>
                
                <li style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted">
                    <a class="ng-tns-c27-2" href="/promotions.php" style="cursor: pointer;" type="GROUP">Promosyonlar</a>
                </li>
                
                <li style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted">
                    <a class="ng-tns-c27-2" style="cursor: pointer" type="GROUP" href="/profile/deposit-withdraw">Para Yatırma/Para Çekme</a>
                </li>
                
                <li style="display: list-item;" class="ng-tns-c27-2 ng-star-inserted">
                    <a class="ng-tns-c27-2" style="cursor: pointer" type="GROUP" href="/profile/kyc">KYC</a>
                </li>
            </ul>
        </div>
    </aside>

    <div class="container-fluid">
        <div class="row">
            <div class="col-12 mt-theme">
                <button class="btn backBtn"><i class="fa-solid fa-angle-left"></i></button>
                <ul class="breadcrumb">
                    <li class="breadcrumb-item">
                        <a href="/">Ana Sayfa</a>
                    </li>
                    <li aria-current="page" class="breadcrumb-item">Sorumlu Oyun</li>
                </ul>
            </div>
            
            <div class="col-12">
                <div class="profileRow">
                    <div class="secTitle">
                        <h5><i class="fas fa-shield-alt me-2"></i>Sorumlu Oyun Araçları</h5>
                    </div>

                    <!-- Durum Kartları -->
                    <div class="row mb-4">
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-body text-center">
                                    <i class="fas fa-clock text-primary mb-2" style="font-size: 2rem;"></i>
                                    <h6>Günlük Limit</h6>
                                    <p class="mb-0"><span class="badge badge-success">Aktif</span></p>
                                    <small class="text-muted">500 ₺ / 1000 ₺</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-body text-center">
                                    <i class="fas fa-calendar-week text-warning mb-2" style="font-size: 2rem;"></i>
                                    <h6>Haftalık Limit</h6>
                                    <p class="mb-0"><span class="badge badge-warning">Pasif</span></p>
                                    <small class="text-muted">Limit belirlenmemiş</small>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <div class="card">
                                <div class="card-body text-center">
                                    <i class="fas fa-ban text-danger mb-2" style="font-size: 2rem;"></i>
                                    <h6>Self-Exclusion</h6>
                                    <p class="mb-0"><span class="badge badge-success">Aktif Değil</span></p>
                                    <small class="text-muted">Hesap erişilebilir</small>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Tab Navigation -->
                    <ul class="nav nav-tabs" id="responsibleGamingTabs" role="tablist">
                        <li class="nav-item" role="presentation">
                            <button class="nav-link active" id="limits-tab" data-bs-toggle="tab" data-bs-target="#limits" type="button" role="tab">
                                <i class="fas fa-sliders-h me-1"></i>Limitler
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="exclusion-tab" data-bs-toggle="tab" data-bs-target="#exclusion" type="button" role="tab">
                                <i class="fas fa-user-slash me-1"></i>Self-Exclusion
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="sessions-tab" data-bs-toggle="tab" data-bs-target="#sessions" type="button" role="tab">
                                <i class="fas fa-history me-1"></i>Oyun Oturumları
                            </button>
                        </li>
                        <li class="nav-item" role="presentation">
                            <button class="nav-link" id="warnings-tab" data-bs-toggle="tab" data-bs-target="#warnings" type="button" role="tab">
                                <i class="fas fa-exclamation-triangle me-1"></i>Uyarılar
                            </button>
                        </li>
                    </ul>

                    <!-- Tab Content -->
                    <div class="tab-content" id="responsibleGamingTabsContent">
                        <!-- Limitler Tab -->
                        <div class="tab-pane fade show active" id="limits" role="tabpanel">
                            <div class="row">
                                <div class="col-md-8">
                                    <div class="card">
                                        <div class="card-header">
                                            <h5 class="mb-0"><i class="fas fa-plus-circle me-2"></i>Yeni Limit Belirle</h5>
                                        </div>
                                        <div class="card-body">
                                            <form id="limitForm">
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="form-group">
                                                            <label for="limitType" class="form-label">Limit Türü</label>
                                                            <select class="form-control" id="limitType" required>
                                                                <option value="">Seçiniz</option>
                                                                <option value="daily">Günlük Limit</option>
                                                                <option value="weekly">Haftalık Limit</option>
                                                                <option value="monthly">Aylık Limit</option>
                                                            </select>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="form-group">
                                                            <label for="limitAmount" class="form-label">Limit Miktarı (₺)</label>
                                                            <input type="number" class="form-control" id="limitAmount" min="1" required>
                                                        </div>
                                                    </div>
                                                </div>
                                                <button type="submit" class="btn btn-primary">
                                                    <i class="fas fa-save me-1"></i>Limit Belirle
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="alert alert-info">
                                        <h6><i class="fas fa-info-circle me-1"></i>Limit Bilgileri</h6>
                                        <ul class="mb-0">
                                            <li>Limitler 24 saat sonra aktif olur</li>
                                            <li>Limit azaltma anında geçerlidir</li>
                                            <li>Limit artırma 7 gün sonra geçerlidir</li>
                                            <li>Limitler tüm oyunları kapsar</li>
                                        </ul>
                                    </div>
                                </div>
                            </div>

                            <!-- Mevcut Limitler -->
                            <div class="card mt-4">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-list me-2"></i>Mevcut Limitler</h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table">
                                            <thead>
                                                <tr>
                                                    <th>Limit Türü</th>
                                                    <th>Miktar</th>
                                                    <th>Kullanılan</th>
                                                    <th>Kalan</th>
                                                    <th>Durum</th>
                                                    <th>İşlem</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php
                                                $stmt = $conn->prepare("SELECT type, amount, used, status FROM user_limits WHERE user_id=?");
                                                $stmt->bind_param('i', $user_id);
                                                $stmt->execute();
                                                $res = $stmt->get_result();
                                                $hasRows = false;
                                                while ($row = $res->fetch_assoc()) {
                                                    $hasRows = true;
                                                    $typeText = ($row['type'] === 'daily') ? 'Günlük Limit' : (($row['type'] === 'weekly') ? 'Haftalık Limit' : 'Aylık Limit');
                                                    $amount = (int)$row['amount'];
                                                    $used = (int)$row['used'];
                                                    $remain = max(0, $amount - $used);
                                                    $badgeClass = ($row['status'] === 'active') ? 'badge-success' : 'badge-warning';
                                                    $badgeText = ($row['status'] === 'active') ? 'Aktif' : 'Pasif';
                                                    echo '<tr data-type="'.htmlspecialchars($row['type']).'">';
                                                    echo '<td class="limit-type">'.$typeText.'</td>';
                                                    echo '<td class="limit-amount">'.number_format($amount, 0, ',', '.')." ₺".'</td>';
                                                    echo '<td class="limit-used">'.number_format($used, 0, ',', '.')." ₺".'</td>';
                                                    echo '<td class="limit-remaining">'.number_format($remain, 0, ',', '.')." ₺".'</td>';
                                                    echo '<td class="limit-status"><span class="badge '.$badgeClass.'">'.$badgeText.'</span></td>';
                                                    echo '<td><button class="btn btn-sm btn-warning edit-limit-btn">Düzenle</button> <button class="btn btn-sm btn-danger delete-limit-btn">Kaldır</button></td>';
                                                    echo '</tr>';
                                                }
                                                $stmt->close();
                                                if (!$hasRows) {
                                                    echo '<tr><td colspan="6" class="text-center text-muted">Henüz tanımlı limitiniz yok.</td></tr>';
                                                }
                                                ?>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Self-Exclusion Tab -->
                        <div class="tab-pane fade" id="exclusion" role="tabpanel">
                            <div class="alert alert-danger">
                                <h4><i class="fas fa-exclamation-triangle me-2"></i>Dikkat!</h4>
                                <p>Self-exclusion işlemi geri alınamaz bir işlemdir. Belirlediğiniz süre boyunca hesabınıza erişim sağlayamayacaksınız.</p>
                            </div>

                            <div class="row">
                                <div class="col-md-8">
                                    <div class="card">
                                        <div class="card-header">
                                            <h5 class="mb-0"><i class="fas fa-user-slash me-2"></i>Self-Exclusion Başvurusu</h5>
                                        </div>
                                        <div class="card-body">
                                            <form id="exclusionForm">
                                                <div class="form-group">
                                                    <label for="exclusionPeriod" class="form-label">Exclusion Süresi</label>
                                                    <select class="form-control" id="exclusionPeriod" required>
                                                        <option value="">Seçiniz</option>
                                                        <option value="1">1 Ay</option>
                                                        <option value="3">3 Ay</option>
                                                        <option value="6">6 Ay</option>
                                                        <option value="12">1 Yıl</option>
                                                        <option value="permanent">Kalıcı</option>
                                                    </select>
                                                </div>
                                                <div class="form-group">
                                                    <label for="exclusionReason" class="form-label">Sebep (Opsiyonel)</label>
                                                    <textarea class="form-control" id="exclusionReason" rows="3" placeholder="Self-exclusion sebebinizi belirtebilirsiniz..."></textarea>
                                                </div>
                                                <div class="form-check">
                                                    <input class="form-check-input" type="checkbox" id="exclusionConfirm" required>
                                                    <label class="form-check-label" for="exclusionConfirm">
                                                        Bu işlemin geri alınamaz olduğunu anlıyorum ve onaylıyorum.
                                                    </label>
                                                </div>
                                                <button type="submit" class="btn btn-danger mt-3">
                                                    <i class="fas fa-ban me-1"></i>Self-Exclusion Uygula
                                                </button>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="card">
                                        <div class="card-header">
                                            <h6 class="mb-0">Self-Exclusion Geçmişi</h6>
                                        </div>
                                        <div class="card-body">
                                            <p class="text-muted">Henüz self-exclusion geçmişiniz bulunmamaktadır.</p>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Oyun Oturumları Tab -->
                        <div class="tab-pane fade" id="sessions" role="tabpanel">
                            <div class="loading text-center py-4">
                                <i class="fas fa-spinner fa-spin"></i>
                                <p>Oyun oturumları yükleniyor...</p>
                            </div>
                            
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-history me-2"></i>Son Oyun Oturumları</h5>
                                </div>
                                <div class="card-body">
                                    <div class="table-responsive">
                                        <table class="table">
                                            <thead>
                                                <tr>
                                                    <th>Tarih</th>
                                                    <th>Oyun</th>
                                                    <th>Süre</th>
                                                    <th>Bahis</th>
                                                    <th>Kazanç</th>
                                                    <th>Net</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <tr>
                                                    <td colspan="6" class="text-center text-muted">Henüz oyun oturumu bulunmamaktadır.</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Uyarılar Tab -->
                        <div class="tab-pane fade" id="warnings" role="tabpanel">
                            <div class="loading text-center py-4">
                                <i class="fas fa-spinner fa-spin"></i>
                                <p>Uyarılar yükleniyor...</p>
                            </div>
                            
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="mb-0"><i class="fas fa-exclamation-triangle me-2"></i>Sistem Uyarıları</h5>
                                </div>
                                <div class="card-body">
                                    <div class="alert alert-warning">
                                        <h6><i class="fas fa-info-circle me-1"></i>Bilgilendirme</h6>
                                        <p class="mb-0">Sorumlu oyun uyarıları burada görüntülenecektir. Şu anda aktif uyarınız bulunmamaktadır.</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Form işlemleri
document.getElementById('limitForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const limitType = document.getElementById('limitType').value;
    const limitAmount = parseInt(document.getElementById('limitAmount').value, 10);
    if (!limitType || !limitAmount || limitAmount <= 0) {
        alert('Lütfen geçerli bir limit türü ve miktar girin.');
        return;
    }
    const body = new URLSearchParams({ action: 'update_limit', type: limitType, amount: String(limitAmount) });
    fetch(location.pathname, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body })
      .then(r => r.json())
      .then(j => {
        if (j.status === 'success') {
          location.reload();
        } else {
          alert('Limit belirlenemedi.');
        }
      })
      .catch(() => alert('Bağlantı hatası'));
});

document.getElementById('exclusionForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const period = document.getElementById('exclusionPeriod').value;
    const confirm = document.getElementById('exclusionConfirm').checked;
    
    if (!period || !confirm) {
        alert('Lütfen tüm alanları doldurun ve onay kutusunu işaretleyin.');
        return;
    }
    
    if (confirm('Bu işlem geri alınamaz! Devam etmek istediğinizden emin misiniz?')) {
        // AJAX ile self-exclusion işlemi
        alert('Self-exclusion başvurunuz alınmıştır. 24 saat içinde işleme alınacaktır.');
    }
});

// Loading animasyonlarını gizle
setTimeout(function() {
    document.querySelectorAll('.loading').forEach(function(element) {
        element.style.display = 'none';
    });
}, 2000);
</script>

<!-- Limit Düzenleme Modalı -->
<div class="modal fade" id="editLimitModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title"><i class="fas fa-edit me-2"></i>Limit Düzenle</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="editLimitForm">
          <div class="mb-3">
            <label class="form-label">Limit Türü</label>
            <select class="form-control" id="editLimitType" required>
              <option value="daily">Günlük Limit</option>
              <option value="weekly">Haftalık Limit</option>
              <option value="monthly">Aylık Limit</option>
            </select>
          </div>
          <div class="mb-3">
            <label class="form-label">Limit Miktarı (₺)</label>
            <input type="number" class="form-control" id="editLimitAmount" min="1" required />
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">İptal</button>
        <button type="button" class="btn btn-primary" id="saveLimitChanges">Kaydet</button>
      </div>
    </div>
  </div>
 </div>

<script>
// Mevcut Limitler: Düzenle/Kaldır butonları
document.addEventListener('DOMContentLoaded', function() {
  const editButtons = document.querySelectorAll('.edit-limit-btn');
  const deleteButtons = document.querySelectorAll('.delete-limit-btn');
  const editModalEl = document.getElementById('editLimitModal');
  const editModal = new bootstrap.Modal(editModalEl);
  let currentRow = null;

  editButtons.forEach(btn => {
    btn.addEventListener('click', function() {
      const row = this.closest('tr');
      currentRow = row;
      const typeText = row.querySelector('.limit-type').textContent.trim();
      const amountText = row.querySelector('.limit-amount').textContent.trim();

      const typeMap = {
        'Günlük Limit': 'daily',
        'Haftalık Limit': 'weekly',
        'Aylık Limit': 'monthly'
      };

      const numericAmount = parseInt(amountText.replace(/[^0-9]/g, ''), 10) || 0;
      document.getElementById('editLimitType').value = typeMap[typeText] || 'daily';
      document.getElementById('editLimitAmount').value = numericAmount;

      editModal.show();
    });
  });

  document.getElementById('saveLimitChanges').addEventListener('click', function() {
    const newType = document.getElementById('editLimitType').value;
    const newAmount = parseInt(document.getElementById('editLimitAmount').value, 10);
    if (!newType || !newAmount || newAmount <= 0) {
      alert('Lütfen geçerli bir limit türü ve miktar girin.');
      return;
    }
    const body = new URLSearchParams({ action: 'update_limit', type: newType, amount: String(newAmount) });
    fetch(location.pathname, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body })
      .then(r => r.json())
      .then(j => {
        if (j.status === 'success') {
          editModal.hide();
          location.reload();
        } else {
          alert('Limit güncellenemedi.');
        }
      })
      .catch(() => alert('Bağlantı hatası'));
  });

  deleteButtons.forEach(btn => {
    btn.addEventListener('click', function() {
      const row = this.closest('tr');
      const type = row.getAttribute('data-type') || 'daily';
      if (confirm('Bu limiti kaldırmak istediğinize emin misiniz?')) {
        const body = new URLSearchParams({ action: 'remove_limit', type });
        fetch(location.pathname, { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body })
          .then(r => r.json())
          .then(j => {
            if (j.status === 'success') {
              location.reload();
            } else {
              alert('Limit kaldırılamadı.');
            }
          })
          .catch(() => alert('Bağlantı hatası'));
      }
    });
  });
});
</script>

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