<?php
session_start();
error_reporting(0);

define('SITES_PER_PAGE', 100);
define('DATA_DIR', __DIR__ . '/data');
define('CACHE_FILE', DATA_DIR . '/domains_cache.txt');
define('VOTES_FILE', DATA_DIR . '/votes.txt');
define('USER_SITES_FILE', DATA_DIR . '/user_sites.txt');
define('MALICIOUS_FILE', DATA_DIR . '/malicious.txt');
define('ADS_FILE', DATA_DIR . '/ads.txt');
define('IP_VOTES_FILE', DATA_DIR . '/ip_votes.txt');
define('IP_DOMAINS_FILE', DATA_DIR . '/ip_domains.txt');
define('BANNED_IPS_FILE', DATA_DIR . '/banned_ips.txt');

require_once 'functions.php';
require_once 'languages.php';

// Tema Yönetimi
if (isset($_GET['theme'])) $_SESSION['theme'] = $_GET['theme'];
$current_theme = $_SESSION['theme'] ?? 'dark';

$client_ip = getClientIP();
if (isIPBanned($client_ip)) die($t['access_denied'] ?? 'Erişim Engellendi');

// İşlemler
if (isset($_POST['vote'])) {
    $domain = $_POST['domain'];
    if (!checkIPVote($client_ip, $domain)) {
        $votes = loadVotes();
        $votes[$domain] = ($votes[$domain] ?? 0) + 1;
        saveVotes($votes);
        recordIPVote($client_ip, $domain);
        $_SESSION['success'] = $t['success_vote'] ?? 'Oyunuz kaydedildi!';
    }
    header('Location: index.php?' . http_build_query($_GET)); exit;
}

if (isset($_POST['mark_malicious'])) {
    markAsMalicious($_POST['domain']);
    $_SESSION['success'] = $t['success_malicious'] ?? 'Site zararlı olarak işaretlendi!';
    header('Location: index.php?' . http_build_query($_GET)); exit;
}

if (isset($_POST['add_site'])) {
    if (saveUserSite($_POST['new_domain'], $client_ip)) {
        $_SESSION['success'] = $t['success_add'] ?? 'Site eklendi!';
    }
    header('Location: index.php#add-site'); exit;
}

if (isset($_POST['add_bulk'])) {
    $domains = explode("\n", $_POST['bulk_domains']);
    $added = 0;
    foreach ($domains as $d) if (saveUserSite($d, $client_ip)) $added++;
    $_SESSION['success'] = "$added " . ($t['success_add'] ?? 'Site eklendi!');
    header('Location: index.php#add-site'); exit;
}

if (isset($_FILES['file_domains'])) {
    $result = processLargeFile($_FILES['file_domains']['tmp_name'], $client_ip);
    $_SESSION['success'] = $result['added'] . " " . ($t['success_add'] ?? 'Site eklendi!');
    header('Location: index.php#add-site'); exit;
}

$search = $_GET['search'] ?? '';
$page = max(1, (int)$_GET['page']);
$offset = ($page - 1) * SITES_PER_PAGE;

$votes = loadVotes();
arsort($votes);
$malicious = array_flip(loadMaliciousSites());
$display_domains = [];
$total_found = 0;

foreach ($votes as $domain => $count) {
    if (isset($malicious[$domain])) continue;
    if ($search && stripos($domain, $search) === false) continue;
    $total_found++;
    if ($total_found > $offset && count($display_domains) < SITES_PER_PAGE) {
        $display_domains[] = ['domain' => $domain, 'votes' => $count];
    }
}

if (count($display_domains) < SITES_PER_PAGE) {
    $files = [USER_SITES_FILE, CACHE_FILE];
    foreach ($files as $file) {
        if (!file_exists($file)) continue;
        $handle = fopen($file, "r");
        if ($handle) {
            while (($line = fgets($handle)) !== false) {
                $domain = trim($line);
                if (empty($domain) || isset($votes[$domain]) || isset($malicious[$domain])) continue;
                if ($search && stripos($domain, $search) === false) continue;
                $total_found++;
                if ($total_found > $offset && count($display_domains) < SITES_PER_PAGE) {
                    $display_domains[] = ['domain' => $domain, 'votes' => 0];
                }
                if (!$search && $total_found > $offset + SITES_PER_PAGE) break;
            }
            fclose($handle);
        }
    }
}

