<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

error_reporting(E_ALL);
ini_set('display_errors', 1);
set_time_limit(10);

require_once __DIR__ . '/php/include/db.php';

/* ===== SAFE SERVER LOAD CHECK ===== */
$load = function_exists('sys_getloadavg') ? sys_getloadavg() : [0];
$serverBusy = ($load[0] ?? 0) > 4;

/* ===== SAFE FETCH FUNCTION ===== */
function fetchCount(PDO $db, string $sql): int
{
    try {
        $stmt = $db->query($sql);

        if (!$stmt) {
            return 0;
        }

        $value = $stmt->fetchColumn();

        return ($value !== false) ? (int) $value : 0;
    } catch (Throwable $e) {
        return 0;
    }
}

/* ===== PORT CHECK ===== */
function checkPort(string $host, int $port, int $timeout = 1): bool
{
    $fp = @fsockopen($host, $port, $errno, $errstr, $timeout);

    if ($fp) {
        fclose($fp);
        return true;
    }

    return false;
}

/* ===== CHANNEL CONFIG ===== */
$host = '62.146.235.210';

$channelPorts = [
    1  => 35011,
    2  => 35021,
    3  => 35059,
    4  => 35014,
    5  => 35058,
    16 => 35019
];

/* ===== CACHE SYSTEM ===== */
$cacheDir = __DIR__ . '/cache';
$cacheFile = $cacheDir . '/cache_stats.json';
$cacheTime = 5;

if (!is_dir($cacheDir)) {
    @mkdir($cacheDir, 0755, true);
}

/* ===== SERVER STATS ===== */
$totalAccounts = fetchCount(
    $conn,
    "SELECT COUNT(*) FROM cabal_auth_table WITH (NOLOCK)"
);

$onlinePlayers = fetchCount(
    $connServer,
    "SELECT COUNT(*) FROM cabal_character_table WITH (NOLOCK) WHERE Login = 1"
);

$recentLogins = fetchCount(
    $conn,
    "SELECT COUNT(*) FROM cabal_auth_table WITH (NOLOCK)"
);

/* ===== CHANNEL PLAYERS ===== */
$channelCounts = [
    1  => 0,
    2  => 0,
    3  => 0,
    4  => 0,
    5  => 0,
    16 => 0
];

try {
    $stmt = $connServer->query("
        SELECT CHANNELIDX, COUNT(*) AS total
        FROM cabal_character_table WITH (NOLOCK)
        WHERE Login = 1
        GROUP BY CHANNELIDX
    ");

    if ($stmt) {
        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
            $ch = (int) $row['CHANNELIDX'];

            if (isset($channelCounts[$ch])) {
                $channelCounts[$ch] = (int) $row['total'];
            }
        }
    }
} catch (Throwable $e) {
    // Keep default channel counts.
}

function getBars(int $players, int $max = 100): int
{
    return (int) round(min(100, ($players / $max) * 100) / 10);
}

/* ===== STATUS ===== */
$serverStatus = ($onlinePlayers > 0) ? 'Online' : 'Online (Idle)';
$statusColor = ($onlinePlayers > 0) ? 'text-green-400' : 'text-yellow-400';

