<?php

declare(strict_types=1);

/*
|--------------------------------------------------------------------------
| Bootstrap dan session
|--------------------------------------------------------------------------
*/

$bootstrapFile = __DIR__ . '/bootstrap.php';

if (is_file($bootstrapFile)) {
    require_once $bootstrapFile;
}

if (session_status() === PHP_SESSION_NONE) {
    session_name('USERSESSID');
    session_start();
}

if (!function_exists('e')) {
    function e($value)
    {
        return htmlspecialchars(
            (string) $value,
            ENT_QUOTES,
            'UTF-8'
        );
    }
}

/*
|--------------------------------------------------------------------------
| Informasi halaman
|--------------------------------------------------------------------------
*/

$siteName = isset($siteName)
    ? (string) $siteName
    : 'Platform Online';

$pageTitle = 'Login Member';
$activeMenu = '';
$isLoggedIn = !empty($_SESSION['user_id']);

/*
|--------------------------------------------------------------------------
| Pengguna yang sudah login langsung ke beranda
|--------------------------------------------------------------------------
*/

if ($isLoggedIn && !isset($_GET['stay'])) {
    header('Location: index.php');
    exit;
}

/*
|--------------------------------------------------------------------------
| Koneksi database PDO
|--------------------------------------------------------------------------
*/

$databaseFile = __DIR__ . '/config/database.php';

if (!isset($pdo) || !($pdo instanceof PDO)) {
    if (!is_file($databaseFile)) {
        http_response_code(500);

        exit(
            'File koneksi database tidak ditemukan: ' .
            e($databaseFile)
        );
    }

    require_once $databaseFile;
}

if (!isset($pdo) || !($pdo instanceof PDO)) {
    http_response_code(500);

    exit(
        'Koneksi PDO $pdo tidak tersedia dari config/database.php.'
    );
}

$pdo->setAttribute(
    PDO::ATTR_ERRMODE,
    PDO::ERRMODE_EXCEPTION
);

$pdo->setAttribute(
    PDO::ATTR_DEFAULT_FETCH_MODE,
    PDO::FETCH_ASSOC
);

/*
|--------------------------------------------------------------------------
| Helper redirect aman
|--------------------------------------------------------------------------
*/

function loginSafeRedirect(string $target): string
{
    $target = trim($target);

    if ($target === '') {
        return 'index.php';
    }

    /*
     * Tolak URL eksternal, protocol-relative, dan karakter baris baru.
     */
    if (
        preg_match('/[\r\n]/', $target) ||
        strpos($target, '//') === 0 ||
        preg_match('/^[a-z][a-z0-9+.-]*:/i', $target)
    ) {
        return 'index.php';
    }

    /*
     * Hanya izinkan path lokal sederhana.
     */
    if (!preg_match('/^[A-Za-z0-9_\-\.\/\?\=&%]+$/', $target)) {
        return 'index.php';
    }

    return ltrim($target, '/');
}

/*
|--------------------------------------------------------------------------
| CSRF
|--------------------------------------------------------------------------
*/

if (
    empty($_SESSION['login_csrf']) ||
    !is_string($_SESSION['login_csrf'])
) {
    $_SESSION['login_csrf'] =
        bin2hex(random_bytes(32));
}

$csrfToken = (string) $_SESSION['login_csrf'];

/*
|--------------------------------------------------------------------------
| Pembatasan percobaan login sederhana berbasis session
|--------------------------------------------------------------------------
*/

$attemptLimit = 5;
$lockDuration = 600;

$loginAttempts = isset($_SESSION['login_attempts'])
    ? (int) $_SESSION['login_attempts']
    : 0;

$loginLockedUntil = isset($_SESSION['login_locked_until'])
    ? (int) $_SESSION['login_locked_until']
    : 0;

if (
    $loginLockedUntil > 0 &&
    $loginLockedUntil <= time()
) {
    unset(
        $_SESSION['login_attempts'],
        $_SESSION['login_locked_until']
    );

    $loginAttempts = 0;
    $loginLockedUntil = 0;
}

/*
|--------------------------------------------------------------------------
| Nilai formulir
|--------------------------------------------------------------------------
*/

$formLogin = '';
$errors = [];

