<?php
session_start(); // Oturum başlat
include '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 (PDOException $e) {
    die("Veritabanına bağlanılamadı: " . $e->getMessage());
}
if (!isset($_SESSION['admin_logged_in'])) {
    header("Location: index.php");
    exit;
}

// Sayfalama ayarları
$limit = 9; // Sayfa başına gösterilecek veri sayısı
$page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
$offset = ($page - 1) * $limit;

// Toplam başvuru sayısını al
try {
    $total_stmt = $pdo->query("SELECT COUNT(*) AS total FROM affiliate_applications");
    $total_row = $total_stmt->fetch(PDO::FETCH_ASSOC);
    $total_affiliates = (int)$total_row['total'];
} catch (PDOException $e) {
    $total_affiliates = 0;
    $conn_error_message = "Veritabanı hatası: " . htmlspecialchars($e->getMessage());
}
$total_pages = max(1, (int)ceil($total_affiliates / $limit));

// Başvuru verilerini al
try {
    $apps_stmt = $pdo->prepare("SELECT * FROM affiliate_applications LIMIT :limit OFFSET :offset");
    $apps_stmt->bindValue(':limit', $limit, PDO::PARAM_INT);
    $apps_stmt->bindValue(':offset', $offset, PDO::PARAM_INT);
    $apps_stmt->execute();
    $result_affiliates = $apps_stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    $result_affiliates = [];
    $conn_error_message = "Veri alınırken hata: " . htmlspecialchars($e->getMessage());
}
?>

<!DOCTYPE html>
<html lang="tr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Affiliate Başvuruları</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons/font/bootstrap-icons.css" rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
</head>
<body>

    <div class="container-fluid">
        <div class="row">

    <!-- Yan Menü (Sidebar) -->
    <?php include 'sidebar.php'; ?>

            <div class="col-md-10 p-4">
    <?php if (!empty($conn_error_message)): ?>
        <div class="alert alert-danger" role="alert">
            <?php echo $conn_error_message; ?>
        </div>
    <?php endif; ?>

        <!-- Başvuru Tablosu -->
        <table class="table table-bordered table-sm">
            <thead class="table-light">
                <tr>
                    <th>ID</th>
                    <th>Ad Soyad</th>
                    <th>E-posta</th>
                    <th>Telefon</th>
                    <th>Kullanıcı Adı</th>
                    <th>Şirket</th>
                    <th>Web Sitesi</th>
                    <th>Telegram</th>
                    <th>Instagram</th>
                    <th>TikTok</th>
                    <th>Başvuru Tarihi</th>
                    <th>Durum</th>
                    <th>İşlem</th>
                </tr>
            </thead>
            <tbody>
                <?php if (!empty($result_affiliates)): ?>
                    <?php foreach ($result_affiliates as $row): ?>
                        <tr>
                            <td><?php echo htmlspecialchars($row['id']); ?></td>
                            <td><?php echo htmlspecialchars($row['first_name']) . ' ' . htmlspecialchars($row['last_name']); ?></td>
                            <td><?php echo htmlspecialchars($row['email']); ?></td>
                            <td><?php echo htmlspecialchars($row['phone_number']); ?></td>
                            <td><?php echo htmlspecialchars($row['username']); ?></td>
                            <td><?php echo htmlspecialchars($row['company']); ?></td>
                            <td>
                                <?php if (!empty($row['website'])): ?>
                                    <a href="<?php echo htmlspecialchars($row['website']); ?>" target="_blank" rel="noopener noreferrer">Site</a>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if (!empty($row['telegram_channel'])): ?>
                                    <a href="<?php echo htmlspecialchars($row['telegram_channel']); ?>" target="_blank" rel="noopener noreferrer">Telegram</a>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if (!empty($row['instagram'])): ?>
                                    <a href="<?php echo htmlspecialchars($row['instagram']); ?>" target="_blank" rel="noopener noreferrer">Instagram</a>
                                <?php endif; ?>
                            </td>
                            <td>
                                <?php if (!empty($row['tiktok'])): ?>
                                    <a href="<?php echo htmlspecialchars($row['tiktok']); ?>" target="_blank" rel="noopener noreferrer">TikTok</a>
                                <?php endif; ?>
                            </td>
                            <td><?php echo htmlspecialchars($row['created_at']); ?></td>
                            <td><?php echo htmlspecialchars(isset($row['status']) ? $row['status'] : 'Beklemede'); ?></td>
                            <td>
                                <button class="btn btn-success btn-sm" onclick="updateApplicationStatus(<?php echo (int)$row['id']; ?>, 'Onaylandı')">Onayla</button>
                                <button class="btn btn-danger btn-sm" onclick="updateApplicationStatus(<?php echo (int)$row['id']; ?>, 'Reddedildi')">Reddet</button>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                <?php else: ?>
                    <tr>
                        <td colspan="13">Kayıt bulunamadı.</td>
                    </tr>
                <?php endif; ?>
            </tbody>
        </table>

        <!-- Sayfalama -->
        <nav aria-label="Sayfalama">
            <ul class="pagination justify-content-center">
                <li class="page-item <?php if ($page == 1) echo 'disabled'; ?>">
                    <a class="page-link" href="?page=<?php echo $page - 1; ?>">Önceki</a>
                </li>
                <?php for ($i = 1; $i <= $total_pages; $i++): ?>
                    <li class="page-item <?php if ($i == $page) echo 'active'; ?>">
                        <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                    </li>
                <?php endfor; ?>
                <li class="page-item <?php if ($page == $total_pages) echo 'disabled'; ?>">
                    <a class="page-link" href="?page=<?php echo $page + 1; ?>">Sonraki</a>
                </li>
            </ul>
        </nav>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        function updateApplicationStatus(id, status) {
            if (!confirm('Başvuruyu ' + status + ' olarak işaretlemek istiyor musunuz?')) return;
            fetch('update_application_status.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: new URLSearchParams({ id: id, status: status })
            })
            .then(res => res.text())
            .then(text => {
                if (text.trim() === 'OK') {
                    alert('Başvuru durumu güncellendi.');
                    location.reload();
                } else {
                    alert('Hata: ' + text);
                }
            })
            .catch(err => alert('İstek başarısız: ' + err));
        }
    </script>
        </div>
    </div>
</body>
</html>
