<?php
// public/register.php
declare(strict_types=1);

require_once dirname(__DIR__) . '/_session.php';

$projectRoot = dirname(__DIR__);

require_once $projectRoot . '/inc/i18n.php';
require_once $projectRoot . '/db.php';
require_once $projectRoot . '/inc/i18n_helpers.php';
require_once $projectRoot . '/lib/legal_texts.php';

$configPath = $projectRoot . '/config.php';
$config = [];
if (is_file($configPath)) {
    $cfg = require $configPath;
    if (is_array($cfg)) {
        $config = $cfg;
    }
}

function mhk_normalize_base_url(?string $base): string {
    $base = trim((string)$base);
    if ($base === '' || $base === '/') {
        return '';
    }
    return '/' . trim($base, '/');
}

function mhk_url(string $path = ''): string {
    global $base;
    $path = ltrim($path, '/');
    return ($base === '' ? '' : $base) . '/' . $path;
}

function clean_input(string $value): string {
    return trim($value);
}

function norm_phone_variants(string $phoneLocal): array {
    $digits = preg_replace('/\D+/', '', $phoneLocal);

    if ($digits === '') {
        return [null, null];
    }

    if (strlen($digits) === 8) {
        return ['+993' . $digits, $digits];
    }

    if (strlen($digits) === 11 && substr($digits, 0, 3) === '993') {
        return ['+' . $digits, $digits];
    }

    return [$phoneLocal, $phoneLocal];
}

$base = mhk_normalize_base_url($config['base_url'] ?? '');
$lang = me_get_lang();
$legalTexts = mhk_legal_texts($lang);
$legalRequiredError = trim((string)($legalTexts['required_error'] ?? ''));
if ($legalRequiredError === '') {
    $legalRequiredError = __('page.registration.legal.required');
}