$nextUrl = loginSafeRedirect(
    isset($_GET['next'])
        ? (string) $_GET['next']
        : (
            isset($_POST['next'])
                ? (string) $_POST['next']
                : 'index.php'
        )
);

/*
|--------------------------------------------------------------------------
| Pesan setelah pendaftaran
|--------------------------------------------------------------------------
*/

$registeredMessage =
    isset($_GET['registered']) &&
    $_GET['registered'] === '1';

/*
|--------------------------------------------------------------------------
| Proses login
|--------------------------------------------------------------------------
*/

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $formLogin = trim(
        (string) ($_POST['login'] ?? '')
    );

    $password = (string) ($_POST['password'] ?? '');
    $postedCsrf =
        (string) ($_POST['csrf_token'] ?? '');

    if (
        $postedCsrf === '' ||
        !hash_equals($csrfToken, $postedCsrf)
    ) {
        $errors[] =
            'Sesi formulir sudah berubah. Muat ulang halaman lalu coba lagi.';
    }

    if (
        $loginLockedUntil > time()
    ) {
        $remainingSeconds =
            $loginLockedUntil - time();

        $remainingMinutes =
            max(
                1,
                (int) ceil($remainingSeconds / 60)
            );

        $errors[] =
            'Terlalu banyak percobaan login. Coba lagi dalam ' .
            $remainingMinutes .
            ' menit.';
    }

    if ($formLogin === '') {
        $errors[] =
            'Masukkan username atau email.';
    }

    if ($password === '') {
        $errors[] =
            'Masukkan password.';
    }

    if (
        $formLogin !== '' &&
        strlen($formLogin) > 191
    ) {
        $errors[] =
            'Username atau email terlalu panjang.';
    }

    if (empty($errors)) {
        try {
            $userStatement = $pdo->prepare(
                'SELECT
                    id,
                    username,
                    password_hash,
                    email,
                    phone,
                    payment_method,
                    account_number,
                    account_name,
                    balance_local,
                    referral_balance,
                    referral_code,
                    upline_id,
                    status
                 FROM users
                 WHERE username = :login_username
                    OR email = :login_email
                 LIMIT 1'
            );

            $userStatement->execute([
                ':login_username' => $formLogin,
                ':login_email' => strtolower($formLogin),
            ]);

            $user = $userStatement->fetch();

            $passwordValid =
                $user &&
                isset($user['password_hash']) &&
                password_verify(
                    $password,
                    (string) $user['password_hash']
                );

            if (!$passwordValid) {
                $loginAttempts++;

                $_SESSION['login_attempts'] =
                    $loginAttempts;

                if ($loginAttempts >= $attemptLimit) {
                    $loginLockedUntil =
                        time() + $lockDuration;

                    $_SESSION['login_locked_until'] =
                        $loginLockedUntil;

                    $errors[] =
                        'Login gagal lima kali. Akses login dikunci sementara selama 10 menit.';
                } else {
                    $remainingAttempts =
                        $attemptLimit - $loginAttempts;

                    $errors[] =
                        'Username/email atau password tidak sesuai. Sisa percobaan: ' .
                        $remainingAttempts .
                        '.';
                }
            } elseif (
                strtoupper((string) $user['status']) !==
                'ACTIVE'
            ) {
                $errors[] =
                    'Akun belum aktif atau sedang dibatasi. Hubungi layanan pelanggan.';
            } else {
                /*
                |--------------------------------------------------------------------------
                | Perbarui hash lama bila algoritma berubah
                |--------------------------------------------------------------------------
                */

                if (
                    password_needs_rehash(
                        (string) $user['password_hash'],
                        PASSWORD_DEFAULT
                    )
                ) {
                    $newPasswordHash =
                        password_hash(
                            $password,
                            PASSWORD_DEFAULT
                        );

                    if ($newPasswordHash !== false) {
                        $rehashStatement =
                            $pdo->prepare(
                                'UPDATE users
                                 SET password_hash = :password_hash
                                 WHERE id = :id'
                            );

                        $rehashStatement->execute([
                            ':password_hash' =>
                                $newPasswordHash,
                            ':id' => (int) $user['id'],
                        ]);
                    }
                }

                /*
                |--------------------------------------------------------------------------
                | Catat login terakhir
                |--------------------------------------------------------------------------
                */

                $updateLoginStatement =
                    $pdo->prepare(
                        'UPDATE users
                         SET last_login_at = NOW()
                         WHERE id = :id'
                    );

                $updateLoginStatement->execute([
                    ':id' => (int) $user['id'],
                ]);

                /*
                |--------------------------------------------------------------------------
                | Buat session pengguna
                |--------------------------------------------------------------------------
                */

                session_regenerate_id(true);

                $_SESSION['user_id'] =
                    (int) $user['id'];

                $_SESSION['username'] =
                    (string) $user['username'];

                $_SESSION['email'] =
                    (string) $user['email'];

                $_SESSION['phone'] =
                    (string) $user['phone'];

                $_SESSION['payment_method'] =
                    (string) $user['payment_method'];

                $_SESSION['account_number'] =
                    (string) $user['account_number'];

                $_SESSION['account_name'] =
                    (string) $user['account_name'];

                $_SESSION['balance_local'] =
                    (float) $user['balance_local'];

                /*
                 * Kompatibel dengan index.php lama yang membaca
                 * $_SESSION['balance'].
                 */
                $_SESSION['balance'] =
                    (float) $user['balance_local'];

                $_SESSION['referral_balance'] =
                    (float) $user['referral_balance'];

                $_SESSION['referral_code'] =
                    (string) $user['referral_code'];

                $_SESSION['upline_id'] =
                    $user['upline_id'] !== null
                        ? (int) $user['upline_id']
                        : null;

                $_SESSION['login_time'] = time();

                unset(
                    $_SESSION['login_attempts'],
                    $_SESSION['login_locked_until']
                );

                $_SESSION['login_csrf'] =
                    bin2hex(random_bytes(32));

                header(
                    'Location: ' . $nextUrl
                );
                exit;
            }
        } catch (Throwable $exception) {
            error_log(
                'LOGIN ERROR: ' .
                $exception->getMessage()
            );

            $errors[] =
                'Login belum berhasil karena terjadi kesalahan pada server.';
        }
    }
}

