<?php
declare(strict_types=1);

$bootstrapFile = __DIR__ . '/bootstrap.php';
if (is_file($bootstrapFile)) {
    require_once $bootstrapFile;
}

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


/* Sticky referral: tersimpan sampai link referral berbeda dibuka. */
require_once __DIR__ . '/includes/referral_sticky.php';
$stickyReferralCode = stickyReferralCurrent();

/*
|--------------------------------------------------------------------------
| Pengguna yang sudah login tidak boleh membuka halaman register
|--------------------------------------------------------------------------
*/

if (!empty($_SESSION['user_id'])) {
    header('Location: account.php');
    exit;
}

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

$siteName = isset($siteName) ? (string) $siteName : 'Platform Online';
$pageTitle = 'Daftar Akun';
$activeMenu = '';
$isLoggedIn = !empty($_SESSION['user_id']);

$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);

$paymentMethods = [
    'QRIS', 'BCA', 'BRI', 'BNI', 'SEABANK', 'MANDIRI', 'CIMB',
    'SINARMAS', 'BTN', 'DANAMON', 'OCBC', 'KROM BANK', 'BANK JAGO',
    'MAYBANK', 'PERMATA', 'JENIUS', 'MEGA', 'BJB', 'NOBU BANK',
    'ALLOBANK', 'DANA', 'GOPAY', 'OVO', 'SHOPEEPAY', 'SAKUKU',
    'LINKAJA', 'DOKU',
];

function makeReferralCode(PDO $pdo, string $username): string
{
    $prefix = strtoupper(preg_replace('/[^A-Z0-9]/i', '', $username));
    $prefix = substr($prefix, 0, 4);
    if ($prefix === '') {
        $prefix = 'USER';
    }

    for ($attempt = 0; $attempt < 30; $attempt++) {
        $code = 'R8' . $prefix . strtoupper(bin2hex(random_bytes(3)));

        $stmt = $pdo->prepare(
            'SELECT id FROM users WHERE referral_code = :code LIMIT 1'
        );
        $stmt->execute([':code' => $code]);

        if (!$stmt->fetch()) {
            return $code;
        }
    }

    throw new RuntimeException('Gagal membuat kode referral unik.');
}

if (empty($_SESSION['register_csrf'])) {
    $_SESSION['register_csrf'] = bin2hex(random_bytes(32));
}
$csrfToken = (string) $_SESSION['register_csrf'];

$form = [
    'username' => '',
    'email' => '',
    'phone' => '',
    'payment_method' => '',
    'account_number' => '',
    'account_name' => '',
    'referral' => $stickyReferralCode,
];

$errors = [];
$successData = null;