if (!isset($pdo) || !($pdo instanceof PDO)) {
    http_response_code(500);
    echo htmlspecialchars(__('common.error'), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
    exit;
}

if (!empty($_SESSION['user']['id'])) {
    header('Location: ' . mhk_url('index.php'));
    exit;
}

$errors = [];
$name = '';
$phone_local = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name = isset($_POST['name']) ? clean_input((string)$_POST['name']) : '';
    $phone_local = isset($_POST['phone_local'])
        ? preg_replace('/\D/', '', (string)$_POST['phone_local'])
        : '';
    $password = isset($_POST['password']) ? (string)$_POST['password'] : '';
    $password_confirm = isset($_POST['password_confirm']) ? (string)$_POST['password_confirm'] : '';
$legal_accept = isset($_POST['legal_accept']) && (string)$_POST['legal_accept'] === '1';

    if ($name === '') {
        $errors[] = __('page.registration.error.name_required');
    }

    if ($phone_local === '') {
        $errors[] = __('page.registration.error.phone_required');
    } elseif (!preg_match('/^\d{8}$/', $phone_local)) {
        $errors[] = __('page.registration.error.phone_invalid');
    }

    if ($password === '') {
        $errors[] = __('page.registration.error.password_required');
    }

if ($password !== $password_confirm) {
    $errors[] = __('page.registration.error.password_mismatch');
}

if (!$legal_accept) {
    $errors[] = $legalRequiredError;
}

    if (empty($errors)) {
        [$phoneNorm, $phoneAlt] = norm_phone_variants($phone_local);

        $stmt = $pdo->prepare("
            SELECT id
            FROM users
            WHERE phone = :phone1 OR phone = :phone2
            LIMIT 1
        ");
        $stmt->execute([
            ':phone1' => $phoneNorm,
            ':phone2' => $phoneAlt,
        ]);

        if ($stmt->fetch(PDO::FETCH_ASSOC)) {
            $errors[] = __('page.registration.error.phone_exists');
        } else {
            $verifyCode = random_int(100000, 999999);
            $status = 'pending';
            $passwordHash = password_hash($password, PASSWORD_BCRYPT);
            $ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';

            $insert = $pdo->prepare("
                INSERT INTO users (
                    name,
                    phone,
                    ip,
                    password_hash,
                    role,
                    created_at,
                    verify_code,
                    status
                ) VALUES (
                    :name,
                    :phone,
                    :ip,
                    :password_hash,
                    :role,
                    NOW(),
                    :verify_code,
                    :status
                )
            ");

            $insert->execute([
                ':name'          => $name,
                ':phone'         => $phoneNorm,
                ':ip'            => $ip,
                ':password_hash' => $passwordHash,
                ':role'          => 'user',
                ':verify_code'   => (string)$verifyCode,
                ':status'        => $status,
            ]);

            $userId = (int)$pdo->lastInsertId();

            $stmt = $pdo->prepare("
                SELECT
                    id,
                    name,
                    phone,
                    role,
                    created_at,
                    verify_code,
                    status,
                    COALESCE(session_version, 0) AS session_version,
                    COALESCE(balance, 0) AS balance
                FROM users
                WHERE id = :id
                LIMIT 1
            ");
            $stmt->execute([':id' => $userId]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if (!$user) {
                $errors[] = __('page.registration.error.generic');
            } else {
                session_regenerate_id(true);

                $_SESSION['user'] = [
                    'id'              => (int)$user['id'],
                    'name'            => $user['name'] ?? '',
                    'phone'           => $user['phone'] ?? '',
                    'role'            => $user['role'] ?? 'user',
                    'created_at'      => $user['created_at'] ?? null,
                    'verify_code'     => $user['verify_code'] ?? null,
                    'status'          => $user['status'] ?? null,
                    'session_version' => (int)($user['session_version'] ?? 0),
                    'balance'         => (float)($user['balance'] ?? 0),
                    'is_superadmin'   => (($user['role'] ?? '') === 'superadmin') ? 1 : 0,
                ];

                header('Location: ' . mhk_url('index.php'));
                exit;
            }
        }
    }
}

$jsTexts = [
    'enter8'        => __('page.registration.error.phone_invalid'),
    'checking'      => __('page.registration.phone.checking'),
    'exists'        => __('page.registration.error.phone_exists'),
    'free'          => __('page.registration.phone.free'),
    'wait_check'    => __('page.registration.phone.wait_check'),
'legal_required' => $legalRequiredError,
];
?>
<!doctype html>
<html lang="<?= htmlspecialchars($lang) ?>">
<head>
<meta charset="utf-8">
<title><?= htmlspecialchars(__('page.registration.title')) ?></title>
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">

<script>
(function(){
  try {
    var ua = navigator.userAgent || '';
    var qs = new URLSearchParams(window.location.search || '');
    var isApp =
      /MehanikApp/i.test(ua) ||
      qs.get('app') === '1' ||
      document.cookie.indexOf('mehanik_app=1') !== -1;

    var saved = localStorage.getItem('mhk_header_theme');
    if (saved !== 'gold' && saved !== 'dark') saved = 'dark';

    document.documentElement.setAttribute('data-mhk-theme', saved);

    if (isApp) {
      document.documentElement.classList.add('mhk-app-webview');
    }
  } catch (e) {
    document.documentElement.setAttribute('data-mhk-theme', 'dark');
  }
})();
</script>

<link rel="stylesheet" href="<?= htmlspecialchars(mhk_url('assets/css/app-theme-vars.css?v=2'), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?>">
<link rel="stylesheet" href="<?= htmlspecialchars(mhk_url('assets/css/app-auth.css?v=2'), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8') ?>">

<style>
  :root{
    --mhk-bg-1:#fffdf7;
    --mhk-bg-2:#f8f1df;
    --mhk-bg-3:#ead7a4;
    --mhk-white:#ffffff;
    --mhk-text:#4a3720;
    --mhk-text-soft:#6b5330;
    --mhk-muted:#8b6f45;
    --mhk-gold:#d4af37;
    --mhk-gold-strong:#b8932f;
    --mhk-gold-soft:#f5e7bf;
    --mhk-border:rgba(180,143,61,0.22);
    --mhk-danger:#b42318;
    --mhk-danger-bg:#fff5f3;
    --mhk-success:#027a48;
    --mhk-shadow:0 18px 40px rgba(122,93,30,0.14);
    --mhk-shadow-soft:0 10px 22px rgba(122,93,30,0.10);
  }

  *{box-sizing:border-box}
  html,body{height:100%}
  body{
    margin:0;
    font-family:Inter,system-ui,-apple-system,"Segoe UI",Roboto,"Helvetica Neue",Arial,sans-serif;
    color:var(--mhk-text);
    background:
      radial-gradient(circle at 12% 18%, rgba(212,175,55,0.18), transparent 22%),
      radial-gradient(circle at 84% 12%, rgba(255,255,255,0.75), transparent 18%),
      linear-gradient(135deg,var(--mhk-bg-1) 0%, var(--mhk-bg-2) 52%, var(--mhk-bg-3) 100%);
    display:flex;
    align-items:center;
    justify-content:center;
    padding:24px;
    overflow-x:hidden;
  }

  body::before,
  body::after{
    content:"";
    position:fixed;
    border-radius:999px;
    pointer-events:none;
    z-index:0;
    filter:blur(12px);
  }
  body::before{
    width:300px;
    height:300px;
    left:-70px;
    bottom:-70px;
    background:radial-gradient(circle, rgba(212,175,55,0.22), transparent 68%);
  }
  body::after{
    width:250px;
    height:250px;
    right:-40px;
    top:-40px;
    background:radial-gradient(circle, rgba(255,255,255,0.8), transparent 68%);
  }

  .page{
    position:relative;
    z-index:1;
    width:100%;
    max-width:1120px;
  }

  .mhk-lang-floating{
    position:absolute;
    top:-6px;
    right:4px;
    z-index:50;
  }

  .wrap{
    width:100%;
    display:grid;
    grid-template-columns: 460px 1.05fr;
    gap:26px;
    align-items:stretch;
  }

  .promo{
    min-height:620px;
    position:relative;
    overflow:hidden;
    border-radius:28px;
    padding:34px;
    color:var(--mhk-text);
    background:
      linear-gradient(180deg, rgba(255,255,255,0.90), rgba(255,248,231,0.84)),
      linear-gradient(135deg, rgba(212,175,55,0.12), rgba(255,255,255,0.4));
    border:1px solid var(--mhk-border);
    box-shadow:var(--mhk-shadow);
    display:flex;
    flex-direction:column;
    justify-content:space-between;
  }

  .promo::before{
    content:"";
    position:absolute;
    inset:auto auto -70px -40px;
    width:260px;
    height:260px;
    border-radius:50%;
    background:radial-gradient(circle, rgba(212,175,55,0.18), transparent 68%);
    pointer-events:none;
  }

  .promo__brand{
    display:inline-flex;
    align-items:center;
    gap:12px;
    margin-bottom:18px;
  }
  .promo__mark{
    width:52px;
    height:52px;
    border-radius:16px;
    display:flex;
    align-items:center;
    justify-content:center;
    background:linear-gradient(135deg, #e0bf62, #c79d2b 55%, #f4e4ad);
    color:#fff;
    font-weight:900;
    font-size:20px;
    box-shadow: inset 0 1px 0 rgba(255,255,255,0.35), 0 10px 20px rgba(199,157,43,0.24);
  }
  .promo__brand-text{
    display:flex;
    flex-direction:column;
    line-height:1.05;
  }
  .promo__brand-title{
    font-weight:900;
    font-size:1.1rem;
  }
  .promo__brand-sub{
    margin-top:4px;
    font-size:.78rem;
    color:var(--mhk-muted);
    font-weight:700;
  }

  .promo h1{
    margin:0 0 14px;
    font-size:clamp(2rem, 3vw, 3.3rem);
    line-height:1.02;
    letter-spacing:-0.03em;
  }
  .promo p{
    margin:0;
    color:var(--mhk-text-soft);
    font-size:1rem;
    line-height:1.7;
  }

  .promo__steps{
    display:grid;
    gap:12px;
    margin-top:24px;
  }
  .promo__step{
    display:flex;
    align-items:flex-start;
    gap:12px;
    padding:14px 16px;
    border-radius:18px;
    background:rgba(255,255,255,0.52);
    border:1px solid rgba(212,175,55,0.14);
    box-shadow:var(--mhk-shadow-soft);
  }
  .promo__step-num{
    width:28px;
    height:28px;
    flex:0 0 28px;
    border-radius:999px;
    display:flex;
    align-items:center;
    justify-content:center;
    background:linear-gradient(135deg, #ecd28a, #c79d2b);
    color:#fff;
    font-weight:900;
    font-size:13px;
  }
  .promo__step-title{
    font-weight:900;
    font-size:.92rem;
    margin-bottom:3px;
  }
  .promo__step-text{
    font-size:.84rem;
    color:var(--mhk-muted);
    line-height:1.5;
  }

  .promo__footer{
    margin-top:26px;
    padding-top:18px;
    border-top:1px solid rgba(180,143,61,0.14);
    font-size:.9rem;
    color:var(--mhk-text-soft);
  }

  .card{
    position:relative;
    border-radius:28px;
    padding:26px;
    background:linear-gradient(180deg, rgba(255,255,255,0.97), rgba(255,248,232,0.92));
    border:1px solid var(--mhk-border);
    box-shadow:var(--mhk-shadow);
    display:flex;
    flex-direction:column;
    justify-content:center;
    min-height:620px;
  }

  .card__top{
    display:flex;
    align-items:flex-start;
    justify-content:space-between;
    gap:14px;
    margin-bottom:18px;
  }
  .card__brand{
    display:flex;
    align-items:center;
    gap:12px;
  }
  .card__mark{
    width:46px;
    height:46px;
    border-radius:15px;
    display:flex;
    align-items:center;
    justify-content:center;
    background:linear-gradient(135deg, #e0bf62, #c79d2b 55%, #f4e4ad);
    color:#fff;
    font-weight:900;
    font-size:18px;
    box-shadow: inset 0 1px 0 rgba(255,255,255,0.35), 0 8px 16px rgba(199,157,43,0.20);
  }
  .card__eyebrow{
    display:inline-flex;
    align-items:center;
    padding:5px 10px;
    border-radius:999px;
    background:rgba(212,175,55,0.10);
    color:var(--mhk-gold-strong);
    font-size:.72rem;
    font-weight:900;
    letter-spacing:.04em;
    text-transform:uppercase;
    margin-bottom:8px;
  }
  .card__title{
    font-size:1.35rem;
    font-weight:900;
    margin:0;
    color:var(--mhk-text);
  }
  .card__subtitle{
    margin-top:5px;
    font-size:.86rem;
    color:var(--mhk-muted);
    line-height:1.5;
  }
  .card__meta{
    font-size:.78rem;
    color:var(--mhk-muted);
    font-weight:800;
    white-space:nowrap;
  }

  .errors{
    margin-bottom:14px;
    background:var(--mhk-danger-bg);
    border:1px solid rgba(180,35,24,0.16);
    color:var(--mhk-danger);
    padding:12px 14px;
    border-radius:16px;
    box-shadow:0 8px 18px rgba(180,35,24,0.05);
  }
  .errors ul{ margin:0; padding-left:18px; }
  .errors li + li{ margin-top:4px; }

  form{
    display:flex;
    flex-direction:column;
    gap:14px;
  }

  .field-label{
    display:block;
    margin-bottom:7px;
    font-size:.8rem;
    color:var(--mhk-muted);
    font-weight:800;
    letter-spacing:.01em;
  }

  .input-inline{
    display:flex;
    align-items:stretch;
  }

  .prefix{
    display:flex;
    align-items:center;
    justify-content:center;
    min-width:78px;
    padding:0 14px;
    border-radius:16px 0 0 16px;
    border:1px solid rgba(180,143,61,0.18);
    border-right:0;
    background:linear-gradient(180deg, #fffdf7, #f7edd7);
    color:var(--mhk-text-soft);
    font-weight:900;
    font-size:.92rem;
  }

  .field-input{
    width:100%;
    height:52px;
    border:1px solid rgba(180,143,61,0.18);
    border-radius:16px;
    background:rgba(255,255,255,0.96);
    color:var(--mhk-text);
    padding:0 16px;
    font-size:.96rem;
    font-weight:600;
    outline:none;
    transition:border-color .18s ease, box-shadow .18s ease, background .18s ease;
  }
  .field-input::placeholder{
    color:#b39a68;
    font-weight:500;
  }
  .field-input:focus{
    border-color:rgba(212,175,55,0.55);
    box-shadow:0 0 0 4px rgba(212,175,55,0.10);
    background:#fff;
  }

  .input-inline .field-input{
    border-radius:0 16px 16px 0;
  }

  .field-hint{
    margin-top:8px;
    font-size:.78rem;
    color:var(--mhk-muted);
    line-height:1.5;
    min-height:18px;
  }

  .phone-check-msg{
    margin-top:6px;
    font-size:.78rem;
    min-height:18px;
    font-weight:800;
  }

  .actions{
    display:flex;
    gap:10px;
    align-items:center;
    margin-top:6px;
    flex-wrap:wrap;
  }

  .btn-primary{
    appearance:none;
    border:0;
    min-height:50px;
    padding:0 18px;
    border-radius:16px;
    cursor:pointer;
    font-weight:900;
    font-size:.92rem;
    color:#fff;
    background:linear-gradient(135deg, #d4af37, #b8932f);
    box-shadow:0 12px 24px rgba(184,147,47,0.22);
    transition:transform .16s ease, box-shadow .16s ease, filter .16s ease;
  }
  .btn-primary:hover{
    transform:translateY(-1px);
    box-shadow:0 15px 28px rgba(184,147,47,0.28);
    filter:saturate(1.03);
  }
  .btn-primary[disabled]{
    opacity:.72;
    cursor:not-allowed;
    transform:none;
    box-shadow:0 8px 16px rgba(184,147,47,0.16);
  }

  .btn-link{
    color:var(--mhk-gold-strong);
    text-decoration:none;
    font-weight:900;
    font-size:.9rem;
  }
  .btn-link:hover{
    text-decoration:underline;
  }

  .small-muted{
    margin-top:12px;
    font-size:.8rem;
    color:var(--mhk-muted);
    line-height:1.55;
  }

  .mhk-lang-custom{
    position:relative;
    display:inline-block;
  }
  .lang-btn{
    display:inline-flex;
    align-items:center;
    gap:6px;
    padding:8px 10px;
    border-radius:999px;
    font-weight:900;
    cursor:pointer;
    border:1px solid rgba(180,143,61,0.18);
    background:linear-gradient(180deg, rgba(255,255,255,0.96), rgba(255,248,231,0.88));
    color:var(--mhk-text);
    box-shadow:0 6px 14px rgba(122,93,30,0.10);
    backdrop-filter:blur(8px);
  }
  .lang-btn .label{ font-size:.72rem; }
  .lang-btn .caret{
    width:0;
    height:0;
    border-left:5px solid transparent;
    border-right:5px solid transparent;
    border-top:6px solid var(--mhk-text-soft);
    transform:translateY(1px);
  }

  .lang-list{
    position:absolute;
    top:calc(100% + 8px);
    right:0;
    background:linear-gradient(180deg,#fffefb,#f7edd7);
    border:1px solid rgba(180,143,61,0.22);
    border-radius:12px;
    padding:6px;
    min-width:150px;
    box-shadow:0 14px 30px rgba(122,93,30,0.14);
    display:none;
    z-index:9999;
  }
  .lang-list.open{ display:block; }
  .lang-item{
    display:block;
    padding:8px 10px;
    border-radius:9px;
    color:var(--mhk-text);
    font-weight:800;
    text-decoration:none;
  }
  .lang-item:hover,
  .lang-item:focus{
    background:rgba(212,175,55,0.12);
    color:#3f2d16;
    outline:none;
  }

    .legal-box{
    margin-top:2px;
    padding:12px 14px;
    border-radius:16px;
    background:rgba(255,255,255,0.58);
    border:1px solid rgba(180,143,61,0.16);
  }
  .legal-check{
    display:flex;
    align-items:flex-start;
    gap:10px;
    cursor:pointer;
    color:var(--mhk-text-soft);
    font-size:.84rem;
    line-height:1.5;
    font-weight:700;
  }
  .legal-check input{
    margin-top:3px;
    width:18px;
    height:18px;
    accent-color:var(--mhk-gold-strong);
    flex:0 0 auto;
  }
  .legal-links{
    margin-top:8px;
    display:flex;
    gap:10px;
    flex-wrap:wrap;
  }
  .legal-link-btn{
    appearance:none;
    border:0;
    background:transparent;
    color:var(--mhk-gold-strong);
    font-weight:900;
    cursor:pointer;
    padding:0;
    font-size:.82rem;
    text-decoration:underline;
  }
  .legal-modal{
    position:fixed;
    inset:0;
    z-index:99999;
    display:none;
    align-items:center;
    justify-content:center;
    padding:18px;
    background:rgba(45,32,12,0.46);
    backdrop-filter:blur(5px);
  }
  .legal-modal.open{ display:flex; }
  .legal-modal__box{
    width:min(760px, 100%);
    max-height:82vh;
    overflow:hidden;
    border-radius:24px;
    background:linear-gradient(180deg,#fffefb,#f8efd8);
    border:1px solid rgba(180,143,61,0.25);
    box-shadow:0 24px 70px rgba(45,32,12,0.25);
    display:flex;
    flex-direction:column;
  }
  .legal-modal__head{
    display:flex;
    align-items:center;
    justify-content:space-between;
    gap:12px;
    padding:18px 20px;
    border-bottom:1px solid rgba(180,143,61,0.16);
  }
  .legal-modal__title{
    margin:0;
    font-size:1.12rem;
    font-weight:900;
    color:var(--mhk-text);
  }
  .legal-modal__close{
    border:0;
    width:36px;
    height:36px;
    border-radius:999px;
    cursor:pointer;
    background:rgba(212,175,55,0.14);
    color:var(--mhk-text);
    font-size:24px;
    line-height:1;
    font-weight:900;
  }
  .legal-modal__body{
    padding:18px 20px 22px;
    overflow:auto;
  }
  .legal-section + .legal-section{
    margin-top:16px;
  }
  .legal-section h4{
    margin:0 0 7px;
    font-size:.96rem;
    color:var(--mhk-text);
  }
  .legal-section p{
    margin:0;
    color:var(--mhk-text-soft);
    line-height:1.65;
    font-size:.9rem;
  }
</style>
</head>
<body>
<div class="page">
  <div class="mhk-lang-floating">
    <div class="mhk-lang-custom" id="mhk-lang-custom">
      <button type="button" class="lang-btn" id="mhk-lang-btn" aria-haspopup="true" aria-expanded="false" aria-controls="mhk-lang-list">
        <span class="label"><?= strtoupper(me_get_lang()) ?></span>
        <span class="caret" aria-hidden="true"></span>
      </button>

      <div class="lang-list" id="mhk-lang-list" role="menu" aria-label="<?= htmlspecialchars(__('common.language')) ?>">
        <a class="lang-item" role="menuitem" href="<?= htmlspecialchars(url_with_lang('en')) ?>"><?= htmlspecialchars(__('common.lang.en')) ?></a>
        <a class="lang-item" role="menuitem" href="<?= htmlspecialchars(url_with_lang('tm')) ?>"><?= htmlspecialchars(__('common.lang.tm')) ?></a>
        <a class="lang-item" role="menuitem" href="<?= htmlspecialchars(url_with_lang('ru')) ?>"><?= htmlspecialchars(__('common.lang.ru')) ?></a>
      </div>
    </div>
  </div>

  <div class="wrap">
    <section class="promo">
      <div>
        <div class="promo__brand">
          <div class="promo__mark">M</div>
          <div class="promo__brand-text">
            <div class="promo__brand-title"><?= htmlspecialchars(__('common.brand')) ?></div>
            <div class="promo__brand-sub"><?= htmlspecialchars(__('header.brand_subtitle')) ?></div>
          </div>
        </div>

        <h1><?= htmlspecialchars(__('page.registration.promo.title')) ?></h1>
        <p><?= htmlspecialchars(__('page.registration.promo.description')) ?></p>

        <div class="promo__steps">
          <div class="promo__step">
            <div class="promo__step-num">01</div>
            <div>
              <div class="promo__step-title"><?= htmlspecialchars(__('page.registration.form.name_label')) ?></div>
              <div class="promo__step-text"><?= htmlspecialchars(__('page.registration.form.name_placeholder')) ?></div>
            </div>
          </div>

          <div class="promo__step">
            <div class="promo__step-num">02</div>
            <div>
              <div class="promo__step-title"><?= htmlspecialchars(__('page.registration.form.phone_label')) ?></div>
              <div class="promo__step-text"><?= htmlspecialchars(__('page.registration.form.phone_hint')) ?></div>
            </div>
          </div>

          <div class="promo__step">
            <div class="promo__step-num">03</div>
            <div>
              <div class="promo__step-title"><?= htmlspecialchars(__('page.registration.promo.hint_label')) ?></div>
              <div class="promo__step-text"><?= htmlspecialchars(__('page.registration.promo.hint')) ?></div>
            </div>
          </div>
        </div>
      </div>

      <div class="promo__footer">
        <?= htmlspecialchars(__('page.registration.card.footer_note')) ?>
      </div>
    </section>

    <section class="card" aria-live="polite">
      <div class="card__top">
        <div class="card__brand">
          <div class="card__mark">M</div>
          <div>
            <div class="card__eyebrow"><?= htmlspecialchars(__('page.registration.card.note')) ?></div>
            <h2 class="card__title"><?= htmlspecialchars(__('page.registration.card.title')) ?></h2>
            <div class="card__subtitle"><?= htmlspecialchars(__('page.registration.card.subtitle')) ?></div>
          </div>
        </div>

        <div class="card__meta"><?= htmlspecialchars(__('page.registration.title')) ?></div>
      </div>

      <?php if (!empty($errors)): ?>
        <div class="errors">
          <ul>
            <?php foreach ($errors as $e): ?>
              <li><?= htmlspecialchars($e) ?></li>
            <?php endforeach; ?>
          </ul>
        </div>
      <?php endif; ?>

      <form method="post" action="" autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false" id="registerForm" novalidate>
        <input style="display:none" type="text" name="fakeusernameremembered" id="fakeusernameremembered" autocomplete="off">

        <div>
          <label class="field-label" for="name"><?= htmlspecialchars(__('page.registration.form.name_label')) ?></label>
          <input
            id="name"
            name="name"
            class="field-input"
            type="text"
            placeholder="<?= htmlspecialchars(__('page.registration.form.name_placeholder')) ?>"
            required
            autocomplete="off"
            value="<?= htmlspecialchars($name) ?>"
          >
        </div>

        <div>
          <label class="field-label" for="phone_local"><?= htmlspecialchars(__('page.registration.form.phone_label')) ?></label>
          <div class="input-inline">
            <div class="prefix">+993</div>
            <input
              id="phone_local"
              name="phone_local"
              class="field-input"
              type="text"
              inputmode="numeric"
              pattern="\d{8}"
              maxlength="8"
              placeholder="XXXXXXXX"
              autocomplete="off"
              autocorrect="off"
              autocapitalize="off"
              spellcheck="false"
              value="<?= htmlspecialchars($phone_local) ?>"
            >
          </div>
          <div class="field-hint"><?= htmlspecialchars(__('page.registration.form.phone_hint')) ?></div>
          <div id="phoneCheckMsg" class="phone-check-msg"></div>
        </div>

        <div>
          <label class="field-label" for="password"><?= htmlspecialchars(__('page.registration.form.password_label')) ?></label>
          <input
            id="password"
            name="password"
            class="field-input"
            type="password"
            placeholder="<?= htmlspecialchars(__('page.registration.form.password_placeholder')) ?>"
            required
            autocomplete="new-password"
          >
        </div>

        <div>
          <label class="field-label" for="password_confirm"><?= htmlspecialchars(__('page.registration.form.password_confirm_label')) ?></label>
          <input
            id="password_confirm"
            name="password_confirm"
            class="field-input"
            type="password"
            placeholder="<?= htmlspecialchars(__('page.registration.form.password_confirm_placeholder')) ?>"
            required
            autocomplete="new-password"
          >
        </div>

        <div class="legal-box">
          <label class="legal-check">
            <input type="checkbox" name="legal_accept" id="legal_accept" value="1" required>
            <span><?= htmlspecialchars($legalTexts['accept_text'] ?? __('page.registration.legal.accept_text')) ?></span>
          </label>

          <div class="legal-links">
            <button type="button" class="legal-link-btn" data-legal-open="rules">
              <?= htmlspecialchars($legalTexts['open_rules'] ?? __('page.registration.legal.open_rules')) ?>
            </button>
            <button type="button" class="legal-link-btn" data-legal-open="agreement">
              <?= htmlspecialchars($legalTexts['open_agreement'] ?? __('page.registration.legal.open_agreement')) ?>
            </button>
          </div>
        </div>

        <div class="actions">
          <button type="submit" class="btn-primary"><?= htmlspecialchars(__('page.registration.form.submit')) ?></button>
          <a class="btn-link" href="<?= htmlspecialchars(mhk_url('login.php')) ?>"><?= htmlspecialchars(__('page.registration.form.login_link')) ?></a>
        </div>

        <div class="small-muted">
          <?= htmlspecialchars(__('page.registration.card.footer_note')) ?>
        </div>
      </form>
    </section>
  </div>
</div>

<div class="legal-modal" id="legalModal" aria-hidden="true">
  <div class="legal-modal__box" role="dialog" aria-modal="true">
    <div class="legal-modal__head">
      <h3 class="legal-modal__title" id="legalModalTitle"></h3>
      <button type="button" class="legal-modal__close" id="legalModalClose" aria-label="Close">×</button>
    </div>
    <div class="legal-modal__body" id="legalModalBody"></div>
  </div>
</div>

<script>
(function(){
  var btn = document.getElementById('mhk-lang-btn');
  var list = document.getElementById('mhk-lang-list');
  var wrapper = document.getElementById('mhk-lang-custom');

  if (!btn || !list) return;

  function open() {
    list.classList.add('open');
    btn.setAttribute('aria-expanded','true');
    var first = list.querySelector('.lang-item');
    if (first) first.focus();
    document.addEventListener('click', docClick);
    document.addEventListener('keydown', onKeyDown);
  }

  function close() {
    list.classList.remove('open');
    btn.setAttribute('aria-expanded','false');
    document.removeEventListener('click', docClick);
    document.removeEventListener('keydown', onKeyDown);
    btn.focus();
  }

  function docClick(e){
    if (!wrapper.contains(e.target)) close();
  }

  function onKeyDown(e){
    if (e.key === 'Escape') close();
    if ((e.key === 'Enter' || e.key === ' ') && document.activeElement.classList.contains('lang-item')) {
      document.activeElement.click();
    }
    if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
      var items = Array.from(list.querySelectorAll('.lang-item'));
      var idx = items.indexOf(document.activeElement);
      if (idx === -1) idx = e.key === 'ArrowDown' ? -1 : 0;
      var next = null;
      if (e.key === 'ArrowDown') next = items[(idx + 1) % items.length];
      else next = items[(idx - 1 + items.length) % items.length];
      if (next) next.focus();
      e.preventDefault();
    }
  }

  btn.addEventListener('click', function(e){
    e.stopPropagation();
    if (list.classList.contains('open')) close();
    else open();
  });

  Array.from(list.querySelectorAll('.lang-item')).forEach(function(a){
    a.setAttribute('tabindex','0');
    a.addEventListener('keydown', function(e){
      if (e.key === 'Enter' || e.key === ' ') {
        window.location = a.href;
      }
    });
  });
})();

(function(){
  try {
    const texts = <?= json_encode($jsTexts, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;

    const legalDocs = <?= json_encode([
      'rulesTitle' => $legalTexts['platform_rules_title'],
      'agreementTitle' => $legalTexts['user_agreement_title'],
      'rules' => $legalTexts['platform_rules'],
      'agreement' => $legalTexts['user_agreement'],
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) ?>;
    const form = document.getElementById('registerForm');
    const phoneField = document.getElementById('phone_local');
    const pass = document.getElementById('password');
    const pass2 = document.getElementById('password_confirm');
    const phoneMsg = document.getElementById('phoneCheckMsg');
    const submitBtn = document.querySelector('#registerForm button[type="submit"]');
    const legalAccept = document.getElementById('legal_accept');
    const legalModal = document.getElementById('legalModal');
    const legalModalTitle = document.getElementById('legalModalTitle');
    const legalModalBody = document.getElementById('legalModalBody');
    const legalModalClose = document.getElementById('legalModalClose');

    function escapeHtml(s) {
      return String(s || '').replace(/[&<>"']/g, function(ch){
        return ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'})[ch];
      });
    }

    function openLegalModal(type) {
      if (!legalModal || !legalModalTitle || !legalModalBody) return;

      const isAgreement = type === 'agreement';
      const title = isAgreement ? legalDocs.agreementTitle : legalDocs.rulesTitle;
      const items = isAgreement ? legalDocs.agreement : legalDocs.rules;

      legalModalTitle.textContent = title || '';
      legalModalBody.innerHTML = (items || []).map(function(item){
        return '<section class="legal-section">' +
          '<h4>' + escapeHtml(item.title) + '</h4>' +
          '<p>' + escapeHtml(item.body) + '</p>' +
        '</section>';
      }).join('');

      legalModal.classList.add('open');
      legalModal.setAttribute('aria-hidden', 'false');
      document.body.style.overflow = 'hidden';
    }

    function closeLegalModal() {
      if (!legalModal) return;
      legalModal.classList.remove('open');
      legalModal.setAttribute('aria-hidden', 'true');
      document.body.style.overflow = '';
    }

    document.querySelectorAll('[data-legal-open]').forEach(function(btn){
      btn.addEventListener('click', function(){
        openLegalModal(btn.getAttribute('data-legal-open'));
      });
    });

    if (legalModalClose) {
      legalModalClose.addEventListener('click', closeLegalModal);
    }

    if (legalModal) {
      legalModal.addEventListener('click', function(e){
        if (e.target === legalModal) closeLegalModal();
      });
    }

    document.addEventListener('keydown', function(e){
      if (e.key === 'Escape') closeLegalModal();
    });
    let phoneCheckTimer = null;
    let phoneCheckPending = false;
    let phoneExists = false;

    function setPhoneMessage(text, color) {
      if (!phoneMsg) return;
      phoneMsg.textContent = text || '';
      phoneMsg.style.color = color || '#8b6f45';
    }

    async function checkPhoneExists(phone) {
      const url = '<?= htmlspecialchars(mhk_url("api/mobile/v1/check-phone.php")) ?>?phone_local=' + encodeURIComponent(phone);

      const res = await fetch(url, {
        method: 'GET',
        headers: { 'Accept': 'application/json' }
      });

      if (!res.ok) {
        throw new Error('HTTP ' + res.status);
      }

      return await res.json();
    }

    if (form) {
      form.setAttribute('autocomplete', 'off');
    }

    window.addEventListener('load', () => {
      setTimeout(() => {
        if (phoneField) phoneField.value = phoneField.value ? phoneField.value.trim() : '';
        if (pass) pass.value = '';
        if (pass2) pass2.value = '';
      }, 60);
    });

    window.addEventListener('pagehide', () => {
      try {
        if (phoneField) phoneField.value = '';
        if (pass) pass.value = '';
        if (pass2) pass2.value = '';
      } catch(e){}
    });

    document.querySelectorAll('input').forEach(input => {
      input.addEventListener('focus', () => {
        setTimeout(() => {
          if (input && (input.id === 'password' || input.id === 'password_confirm')) {
            input.value = '';
          }
        }, 30);
      });
    });

    if (phoneField) {
      phoneField.addEventListener('input', function(){
        this.value = this.value.replace(/\D/g, '').slice(0, 8);

        const val = this.value.trim();

        if (phoneCheckTimer) {
          clearTimeout(phoneCheckTimer);
        }

        phoneCheckPending = false;
        phoneExists = false;
        if (submitBtn) submitBtn.disabled = false;
        setPhoneMessage('', '#8b6f45');

        if (val.length === 0) {
          return;
        }

        if (val.length < 8) {
          setPhoneMessage(texts.enter8, '#8b6f45');
          return;
        }

        phoneCheckPending = true;
        setPhoneMessage(texts.checking, '#8b6f45');

        phoneCheckTimer = setTimeout(async () => {
          try {
            const data = await checkPhoneExists(val);
            phoneCheckPending = false;

            if (data && data.ok && data.exists) {
              phoneExists = true;
              setPhoneMessage(texts.exists, '#b42318');
              if (submitBtn) submitBtn.disabled = true;
            } else if (data && data.ok) {
              phoneExists = false;
              setPhoneMessage(texts.free, '#027a48');
              if (submitBtn) submitBtn.disabled = false;
            } else {
              phoneExists = false;
              setPhoneMessage('', '#8b6f45');
              if (submitBtn) submitBtn.disabled = false;
            }
          } catch (e) {
            
            phoneCheckPending = false;
            phoneExists = false;
            setPhoneMessage('', '#8b6f45');
            if (submitBtn) submitBtn.disabled = false;
          }
        }, 350);
      });

      if (phoneField.value.trim() !== '') {
        phoneField.dispatchEvent(new Event('input'));
      }
    }

    if (form) {
      form.addEventListener('submit', function(e){
        if (legalAccept && !legalAccept.checked) {
          e.preventDefault();
          alert(texts.legal_required);
          legalAccept.focus();
          return;
        }

        if (phoneCheckPending) {
          e.preventDefault();
          setPhoneMessage(texts.wait_check, '#8b6f45');
          if (phoneField) phoneField.focus();
          return;
        }

        if (phoneExists) {
          e.preventDefault();
          setPhoneMessage(texts.exists, '#b42318');
          if (phoneField) phoneField.focus();
        }
      });
    }
  } catch(e){
    
  }
})();
</script>
</body>
</html>