/*
|--------------------------------------------------------------------------
| Header
|--------------------------------------------------------------------------
*/

require __DIR__ . '/includes/header.php';

?>

<style>
/*
|--------------------------------------------------------------------------
| Halaman login casino
|--------------------------------------------------------------------------
*/

.login-page {
    position: relative;

    width: 100%;
    min-height: calc(100vh - 70px);

    padding: 20px 10px 30px;

    overflow: hidden;

    background:
        radial-gradient(
            circle at 50% -8%,
            rgba(0, 145, 255, 0.28),
            transparent 270px
        ),
        radial-gradient(
            circle at -10% 48%,
            rgba(0, 105, 255, 0.15),
            transparent 190px
        ),
        radial-gradient(
            circle at 110% 55%,
            rgba(255, 179, 0, 0.11),
            transparent 190px
        ),
        linear-gradient(
            180deg,
            #031431 0%,
            #020a1d 58%,
            #010610 100%
        );
}

.login-page::before,
.login-page::after {
    position: absolute;

    width: 190px;
    height: 190px;

    content: "";

    border-radius: 50%;

    filter: blur(38px);

    pointer-events: none;
}

.login-page::before {
    top: 100px;
    left: -160px;

    background:
        rgba(0, 137, 255, 0.22);
}

.login-page::after {
    right: -165px;
    bottom: 120px;

    background:
        rgba(255, 178, 0, 0.13);
}

.login-shell {
    position: relative;
    z-index: 2;

    width: 100%;
    max-width: 480px;

    margin: 0 auto;
}

.login-heading {
    margin-bottom: 14px;

    text-align: center;
}

.login-crown {
    display: block;

    margin-bottom: -5px;

    color: #ffd554;

    font-size: 34px;
    line-height: 1;

    text-shadow:
        0 1px 0 #fff6ad,
        0 3px 0 #743900,
        0 0 12px rgba(255, 196, 41, 0.68);
}