if (!empty($_SESSION['register_success'])) {
    $successData = $_SESSION['register_success'];
    unset($_SESSION['register_success']);
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $form['username'] = trim((string) ($_POST['username'] ?? ''));
    $form['email'] = strtolower(trim((string) ($_POST['email'] ?? '')));
    $form['phone'] = preg_replace('/[^0-9]/', '', (string) ($_POST['phone'] ?? ''));
    $form['payment_method'] = strtoupper(trim((string) ($_POST['payment_method'] ?? '')));
    $form['account_number'] = preg_replace('/[^0-9]/', '', (string) ($_POST['account_number'] ?? ''));
    $form['account_name'] = trim((string) ($_POST['account_name'] ?? ''));
    $postedReferral = stickyReferralNormalize($_POST['referral'] ?? '');
    $form['referral'] = $stickyReferralCode !== ''
        ? $stickyReferralCode
        : $postedReferral;

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

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

    if (!preg_match('/^[A-Za-z0-9_]{4,20}$/', $form['username'])) {
        $errors[] = 'Username harus 4–20 karakter: huruf, angka, atau garis bawah.';
    }

    if (!filter_var($form['email'], FILTER_VALIDATE_EMAIL)) {
        $errors[] = 'Alamat email tidak valid.';
    }

    if (strlen($form['phone']) < 9 || strlen($form['phone']) > 16) {
        $errors[] = 'Nomor handphone harus 9–16 digit.';
    }

    if (strlen($password) < 8) {
        $errors[] = 'Password minimal 8 karakter.';
    }

    if ($password !== $passwordConfirmation) {
        $errors[] = 'Konfirmasi password tidak sama.';
    }

    if (!in_array($form['payment_method'], $paymentMethods, true)) {
        $errors[] = 'Pilih bank atau e-wallet yang tersedia.';
    }

    if (strlen($form['account_number']) < 5 || strlen($form['account_number']) > 30) {
        $errors[] = 'Nomor rekening harus 5–30 digit.';
    }

    if (mb_strlen($form['account_name']) < 3 || mb_strlen($form['account_name']) > 100) {
        $errors[] = 'Nama rekening harus 3–100 karakter.';
    }

    if ($form['referral'] !== '' && !preg_match('/^[A-Z0-9]{6,20}$/', $form['referral'])) {
        $errors[] = 'Format kode referral tidak valid.';
    }

    if (empty($errors)) {
        try {
            $pdo->beginTransaction();

            $dupStmt = $pdo->prepare(
                'SELECT username, email, phone
                 FROM users
                 WHERE username = :username
                    OR email = :email
                    OR phone = :phone
                 LIMIT 1'
            );
            $dupStmt->execute([
                ':username' => $form['username'],
                ':email' => $form['email'],
                ':phone' => $form['phone'],
            ]);
            $duplicate = $dupStmt->fetch();

            if ($duplicate) {
                if (strcasecmp((string) $duplicate['username'], $form['username']) === 0) {
                    $errors[] = 'Username sudah digunakan.';
                }
                if (strtolower((string) $duplicate['email']) === $form['email']) {
                    $errors[] = 'Email sudah digunakan.';
                }
                if ((string) $duplicate['phone'] === $form['phone']) {
                    $errors[] = 'Nomor handphone sudah digunakan.';
                }
            }

            $accountStmt = $pdo->prepare(
                'SELECT id
                 FROM users
                 WHERE payment_method = :method
                   AND account_number = :number
                 LIMIT 1'
            );
            $accountStmt->execute([
                ':method' => $form['payment_method'],
                ':number' => $form['account_number'],
            ]);

            if ($accountStmt->fetch()) {
                $errors[] = 'Nomor rekening tersebut sudah terdaftar.';
            }

            $uplineId = null;
            $referredByCode = null;

            if (empty($errors) && $form['referral'] !== '') {
                $uplineStmt = $pdo->prepare(
                    'SELECT id, referral_code
                     FROM users
                     WHERE referral_code = :code
                       AND status = :status
                     LIMIT 1'
                );
                $uplineStmt->execute([
                    ':code' => $form['referral'],
                    ':status' => 'ACTIVE',
                ]);
                $upline = $uplineStmt->fetch();

                if (!$upline) {
                    $errors[] = 'Kode referral tidak ditemukan atau upline tidak aktif.';
                } else {
                    $uplineId = (int) $upline['id'];
                    $referredByCode = (string) $upline['referral_code'];
                }
            }

            if (!empty($errors)) {
                $pdo->rollBack();
            } else {
                $referralCode = makeReferralCode($pdo, $form['username']);
                $passwordHash = password_hash($password, PASSWORD_DEFAULT);

                if ($passwordHash === false) {
                    throw new RuntimeException('Gagal mengenkripsi password.');
                }

                $insertStmt = $pdo->prepare(
                    'INSERT INTO users
                    (
                        username, password_hash, email, phone,
                        payment_method, account_number, account_name,
                        balance_local, referral_balance,
                        referral_code, upline_id, referred_by_code,
                        status, created_at, updated_at
                    )
                    VALUES
                    (
                        :username, :password_hash, :email, :phone,
                        :payment_method, :account_number, :account_name,
                        0.00, 0.00,
                        :referral_code, :upline_id, :referred_by_code,
                        :status, NOW(), NOW()
                    )'
                );
                $insertStmt->execute([
                    ':username' => $form['username'],
                    ':password_hash' => $passwordHash,
                    ':email' => $form['email'],
                    ':phone' => $form['phone'],
                    ':payment_method' => $form['payment_method'],
                    ':account_number' => $form['account_number'],
                    ':account_name' => $form['account_name'],
                    ':referral_code' => $referralCode,
                    ':upline_id' => $uplineId,
                    ':referred_by_code' => $referredByCode,
                    ':status' => 'ACTIVE',
                ]);

                $newUserId = (int) $pdo->lastInsertId();
                $pdo->commit();

                $_SESSION['register_success'] = [
                    'user_id' => $newUserId,
                    'username' => $form['username'],
                    'referral_code' => $referralCode,
                ];
                $_SESSION['register_csrf'] = bin2hex(random_bytes(32));

                header('Location: register.php?registered=1');
                exit;
            }
        } catch (Throwable $exception) {
            if ($pdo->inTransaction()) {
                $pdo->rollBack();
            }

            error_log('REGISTER ERROR: ' . $exception->getMessage());
            $errors[] = 'Pendaftaran gagal karena terjadi kesalahan pada server.';
        }
    }
}