/* ===== LOGIN ===== */
$loginError = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['id'])) {
    $id = trim((string) ($_POST['id'] ?? ''));
    $pwd = (string) ($_POST['password'] ?? '');

    try {
        $stmt = $conn->prepare("
            SELECT ID, UserNum, Password
            FROM cabal_auth_table WITH (NOLOCK)
            WHERE ID = :id
        ");

        $stmt->execute([':id' => $id]);
        $row = $stmt->fetch(PDO::FETCH_ASSOC);

        if ($row) {
            $stmtPwd = $conn->prepare("
                SELECT pwdcompare(:pwd, Password) AS pwdMatch
                FROM cabal_auth_table
                WHERE ID = :id
            ");

            $stmtPwd->execute([
                ':id'  => $row['ID'],
                ':pwd' => $pwd
            ]);

            $pwdResult = $stmtPwd->fetch(PDO::FETCH_ASSOC);

            if ($pwdResult && (int) $pwdResult['pwdMatch'] === 1) {
                session_regenerate_id(true);

                $_SESSION['user'] = $row['ID'];
                $_SESSION['usernum'] = $row['UserNum'];
                $_SESSION['logged_in'] = true;

                header('Location: /php/index.php');
                exit();
            }

            $loginError = 'Invalid password.';
        } else {
            $loginError = 'Username not found.';
        }
    } catch (Throwable $e) {
        $loginError = 'Login error.';
    }
}

/* ===== LATENCY ===== */
$latencyHost = '62.146.235.210';
$latencyPort = 35010;
$latency = 'N/A';

$start = microtime(true);
$fp = @fsockopen($latencyHost, $latencyPort, $errno, $errstr, 1);

if ($fp) {
    fclose($fp);
    $latency = number_format((microtime(true) - $start) * 1000, 2) . ' ms';
} else {
    $latency = 'Offline';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Cabal Resurrections</title>

<script src="https://cdn.tailwindcss.com"></script>

<link href="https://fonts.googleapis.com/css2?family=Orbitron:wght@600;700;800&family=Rajdhani:wght@400;500;600;700&display=swap" rel="stylesheet">

<style>
body {
    min-height: 100vh;
    margin: 0;
    background:
        linear-gradient(rgba(10, 14, 24, 0.82), rgba(10, 14, 24, 0.92)),
        url('/php/assets/bg.png') no-repeat center top fixed;
    background-size: cover;
    color: #fff7ed;
    font-family: 'Rajdhani', sans-serif;
}

body,
button,
input,
select,
textarea,
a,
p,
span,
div,
h1,
h2,
h3,
h4,
h5,
h6 {
    font-family: 'Rajdhani', sans-serif;
}

.hero-title,
.section-title,
.hero-tag {
    font-family: 'Orbitron', sans-serif;
}

.home-shell {
    max-width: 88rem;
}

.home-panel {
    background: linear-gradient(180deg, rgba(24, 32, 47, 0.95), rgba(15, 20, 31, 0.96));
    border: 1px solid rgba(251, 191, 36, 0.14);
    box-shadow: 0 18px 40px rgba(0, 0, 0, 0.35);
}

.section-title,
.hero-tag {
    letter-spacing: 0.06em;
    text-transform: uppercase;
}

.home-link {
    display: inline-flex;
    align-items: center;
    color: #fdba74;
    font-weight: 600;
    transition: color 0.2s ease, transform 0.2s ease;
}

.home-link:hover {
    color: #fcd34d;
    transform: translateX(2px);
}

.feature-pill {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    border-radius: 9999px;
    border: 1px solid;
    padding: 0.4rem 0.8rem;
    font-size: 0.72rem;
    font-weight: 700;
    letter-spacing: 0.08em;
    text-transform: uppercase;
}

.server-highlights {
    background: linear-gradient(180deg, rgba(8, 30, 40, 0.55), rgba(17, 24, 39, 0.2));
    border: 1px solid rgba(34, 211, 238, 0.2);
}

/* Homepage presentation layer — no gameplay, login, or server logic below is changed. */
html { scroll-behavior: smooth; }
body { background: #080b10; }
.legacy-home { width: 100%; overflow: hidden; background: radial-gradient(ellipse 75% 30% at 50% 10%, rgba(170, 98, 27, .16), transparent 70%), #080b10; }
.legacy-home * { box-sizing: border-box; }
.landing-hero { position: relative; isolation: isolate; min-height: clamp(560px, 43vw, 690px); display: flex; align-items: center; overflow: hidden; border-bottom: 1px solid rgba(229, 169, 90, .28); }
.landing-hero::before { content: ''; position: absolute; inset: 0; z-index: -2; background: #080b10 url('/assets/wall4.jpg') center / contain no-repeat; opacity: .88; }
.landing-hero::after { content: ''; position: absolute; inset: 0; z-index: -1; background: linear-gradient(90deg, #080b10f7 0%, #080b10e2 31%, #080b1080 57%, #080b1025), linear-gradient(0deg, #080b10 0%, transparent 48%); }
.landing-hero__inner { width: min(1220px, 100%); margin: 0 auto; padding: 76px 26px 86px; }
.landing-hero__content { width: min(560px, 100%); position: relative; z-index: 1; }
.landing-hero__eyebrow { color: #e4b87d; font-size: 12px; font-weight: 700; letter-spacing: .21em; text-transform: uppercase; }
.landing-hero__eyebrow::before { content: ''; display: inline-block; width: 8px; height: 8px; margin-right: 10px; background: #f5ba72; box-shadow: 0 0 16px #f5a24b; }
.landing-hero h1 { margin-top: 18px; font-family: 'Orbitron', sans-serif; font-size: clamp(38px, 5.2vw, 72px); line-height: 1.05; letter-spacing: -.045em; text-transform: uppercase; text-shadow: 0 5px 30px #000a; }
.landing-hero h1 span { color: #ebba7c; }
.landing-hero__lead { max-width: 510px; margin-top: 24px; color: #bac0c8; font-size: 19px; line-height: 1.6; }
.landing-actions { display: flex; flex-wrap: wrap; gap: 13px; margin-top: 30px; }
.landing-button { display: inline-flex; align-items: center; justify-content: space-between; gap: 30px; min-height: 55px; padding: 15px 22px; border: 1px solid rgba(239, 190, 126, .45); font-weight: 700; letter-spacing: .09em; text-transform: uppercase; transition: transform .2s ease, box-shadow .2s ease, background .2s ease; }
.landing-button:hover { transform: translateY(-3px); }
.landing-button--primary { background: linear-gradient(110deg, #f4cc93, #d99851); color: #21170e; box-shadow: 0 10px 32px rgba(216, 139, 57, .2); }
.landing-button--secondary { background: rgba(12, 17, 25, .78); color: #f3eadc; }
.landing-button--secondary:hover { background: rgba(86, 59, 35, .75); }
.landing-hero__logo { position: absolute; width: min(25vw, 310px); left: 50%; top: 50%; z-index: 1; transform: translate(-50%, -50%); filter: drop-shadow(0 15px 36px #000b); }
.landing-hero__logo::before { content: ''; position: absolute; inset: 14%; border-radius: 50%; background: rgba(233, 145, 48, .18); filter: blur(44px); z-index: -1; }
.landing-hero__logo img { width: 100%; height: auto; }
.realm-overview { width: min(1210px, calc(100% - 48px)); margin: -38px auto 0; position: relative; z-index: 2; }
.realm-overview .home-panel { border-radius: 4px; background: linear-gradient(125deg, rgba(21, 28, 39, .98), rgba(9, 13, 20, .98)); }
.realm-overview__heading { display: flex; justify-content: space-between; align-items: center; gap: 18px; padding-bottom: 18px; border-bottom: 1px solid rgba(232, 184, 117, .2); }
.realm-overview__heading h2 { margin: 0; text-align: left; font-family: 'Rajdhani', sans-serif; letter-spacing: .03em; }
.realm-live { display: inline-flex; align-items: center; gap: 8px; color: #b9c2cd; font-size: 11px; letter-spacing: .13em; }
.realm-live::before { content: ''; width: 7px; height: 7px; border-radius: 50%; background: #4ade80; box-shadow: 0 0 0 4px rgba(74, 222, 128, .12), 0 0 13px #4ade80; }
.realm-card { padding: 18px; border: 1px solid rgba(255, 255, 255, .08); background: linear-gradient(135deg, rgba(255,255,255,.045), transparent); }
.realm-card h3 { letter-spacing: .07em; text-transform: uppercase; }
.channel-card { min-height: 112px; transition: transform .2s ease, border-color .2s ease; }
.channel-card:hover { transform: translateY(-3px); border-color: rgba(233, 185, 118, .7); }
.channel-bars > div { border-radius: 999px; }
.realm-features { width: min(1120px, calc(100% - 48px)); margin: 70px auto 78px; display: grid; grid-template-columns: repeat(3, 1fr); gap: 40px; }
.realm-features article { border-top: 1px solid rgba(225, 177, 108, .32); padding-top: 20px; }
.realm-features span { color: #d5aa71; font-size: 11px; font-weight: 700; letter-spacing: .16em; }
.realm-features h2 { margin-top: 11px; font-size: 28px; font-weight: 600; }
.realm-features p { margin-top: 8px; color: #98a3b0; font-size: 16px; line-height: 1.6; }
.battle-styles { position: relative; isolation: isolate; width: min(1210px, calc(100% - 48px)); min-height: 405px; margin: 0 auto 84px; overflow: hidden; border: 1px solid rgba(224, 178, 110, .28); background: #10141a; }
.battle-styles::before { content: ''; position: absolute; inset: 0; z-index: -2; background: url('/assets/background2.jpg') center / cover no-repeat; opacity: .48; }
.battle-styles::after { content: ''; position: absolute; inset: 0; z-index: -1; background: linear-gradient(90deg, #0a0f16f5 0%, #0a0f16df 35%, #0a0f1655 69%, #0a0f1622); }
.battle-styles__content { width: min(510px, 100%); padding: 62px 54px; }
.battle-styles__eyebrow { color: #d8ad70; font-size: 11px; font-weight: 700; letter-spacing: .19em; text-transform: uppercase; }
.battle-styles h2 { margin-top: 13px; font-size: clamp(34px, 4vw, 56px); font-weight: 600; line-height: 1.05; }
.battle-styles h2 span { color: #edbd80; }
.battle-styles p { margin-top: 16px; color: #abb4be; font-size: 17px; line-height: 1.6; }
.battle-styles__list { display: flex; flex-wrap: wrap; gap: 8px; margin-top: 26px; }
.battle-styles__list span { padding: 8px 11px; border: 1px solid rgba(234, 191, 124, .26); background: rgba(8, 13, 19, .58); color: #dde2e8; font-size: 11px; font-weight: 700; letter-spacing: .08em; text-transform: uppercase; }
.battle-styles__link { display: inline-flex; margin-top: 26px; color: #efbf80; font-size: 12px; font-weight: 700; letter-spacing: .12em; text-transform: uppercase; transition: color .2s ease, transform .2s ease; }
.battle-styles__link:hover { color: #ffdb9c; transform: translateX(4px); }
@media (max-width: 760px) { .landing-hero { min-height: auto; } .landing-hero::before { background-position: 60% center; } .landing-hero__inner { padding: 62px 24px 76px; text-align: center; } .landing-hero__content { margin: auto; } .landing-hero__logo { position: relative; top: auto; left: auto; transform: none; width: 170px; margin: 0 auto 25px; } .landing-actions { justify-content: center; } .realm-overview { width: min(100% - 32px, 1210px); margin-top: -26px; } .realm-overview__heading { align-items: flex-start; flex-direction: column; } .realm-features { grid-template-columns: 1fr; gap: 28px; margin: 50px auto; } .battle-styles { width: min(100% - 32px, 1210px); min-height: 510px; margin-bottom: 55px; } .battle-styles::before { background-position: 61% center; opacity: .34; } .battle-styles__content { padding: 42px 27px; } }
@media (prefers-reduced-motion: reduce) { html { scroll-behavior: auto; } .landing-button, .channel-card { transition: none; } .landing-button:hover, .channel-card:hover { transform: none; } }
</style>
</head>

<body class="flex flex-col">

<?php include __DIR__ . '/php/include/header.php'; ?>

<main class="legacy-home flex-grow">

    <section class="landing-hero" aria-labelledby="hero-heading">
        <div class="landing-hero__inner">
            <div class="landing-hero__content">
                <p class="landing-hero__eyebrow">Cabal Resurrections · Episode 38</p>
                <h1 id="hero-heading">Legends never die.<br><span>They rise again.</span></h1>
                <p class="landing-hero__lead">Return to Nevareth with meaningful progression, a player-driven economy, and a world built for your next chapter.</p>
                <div class="landing-actions">
                    <button type="button" onclick="openDownloadModal()" class="landing-button landing-button--primary">Download &amp; Play <span aria-hidden="true">↗</span></button>
                    <button type="button" onclick="openRegister()" class="landing-button landing-button--secondary">Create Account <span aria-hidden="true">+</span></button>
                </div>
            </div>
            <div class="landing-hero__logo" aria-hidden="true"><img src="/php/assets/resulogo.png" alt=""></div>
        </div>
    </section>

    <section class="realm-features" aria-label="Server highlights">
        <article><span>01 / PROGRESSION</span><h2>Build your legend.</h2><p>Every dungeon, upgrade, and achievement becomes part of a lasting journey.</p></article>
        <article><span>02 / COMPETITION</span><h2>Answer the call.</h2><p>Stand with your allies, sharpen your skills, and earn your place in Nevareth.</p></article>
        <article><span>03 / ECONOMY</span><h2>Earn your power.</h2><p>Progress with purpose in an economy designed around player experience.</p></article>
    </section>

    <section class="battle-styles" aria-labelledby="battle-styles-heading">
        <div class="battle-styles__content">
            <p class="battle-styles__eyebrow">One world. Your way to fight.</p>
            <h2 id="battle-styles-heading">Choose your <span>power.</span></h2>
            <p>Find the battle style that fits your legend, then make your mark across Nevareth.</p>
            <div class="battle-styles__list" aria-label="Available battle styles">
                <span>Warrior</span><span>Blader</span><span>Wizard</span><span>Force Archer</span><span>Force Shielder</span><span>Force Blader</span>
            </div>
            <button type="button" onclick="openRegister()" class="battle-styles__link">Begin your journey&nbsp; ↗</button>
        </div>
    </section>

    <?php if ($loginError !== ''): ?>
        <section class="mb-8">
            <div class="home-panel rounded-2xl px-5 py-4 border border-red-400/20 text-red-300 text-center">
                <?= htmlspecialchars($loginError, ENT_QUOTES, 'UTF-8') ?>
            </div>
        </section>
    <?php endif; ?>

    <section class="realm-overview">
        <div class="home-panel rounded-3xl p-6 sm:p-8">

            <div class="realm-overview__heading mb-6"><h2 class="section-title text-2xl font-bold text-yellow-400">The realm, at a glance</h2><span class="realm-live">LIVE REALM STATUS</span></div>

            <div class="grid sm:grid-cols-2 gap-6 mb-6">

                <div class="realm-card space-y-3 text-lg text-gray-200">
                    <h3 class="text-yellow-300 font-bold text-lg mb-2">Server Status</h3>

                    <p class="flex justify-between">
                        <span>Status</span>
                        <span class="font-bold <?= htmlspecialchars($statusColor, ENT_QUOTES, 'UTF-8') ?>">
                            <?= htmlspecialchars($serverStatus, ENT_QUOTES, 'UTF-8') ?>
                        </span>
                    </p>

                    <p class="flex justify-between">
                        <span>Latency</span>
                        <span class="font-bold text-cyan-300">
                            <?= htmlspecialchars($latency, ENT_QUOTES, 'UTF-8') ?>
                        </span>
                    </p>

                    <p class="flex justify-between">
                        <span>Channels</span>
                        <span class="font-bold text-white">
                            <?= count($channelPorts) ?>
                        </span>
                    </p>
                </div>

                <div class="realm-card space-y-3 text-lg text-gray-200">
                    <h3 class="text-yellow-300 font-bold text-lg mb-2">Server Statistics</h3>

                    <p class="flex justify-between">
                        <span>Accounts</span>
                        <span class="font-bold text-white">
                            <?= number_format($totalAccounts) ?>
                        </span>
                    </p>

                    <p class="flex justify-between">
                        <span>Online Players</span>
                        <span class="font-bold text-green-400">
                            <?= number_format($onlinePlayers) ?>
                        </span>
                    </p>

                    <p class="flex justify-between">
                        <span>Logins (24h)</span>
                        <span class="font-bold text-cyan-300">
                            <?= number_format($recentLogins) ?>
                        </span>
                    </p>
                </div>

            </div>

            <div class="server-highlights rounded-xl px-4 py-3 text-sm text-slate-200 mb-6">
                Balanced economy, anti-generated-item rules, and long-term progression design for sustainable gameplay.
            </div>

            <div>
                <h3 class="text-sm text-gray-400 mb-3">Channel Status</h3>

                <div class="grid grid-cols-2 sm:grid-cols-3 md:grid-cols-6 gap-3">
                    <?php foreach ($channelPorts as $ch => $port): ?>
                        <?php
                        $online = checkPort($host, $port);
                        $players = $channelCounts[$ch] ?? 0;
                        $bars = getBars($players);
                        ?>

                        <div class="channel-card bg-black/40 p-3 rounded-lg border <?= $ch === 16 ? 'border-purple-500' : 'border-white/10' ?>">

                            <div class="flex justify-between items-center mb-2">
                                <span class="text-xs font-semibold">
                                    <?= $ch === 16 ? 'WAR' : 'CH' . $ch ?>
                                </span>

                                <span class="text-[10px] <?= $online ? 'text-green-400' : 'text-red-400' ?>">
                                    <?= $online ? 'ONLINE' : 'OFFLINE' ?>
                                </span>
                            </div>

                            <div class="channel-bars flex gap-1 mb-2">
                                <?php for ($i = 0; $i < 10; $i++): ?>
                                    <div class="w-2 h-2 <?= $i < $bars ? 'bg-red-500' : 'bg-gray-700' ?>"></div>
                                <?php endfor; ?>
                            </div>

                            <div class="text-[10px] text-gray-400">
                                <?= number_format($players) ?> players
                            </div>

                        </div>
                    <?php endforeach; ?>
                </div>
            </div>

        </div>
    </section>

</main>

<?php include __DIR__ . '/php/include/footer.php'; ?>
<?php include __DIR__ . '/login_modal.php'; ?>
<?php include __DIR__ . '/register_modal.php'; ?>
<?php include __DIR__ . '/downloadnew.php'; ?>

<audio id="siteBgm" autoplay loop muted playsinline>
    <source src="/php/assets/music.mp3" type="audio/mpeg">
</audio>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const bgm = document.getElementById('siteBgm');

    if (!bgm) {
        return;
    }

    bgm.volume = 0.75; // 75%
    bgm.muted = true;

    function tryAutoplay() {
        const playPromise = bgm.play();

        if (playPromise && typeof playPromise.catch === 'function') {
            playPromise.catch(function () {
                waitForUserInteraction();
            });
        }
    }

    function enableSound() {
        bgm.muted = false;
        bgm.play().catch(function () {});
        document.removeEventListener('click', enableSound);
        document.removeEventListener('touchstart', enableSound);
        document.removeEventListener('keydown', enableSound);
    }

    function waitForUserInteraction() {
        document.addEventListener('click', enableSound, { once: true });
        document.addEventListener('touchstart', enableSound, { once: true });
        document.addEventListener('keydown', enableSound, { once: true });
    }

    tryAutoplay();
    waitForUserInteraction();
});
</script>

</body>
</html>