.login-heading h1 {
    margin: 0;

    color: #ffd451;

    background:
        linear-gradient(
            180deg,
            #fff9ba 0%,
            #ffd650 36%,
            #e99000 72%,
            #fff09a 100%
        );

    background-clip: text;
    -webkit-background-clip: text;

    font-size: clamp(26px, 8vw, 38px);
    font-weight: 1000;

    letter-spacing: -0.04em;

    -webkit-text-fill-color: transparent;

    filter:
        drop-shadow(0 2px 0 #703800)
        drop-shadow(0 5px 6px rgba(0, 0, 0, 0.75));
}

.login-heading p {
    margin: 7px 0 0;

    color: #94a9c5;

    font-size: 9px;
    line-height: 1.5;
}

.login-ornament {
    display: flex;

    align-items: center;
    justify-content: center;

    margin: 10px auto 0;

    gap: 7px;

    color: #ffd24c;
}

.login-ornament::before,
.login-ornament::after {
    width: 55px;
    height: 1px;

    content: "";

    background:
        linear-gradient(
            90deg,
            transparent,
            rgba(255, 196, 42, 0.70)
        );
}

.login-ornament::after {
    transform: scaleX(-1);
}

.login-ornament span {
    font-size: 12px;

    text-shadow:
        0 0 7px rgba(255, 193, 37, 0.65);
}

.login-card {
    position: relative;

    padding: 16px 14px 15px;

    overflow: hidden;

    border:
        1px solid rgba(255, 196, 42, 0.36);

    border-radius: 17px;

    background:
        radial-gradient(
            circle at 50% 0,
            rgba(255, 180, 0, 0.10),
            transparent 150px
        ),
        linear-gradient(
            180deg,
            rgba(8, 31, 67, 0.98),
            rgba(2, 12, 29, 0.99)
        );

    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.09),
        0 0 11px rgba(0, 121, 255, 0.20),
        0 12px 28px rgba(0, 0, 0, 0.42);
}

.login-card::before {
    position: absolute;

    top: 0;
    right: 20px;
    left: 20px;

    height: 1px;

    content: "";

    background:
        linear-gradient(
            90deg,
            transparent,
            rgba(255, 244, 170, 0.90),
            transparent
        );
}

.login-alert {
    margin-bottom: 11px;
    padding: 9px 10px;

    border-radius: 10px;

    font-size: 8px;
    line-height: 1.5;
}

.login-alert--error {
    border:
        1px solid rgba(255, 77, 77, 0.42);

    color: #ffd8d8;

    background:
        rgba(111, 12, 18, 0.46);
}

.login-alert--error ul {
    margin: 0;
    padding-left: 16px;
}

.login-alert--success {
    border:
        1px solid rgba(73, 232, 152, 0.36);

    color: #c9ffe0;

    background:
        rgba(5, 75, 45, 0.45);
}

.login-section-title {
    display: flex;

    align-items: center;
    justify-content: center;

    margin:
        1px
        0
        12px;

    gap: 7px;

    color: #ffd350;

    font-size: 10px;
    font-weight: 1000;

    letter-spacing: 0.05em;

    text-transform: uppercase;
}

.login-section-title::before,
.login-section-title::after {
    height: 1px;

    flex: 1;

    content: "";

    background:
        linear-gradient(
            90deg,
            transparent,
            rgba(255, 196, 41, 0.56)
        );
}

.login-section-title::after {
    transform: scaleX(-1);
}

.login-field {
    display: grid;

    margin-bottom: 10px;

    gap: 5px;
}

.login-field label {
    color: #afc0d5;

    font-size: 8px;
    font-weight: 850;
}

.login-required {
    color: #ffd04a;
}

.login-control {
    position: relative;
}

.login-control input {
    display: block;

    width: 100%;
    min-height: 44px;

    padding:
        0
        12px;

    border:
        1px solid rgba(0, 158, 255, 0.35);

    border-radius: 10px;

    outline: none;

    color: #ffffff;

    background:
        linear-gradient(
            180deg,
            rgba(3, 19, 44, 0.97),
            rgba(1, 9, 23, 0.99)
        );

    font-family: inherit;
    font-size: 11px;

    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.05),
        inset 0 -2px 5px rgba(0, 0, 0, 0.32);

    transition:
        border-color 160ms ease,
        box-shadow 160ms ease;
}

.login-control input::placeholder {
    color: #536a87;
}