$ads = loadAds();
?>
<!DOCTYPE html>
<html lang="<?php echo $lang_code; ?>" data-theme="<?php echo $current_theme; ?>">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo $t['title']; ?></title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <div class="container">
            <h1>🌟 <?php echo $t['title']; ?></h1>
            <nav>
                <a href="index.php"><?php echo $t['home']; ?></a>
                <a href="admin/"><?php echo $t['admin']; ?></a>
            </nav>
        </div>
    </header>

    <main class="container">
        <div class="controls">
            <?php foreach($languages as $code => $data): ?>
                <a href="?lang=<?php echo $code; ?>&theme=<?php echo $current_theme; ?>" class="btn-small <?php echo $lang_code == $code ? 'active' : ''; ?>"><?php echo $data['name']; ?></a>
            <?php endforeach; ?>
        </div>

        <div class="controls">
            <?php $themes = ['dark' => '🌙 Dark', 'light' => '☀️ Light', 'blue' => '🔵 Blue', 'purple' => '🟣 Purple', 'green' => '🟢 Green']; ?>
            <?php foreach($themes as $key => $name): ?>
                <a href="?theme=<?php echo $key; ?>&lang=<?php echo $lang_code; ?>" class="btn-small <?php echo $current_theme == $key ? 'active' : ''; ?>"><?php echo $name; ?></a>
            <?php endforeach; ?>
        </div>

        <?php if($_SESSION['success']): ?><div class="alert alert-success"><?php echo $_SESSION['success']; unset($_SESSION['success']); ?></div><?php endif; ?>
        
        <div class="search-box">
            <form method="get">
                <input type="hidden" name="lang" value="<?php echo $lang_code; ?>">
                <input type="hidden" name="theme" value="<?php echo $current_theme; ?>">
                <input type="text" name="search" placeholder="<?php echo $t['search']; ?>..." value="<?php echo htmlspecialchars($search); ?>">
                <button type="submit" class="btn btn-primary"><?php echo $t['search']; ?></button>
            </form>
        </div>
        
        <div class="sites-list">
            <?php $counter = 0; foreach($display_domains as $site): $counter++; ?>
                <?php if($counter > 0 && $counter % 10 == 0 && !empty($ads)): ?><div class="ad-block"><?php echo $ads[array_rand($ads)]; ?></div><?php endif; ?>
                <div class="site-card">
                    <div class="site-rank">#<?php echo $offset + $counter; ?></div>
                    <div class="site-info">
                        <h3><a href="http://<?php echo $site['domain']; ?>" target="_blank"><?php echo $site['domain']; ?></a></h3>
                        <span>⭐ <?php echo $site['votes']; ?> <?php echo strtolower($t['vote']); ?></span>
                    </div>
                    <div class="site-actions">
                        <form method="post" style="display:inline;"><input type="hidden" name="domain" value="<?php echo $site['domain']; ?>"><button type="submit" name="vote" class="btn btn-vote"><?php echo $t['vote']; ?></button></form>
                        <form method="post" style="display:inline;"><input type="hidden" name="domain" value="<?php echo $site['domain']; ?>"><button type="submit" name="mark_malicious" class="btn btn-malicious"><?php echo $t['malicious']; ?></button></form>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>

        <div class="pagination">
            <?php if($page > 1): ?><a href="?page=<?php echo $page-1; ?>&search=<?php echo urlencode($search); ?>&lang=<?php echo $lang_code; ?>&theme=<?php echo $current_theme; ?>" class="btn"><?php echo $t['prev']; ?></a><?php endif; ?>
            <span class="btn btn-current"><?php echo $page; ?></span>
            <?php if(count($display_domains) == SITES_PER_PAGE): ?><a href="?page=<?php echo $page+1; ?>&search=<?php echo urlencode($search); ?>&lang=<?php echo $lang_code; ?>&theme=<?php echo $current_theme; ?>" class="btn"><?php echo $t['next']; ?></a><?php endif; ?>
        </div>

        <div id="add-site" class="add-site-section">
            <h2><?php echo $t['add']; ?></h2>
            <div style="display:grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 20px;">
                <div>
                    <h3><?php echo $t['add']; ?></h3>
                    <form method="post" class="add-site-form">
                        <input type="text" name="new_domain" placeholder="domain.com" required>
                        <button type="submit" name="add_site" class="btn btn-primary"><?php echo $t['add']; ?></button>
                    </form>
                </div>
                <div>
                    <h3><?php echo $t['bulk_add']; ?></h3>
                    <form method="post">
                        <textarea name="bulk_domains" style="width:100%; height:100px; margin-top:10px; background:var(--bg); color:var(--text); border:1px solid var(--border); border-radius:8px; padding:10px;" placeholder="domain1.com&#10;domain2.com"></textarea>
                        <button type="submit" name="add_bulk" class="btn btn-primary" style="width:100%; margin-top:10px;"><?php echo $t['add']; ?></button>
                    </form>
                </div>
            </div>
            <div style="margin-top:20px; border-top:1px solid var(--border); padding-top:20px;">
                <h3><?php echo $t['file_add']; ?> (.txt)</h3>
                <form method="post" enctype="multipart/form-data" style="margin-top:10px;">
                    <input type="file" name="file_domains" accept=".txt" required style="color:var(--text);">
                    <button type="submit" class="btn btn-primary"><?php echo $t['add']; ?></button>
                </form>
            </div>
        </div>
    </main>

    <footer>
        <div class="container">
            <p>Web Tasarım: <a href="https://proweb.net.tr">ProWeb.net.tr</a></p>
        </div>
    </footer>

    <button id="back-to-top" title="<?php echo $t['back_to_top']; ?>">↑</button>

    <script>
        const btt = document.getElementById("back-to-top");
        window.onscroll = function() {
            if (document.body.scrollTop > 200 || document.documentElement.scrollTop > 200) {
                btt.style.display = "flex";
            } else {
                btt.style.display = "none";
            }
        };
        btt.onclick = function() {
            window.scrollTo({top: 0, behavior: 'smooth'});
        };
    </script>
</body>
</html>