$referralUrl = '';
if (is_array($successData) && !empty($successData['referral_code'])) {
    $scheme = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off')
        ? 'https'
        : 'http';
    $host = (string) ($_SERVER['HTTP_HOST'] ?? '');
    $directory = rtrim(
        str_replace('\\', '/', dirname((string) ($_SERVER['SCRIPT_NAME'] ?? '/'))),
        '/'
    );

    $referralUrl = $scheme . '://' . $host . $directory .
        '/register.php?ref=' .
        rawurlencode((string) $successData['referral_code']);
}

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

<style>
.register-page{
    min-height:calc(100vh - 70px);padding:14px 9px 25px;position:relative;
    background:
      radial-gradient(circle at 50% 0,rgba(0,137,255,.23),transparent 270px),
      radial-gradient(circle at 105% 45%,rgba(255,174,0,.10),transparent 190px),
      linear-gradient(180deg,#03132f,#020a1b 58%,#010611);
}
.register-shell{width:100%;max-width:540px;margin:auto;position:relative;z-index:2}
.register-heading{text-align:center;margin-bottom:10px}
.register-crown{display:block;color:#ffd451;font-size:29px;line-height:1;text-shadow:0 1px #fff3a2,0 3px #713700,0 0 10px rgba(255,192,35,.7)}
.register-heading h1{margin:0;color:#ffd451;font-size:clamp(23px,7vw,34px);font-weight:1000;text-shadow:0 2px #713700,0 5px 7px #000}
.register-heading p{margin:5px 0 0;color:#91a7c2;font-size:9px}
.register-card{padding:12px;border:1px solid rgba(255,194,38,.33);border-radius:15px;background:linear-gradient(180deg,rgba(8,31,67,.97),rgba(2,12,29,.99));box-shadow:inset 0 1px rgba(255,255,255,.08),0 0 11px rgba(0,123,255,.16),0 10px 25px rgba(0,0,0,.4)}
.register-title{display:flex;align-items:center;gap:7px;margin:2px 0 8px;color:#ffd353;font-size:10px;font-weight:1000;text-transform:uppercase}
.register-title:before,.register-title:after{content:"";height:1px;flex:1;background:linear-gradient(90deg,transparent,rgba(255,197,46,.56))}
.register-title:after{transform:scaleX(-1)}
.register-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}
.register-field{display:grid;gap:4px;min-width:0}
.register-field.full{grid-column:1/-1}
.register-field label{color:#b2c1d4;font-size:8px;font-weight:850}
.required{color:#ffcf48}
.register-control{position:relative}
.register-control input,.register-control select{
    width:100%;min-height:41px;padding:0 11px;border:1px solid rgba(0,157,255,.34);
    border-radius:9px;outline:none;color:#fff;background:linear-gradient(180deg,#03132e,#010a19);
    font-family:inherit;font-size:11px;box-shadow:inset 0 1px rgba(255,255,255,.05);
}
.register-control input:focus,.register-control select:focus{border-color:#ffc83f;box-shadow:0 0 0 2px rgba(255,192,39,.1),0 0 8px rgba(255,186,25,.3)}
.register-control input::placeholder{color:#536985}
.register-control select{appearance:none;padding-right:34px}
.register-control select option{color:#111;background:#fff}
.select-arrow{position:absolute;right:11px;top:50%;transform:translateY(-50%);color:#ffc947;font-size:10px;pointer-events:none}
.password-control input{padding-right:40px}
.password-toggle{position:absolute;right:7px;top:50%;transform:translateY(-50%);width:29px;height:29px;border:0;border-radius:7px;background:transparent;color:#80cfff;cursor:pointer}
.register-hint{color:#647b98;font-size:7px;line-height:1.4}
.register-divider{height:1px;margin:12px 0;background:linear-gradient(90deg,transparent,rgba(255,255,255,.11),transparent)}
.register-alert{margin-bottom:10px;padding:9px 10px;border:1px solid rgba(255,73,73,.4);border-radius:9px;color:#ffd4d4;background:rgba(104,10,16,.47);font-size:8px;line-height:1.5}
.register-alert ul{margin:0;padding-left:16px}
.register-submit{width:100%;min-height:46px;margin-top:12px;border:1px solid #ffe182;border-radius:10px;color:#321900;background:linear-gradient(180deg,#fff08c,#ffc431 45%,#d87900);font-family:inherit;font-size:12px;font-weight:1000;box-shadow:inset 0 2px rgba(255,255,255,.62),0 5px #5b2c00;cursor:pointer}
.register-submit:active{transform:translateY(3px);box-shadow:0 2px #5b2c00}
.register-login{text-align:center;margin:13px 0 0;color:#8398b3;font-size:8px}
.register-login a{color:#ffd14a;font-weight:900}
.register-success{padding:15px;border:1px solid rgba(76,231,151,.36);border-radius:13px;text-align:center;background:linear-gradient(180deg,rgba(6,68,43,.88),rgba(2,29,20,.96))}
.success-icon{display:grid;place-items:center;width:46px;height:46px;margin:0 auto 8px;border:2px solid #72f1b1;border-radius:50%;color:#032b17;background:#5ee6a2;font-size:24px;font-weight:1000}
.register-success h2{margin:0;color:#fff;font-size:18px}
.register-success p{margin:6px 0 0;color:#a9d9c3;font-size:9px}
.referral-box{margin-top:11px;padding:9px;border:1px dashed rgba(255,203,76,.48);border-radius:10px;background:rgba(28,20,2,.38)}
.referral-box small{display:block;color:#a89972;font-size:7px}
.referral-code{display:block;margin-top:3px;color:#ffd04a;font-size:16px;font-weight:1000;letter-spacing:.06em}
.referral-copy{display:flex;gap:5px;margin-top:8px}
.referral-copy input{width:100%;min-width:0;height:34px;padding:0 8px;border:1px solid rgba(255,255,255,.1);border-radius:7px;color:#b6c7d9;background:#031328;font-size:7px}
.referral-copy button{padding:0 10px;border:1px solid #ffc83d;border-radius:7px;color:#281500;background:linear-gradient(180deg,#ffe27a,#f5ac15);font-size:8px;font-weight:1000;cursor:pointer}
@media(max-width:390px){.register-card{padding:10px}.register-grid{gap:7px}.register-control input,.register-control select{min-height:39px;font-size:10px}}
@media(max-width:340px){.register-grid{grid-template-columns:1fr}.register-field.full{grid-column:auto}}
</style>

<section class="register-page">
<div class="register-shell">
<header class="register-heading">
    <span class="register-crown">♛</span>
    <h1>DAFTAR AKUN</h1>
    <p>Buat akun baru dan dapatkan kode referral pribadi Anda.</p>
</header>

<div class="register-card">
<?php if ($successData): ?>
    <section class="register-success">
        <span class="success-icon">✓</span>
        <h2>Pendaftaran Berhasil</h2>
        <p>
            Akun <strong><?= e($successData['username'] ?? 'Member'); ?></strong>
            sudah dibuat.
        </p>

        <div class="referral-box">
            <small>KODE REFERRAL ANDA</small>
            <strong class="referral-code">
                <?= e($successData['referral_code'] ?? ''); ?>
            </strong>

            <?php if ($referralUrl !== ''): ?>
                <div class="referral-copy">
                    <input id="referralUrl" type="text" value="<?= e($referralUrl); ?>" readonly>
                    <button type="button" onclick="copyReferralUrl()">SALIN</button>
                </div>
            <?php endif; ?>
        </div>

        <p class="register-login">
            Lanjut ke <a href="login.php">halaman login</a>.
        </p>
    </section>
<?php else: ?>

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

    <form method="post" action="register.php" autocomplete="off">
        <input type="hidden" name="csrf_token" value="<?= e($csrfToken); ?>">

        <div class="register-title">Informasi Akun</div>
        <div class="register-grid">
            <div class="register-field">
                <label for="username">Username <span class="required">*</span></label>
                <div class="register-control">
                    <input id="username" name="username" type="text"
                           value="<?= e($form['username']); ?>"
                           placeholder="Contoh: member123" maxlength="20"
                           autocomplete="username" required>
                </div>
                <small class="register-hint">Huruf, angka, atau garis bawah.</small>
            </div>

            <div class="register-field">
                <label for="email">Email <span class="required">*</span></label>
                <div class="register-control">
                    <input id="email" name="email" type="email"
                           value="<?= e($form['email']); ?>"
                           placeholder="nama@email.com" maxlength="191"
                           autocomplete="email" required>
                </div>
            </div>

            <div class="register-field">
                <label for="password">Password <span class="required">*</span></label>
                <div class="register-control password-control">
                    <input id="password" name="password" type="password"
                           placeholder="Minimal 8 karakter" minlength="8"
                           autocomplete="new-password" required>
                    <button class="password-toggle" type="button"
                            data-target="password" aria-label="Tampilkan password">◉</button>
                </div>
            </div>

            <div class="register-field">
                <label for="password_confirmation">
                    Konfirmasi Password <span class="required">*</span>
                </label>
                <div class="register-control password-control">
                    <input id="password_confirmation" name="password_confirmation"
                           type="password" placeholder="Ulangi password"
                           minlength="8" autocomplete="new-password" required>
                    <button class="password-toggle" type="button"
                            data-target="password_confirmation"
                            aria-label="Tampilkan password">◉</button>
                </div>
            </div>

            <div class="register-field full">
                <label for="phone">Nomor Handphone <span class="required">*</span></label>
                <div class="register-control">
                    <input id="phone" name="phone" type="tel" inputmode="numeric"
                           value="<?= e($form['phone']); ?>"
                           placeholder="Contoh: 081234567890"
                           maxlength="20" autocomplete="tel" required>
                </div>
            </div>
        </div>

        <div class="register-divider"></div>
        <div class="register-title">Rekening Penarikan</div>

        <div class="register-grid">
            <div class="register-field">
                <label for="payment_method">
                    Bank / E-Wallet <span class="required">*</span>
                </label>
                <div class="register-control">
                    <select id="payment_method" name="payment_method" required>
                        <option value="">Pilih metode</option>
                        <?php foreach ($paymentMethods as $method): ?>
                            <option value="<?= e($method); ?>"
                                <?= $form['payment_method'] === $method ? 'selected' : ''; ?>>
                                <?= e($method); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    <span class="select-arrow">▼</span>
                </div>
            </div>

            <div class="register-field">
                <label for="account_number">
                    Nomor Rekening <span class="required">*</span>
                </label>
                <div class="register-control">
                    <input id="account_number" name="account_number"
                           type="text" inputmode="numeric"
                           value="<?= e($form['account_number']); ?>"
                           placeholder="Nomor bank/e-wallet"
                           maxlength="30" required>
                </div>
            </div>

            <div class="register-field full">
                <label for="account_name">
                    Nama Rekening <span class="required">*</span>
                </label>
                <div class="register-control">
                    <input id="account_name" name="account_name" type="text"
                           value="<?= e($form['account_name']); ?>"
                           placeholder="Nama sesuai rekening"
                           maxlength="100" required>
                </div>
            </div>
        </div>

        <div class="register-divider"></div>
        <div class="register-title">Referral</div>

        <div class="register-grid">
            <div class="register-field full">
                <label for="referral">Kode Referral Upline</label>
                <div class="register-control">
                    <input id="referral" name="referral" type="text"
                           value="<?= e($form['referral']); ?>"
                           placeholder="Kosongkan jika tidak memiliki referral"
                           maxlength="20" autocomplete="off"
                           <?= $stickyReferralCode !== '' ? 'readonly' : ''; ?>>
                </div>
                <small class="register-hint">
                    <?php if ($stickyReferralCode !== ''): ?>
                        Kode referral tersimpan dari link yang Anda buka dan hanya berubah saat link referral berbeda dibuka.
                    <?php else: ?>
                        Setelah mendaftar, Anda mendapat kode referral sendiri untuk mengundang downline.
                    <?php endif; ?>
                </small>
            </div>
        </div>

        <button class="register-submit" type="submit">DAFTAR SEKARANG</button>

        <p class="register-login">
            Sudah memiliki akun? <a href="login.php">Login di sini</a>
        </p>
    </form>
<?php endif; ?>
</div>
</div>
</section>

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

    var buttons = document.querySelectorAll('[data-target]');

    Array.prototype.forEach.call(buttons, function (button) {
        button.addEventListener('click', function () {
            var input = document.getElementById(button.getAttribute('data-target'));
            if (!input) {
                return;
            }

            var show = input.type === 'password';
            input.type = show ? 'text' : 'password';
            button.textContent = show ? '◌' : '◉';
        });
    });
})();

function copyReferralUrl() {
    var input = document.getElementById('referralUrl');
    if (!input) {
        return;
    }

    input.select();
    input.setSelectionRange(0, 99999);

    if (navigator.clipboard && window.isSecureContext) {
        navigator.clipboard.writeText(input.value);
    } else {
        document.execCommand('copy');
    }
}
</script>

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