.login-control input:focus {
    border-color: #ffc83f;

    box-shadow:
        0 0 0 2px rgba(255, 192, 38, 0.10),
        0 0 9px rgba(255, 185, 25, 0.31);
}

.login-control--password input {
    padding-right: 44px;
}

.login-password-toggle {
    position: absolute;

    top: 50%;
    right: 8px;

    display: grid;

    width: 29px;
    height: 29px;

    place-items: center;

    padding: 0;

    border: 0;

    border-radius: 7px;

    color: #7dd2ff;
    background: transparent;

    font-size: 14px;

    transform: translateY(-50%);

    cursor: pointer;
}

.login-options {
    display: flex;

    align-items: center;
    justify-content: flex-end;

    margin-top: -2px;

    gap: 8px;
}

.login-options a {
    color: #7dcfff;

    font-size: 8px;
    font-weight: 800;

    text-decoration: none;
}

.login-options a:hover {
    color: #ffd34c;
}

.login-submit {
    display: flex;

    width: 100%;
    min-height: 47px;

    align-items: center;
    justify-content: center;

    margin-top: 13px;

    border:
        1px solid #ffe185;

    border-radius: 11px;

    color: #321900;

    background:
        linear-gradient(
            180deg,
            #fff294 0%,
            #ffc630 46%,
            #d87b00 100%
        );

    font-family: inherit;
    font-size: 12px;
    font-weight: 1000;

    letter-spacing: 0.04em;

    box-shadow:
        inset 0 2px 0 rgba(255, 255, 255, 0.66),
        inset 0 -3px 4px rgba(112, 47, 0, 0.46),
        0 0 11px rgba(255, 183, 20, 0.35),
        0 5px 0 #5a2b00;

    cursor: pointer;
}

.login-submit:hover {
    filter: brightness(1.07);
}

.login-submit:active {
    transform: translateY(3px);

    box-shadow:
        inset 0 2px 5px rgba(83, 32, 0, 0.42),
        0 2px 0 #5a2b00;
}

.login-divider {
    display: flex;

    align-items: center;

    margin: 17px 0 12px;

    gap: 8px;

    color: #617793;

    font-size: 7px;
    font-weight: 800;
}

.login-divider::before,
.login-divider::after {
    height: 1px;

    flex: 1;

    content: "";

    background:
        rgba(255, 255, 255, 0.08);
}

.login-register-link {
    display: flex;

    min-height: 41px;

    align-items: center;
    justify-content: center;

    border:
        1px solid rgba(0, 165, 255, 0.38);

    border-radius: 10px;

    color: #ffffff;

    background:
        linear-gradient(
            180deg,
            rgba(9, 55, 104, 0.91),
            rgba(3, 25, 56, 0.98)
        );

    font-size: 9px;
    font-weight: 900;

    text-decoration: none;

    box-shadow:
        inset 0 1px 0 rgba(255, 255, 255, 0.09),
        0 0 8px rgba(0, 135, 255, 0.14);
}

.login-register-link strong {
    margin-left: 4px;

    color: #ffd14a;
}

.login-security {
    display: grid;

    margin-top: 12px;
    padding: 9px;

    grid-template-columns:
        29px
        minmax(0, 1fr);

    align-items: center;

    gap: 8px;

    border:
        1px solid rgba(61, 225, 146, 0.22);

    border-radius: 10px;

    background:
        linear-gradient(
            180deg,
            rgba(5, 55, 37, 0.55),
            rgba(2, 29, 20, 0.72)
        );
}

.login-security > span {
    display: grid;

    width: 29px;
    height: 29px;

    place-items: center;

    border-radius: 50%;

    color: #052819;
    background:
        linear-gradient(
            180deg,
            #76efaf,
            #3bd989
        );

    font-size: 12px;
    font-weight: 1000;
}

.login-security strong {
    display: block;

    color: #ffffff;

    font-size: 8px;
}

.login-security small {
    display: block;

    margin-top: 2px;

    color: #8fb8a4;

    font-size: 6px;
    line-height: 1.45;
}

@media (max-width: 390px) {
    .login-page {
        padding:
            15px
            8px
            25px;
    }

    .login-card {
        padding:
            14px
            11px;
    }

    .login-control input {
        min-height: 42px;

        font-size: 10px;
    }
}
</style>

<section class="login-page">
    <div class="login-shell">

        <header class="login-heading">
            <span
                class="login-crown"
                aria-hidden="true"
            >
                ♛
            </span>

            <h1>
                LOGIN MEMBER
            </h1>

            <p>
                Masuk untuk mengakses akun, saldo lokal,
                deposit, dan seluruh permainan.
            </p>

            <div
                class="login-ornament"
                aria-hidden="true"
            >
                <span>♠</span>
                <span>◆</span>
                <span>♥</span>
            </div>
        </header>

        <div class="login-card">

            <?php if ($registeredMessage): ?>

                <div class="login-alert login-alert--success">
                    Pendaftaran berhasil. Silakan login menggunakan
                    username atau email yang sudah didaftarkan.
                </div>

            <?php endif; ?>

            <?php if (!empty($errors)): ?>

                <div class="login-alert login-alert--error">
                    <ul>
                        <?php foreach ($errors as $error): ?>
                            <li><?= e($error); ?></li>
                        <?php endforeach; ?>
                    </ul>
                </div>

            <?php endif; ?>

            <div class="login-section-title">
                Akses Akun
            </div>

            <form
                method="post"
                action="login.php<?= $nextUrl !== 'index.php'
                    ? '?next=' . rawurlencode($nextUrl)
                    : ''; ?>"
                autocomplete="off"
            >
                <input
                    type="hidden"
                    name="csrf_token"
                    value="<?= e($csrfToken); ?>"
                >

                <input
                    type="hidden"
                    name="next"
                    value="<?= e($nextUrl); ?>"
                >

                <div class="login-field">
                    <label for="loginIdentity">
                        Username atau Email
                        <span class="login-required">*</span>
                    </label>

                    <div class="login-control">
                        <input
                            id="loginIdentity"
                            name="login"
                            type="text"
                            value="<?= e($formLogin); ?>"
                            placeholder="Masukkan username atau email"
                            maxlength="191"
                            autocomplete="username"
                            autofocus
                            required
                        >
                    </div>
                </div>

                <div class="login-field">
                    <label for="loginPassword">
                        Password
                        <span class="login-required">*</span>
                    </label>

                    <div class="login-control login-control--password">
                        <input
                            id="loginPassword"
                            name="password"
                            type="password"
                            placeholder="Masukkan password"
                            autocomplete="current-password"
                            required
                        >

                        <button
                            id="loginPasswordToggle"
                            class="login-password-toggle"
                            type="button"
                            aria-label="Tampilkan password"
                        >
                            ◉
                        </button>
                    </div>
                </div>

                <div class="login-options">
                    <a href="forgot-password.php">
                        Lupa password?
                    </a>
                </div>

                <button
                    class="login-submit"
                    type="submit"
                    <?= $loginLockedUntil > time()
                        ? 'disabled'
                        : ''; ?>
                >
                    MASUK SEKARANG
                </button>
            </form>

            <div class="login-divider">
                BELUM MEMILIKI AKUN?
            </div>

            <a
                class="login-register-link"
                href="register.php"
            >
                Daftar akun baru
                <strong>
                    GRATIS
                </strong>
            </a>

            <div class="login-security">
                <span>
                    ✓
                </span>

                <div>
                    <strong>
                        Login terenkripsi dan terlindungi
                    </strong>

                    <small>
                        Jangan pernah membagikan password atau kode
                        verifikasi kepada pihak lain.
                    </small>
                </div>
            </div>

        </div>
    </div>
</section>

<script>
(function () {
    'use strict';

    var passwordInput =
        document.getElementById('loginPassword');

    var toggleButton =
        document.getElementById('loginPasswordToggle');

    if (!passwordInput || !toggleButton) {
        return;
    }

    toggleButton.addEventListener(
        'click',
        function () {
            var willShow =
                passwordInput.type === 'password';

            passwordInput.type =
                willShow
                    ? 'text'
                    : 'password';

            toggleButton.textContent =
                willShow
                    ? '◌'
                    : '◉';

            toggleButton.setAttribute(
                'aria-label',
                willShow
                    ? 'Sembunyikan password'
                    : 'Tampilkan password'
            );
        }
    );
})();
</script>

<?php require __DIR__ . '/includes/footer.php'; ?>
