<?php
// public/login.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';

$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 mhk_public_url(string $path = ''): string {
    return mhk_url($path);
}

$base = mhk_normalize_base_url($config['base_url'] ?? '');
$lang = me_get_lang();

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(''));
exit;
}

$errors = [];
$phone_local = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $phone_local = isset($_POST['phone_local'])
        ? preg_replace('/\D/', '', (string)$_POST['phone_local'])
        : '';

    $password = isset($_POST['password']) ? (string)$_POST['password'] : '';

    if ($phone_local === '') {
        $errors[] = __('page.login.error.phone_required');
    } elseif (!preg_match('/^\d{8}$/', $phone_local)) {
        $errors[] = __('page.login.error.phone_invalid');
    }

    if ($password === '') {
        $errors[] = __('page.login.error.password_required');
    }

    if (empty($errors)) {
        $phoneNorm = '+993' . $phone_local;

        $stmt = $pdo->prepare("
            SELECT
                id,
                name,
                phone,
                password_hash,
                role,
                created_at,
                verify_code,
                status,
                COALESCE(session_version, 0) AS session_version,
                COALESCE(balance, 0) AS balance
            FROM users
            WHERE phone = :phone
            LIMIT 1
        ");
        $stmt->execute([':phone' => $phoneNorm]);
        $user = $stmt->fetch(PDO::FETCH_ASSOC);

        if (!$user) {
            $errors[] = __('page.login.error.user_not_found');
        } else {
            $hash = (string)($user['password_hash'] ?? '');

            if ($hash === '' || !password_verify($password, $hash)) {
                $errors[] = __('page.login.error.wrong_password');
            } elseif (($user['status'] ?? '') === 'blocked') {
                $errors[] = __('page.login.error.blocked');
            } 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(''));
exit;
            }
        }
    }
}
?>
<!doctype html>
<html lang="<?= htmlspecialchars($lang) ?>">
<head>
<meta charset="utf-8">
<title><?= htmlspecialchars(__('page.login.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=3'), 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-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 15% 20%, rgba(212,175,55,0.18), transparent 22%),
      radial-gradient(circle at 85% 10%, 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:280px;
    height:280px;
    left:-60px;
    bottom:-70px;
    background:radial-gradient(circle, rgba(212,175,55,0.22), transparent 68%);
  }
  body::after{
    width:240px;
    height:240px;
    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:1100px;
  }

  .mhk-lang-floating{
    position:absolute;
    top:-6px;
    right:4px;
    z-index:50;
  }

  .wrap{
    width:100%;
    display:grid;
    grid-template-columns: 1.05fr 460px;
    gap:26px;
    align-items:stretch;
  }

  .promo{
    min-height:560px;
    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 -40px -60px auto;
    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__list{
    display:grid;
    gap:12px;
    margin-top:24px;
  }
  .promo__item{
    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__item-badge{
    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__item-title{
    font-weight:900;
    font-size:.92rem;
    margin-bottom:3px;
  }
  .promo__item-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:560px;
  }

  .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-wrap{
    position:relative;
  }

  .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;
  }

  .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-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;
  }
</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.login.promo.title')) ?></h1>
        <p><?= htmlspecialchars(__('page.login.promo.description')) ?></p>

        <div class="promo__list">
          <div class="promo__item">
            <div class="promo__item-badge">01</div>
            <div>
              <div class="promo__item-title"><?= htmlspecialchars(__('page.login.card.title')) ?></div>
              <div class="promo__item-text"><?= htmlspecialchars(__('page.login.card.subtitle')) ?></div>
            </div>
          </div>

          <div class="promo__item">
            <div class="promo__item-badge">02</div>
            <div>
              <div class="promo__item-title"><?= htmlspecialchars(__('page.login.promo.hint_label')) ?></div>
              <div class="promo__item-text"><?= htmlspecialchars(__('page.login.promo.hint')) ?></div>
            </div>
          </div>

          <div class="promo__item">
            <div class="promo__item-badge">03</div>
            <div>
              <div class="promo__item-title"><?= htmlspecialchars(__('page.login.form.phone_label')) ?> + <?= htmlspecialchars(__('page.login.form.password_label')) ?></div>
              <div class="promo__item-text"><?= htmlspecialchars(__('page.login.form.phone_hint')) ?></div>
            </div>
          </div>
        </div>
      </div>

      <div class="promo__footer">
        <?= htmlspecialchars(__('page.login.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.login.card.note')) ?></div>
            <h2 class="card__title"><?= htmlspecialchars(__('page.login.card.title')) ?></h2>
            <div class="card__subtitle"><?= htmlspecialchars(__('page.login.card.subtitle')) ?></div>
          </div>
        </div>

        <div class="card__meta"><?= htmlspecialchars(__('page.login.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="loginForm" novalidate>
        <input style="display:none" type="text" name="fakeusernameremembered" id="fakeusernameremembered" autocomplete="off">

        <div>
          <label class="field-label" for="phone_local"><?= htmlspecialchars(__('page.login.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.login.form.phone_hint')) ?></div>
        </div>

        <div>
          <label class="field-label" for="password"><?= htmlspecialchars(__('page.login.form.password_label')) ?></label>
          <input
            id="password"
            name="password"
            class="field-input"
            type="password"
            placeholder="<?= htmlspecialchars(__('page.login.form.password_placeholder')) ?>"
            autocomplete="current-password"
            autocorrect="off"
            autocapitalize="off"
            spellcheck="false"
          >
        </div>

        <div class="actions">
          <button type="submit" class="btn-primary"><?= htmlspecialchars(__('page.login.form.submit')) ?></button>
          <a class="btn-link" href="<?= htmlspecialchars(mhk_url('register')) ?>"><?= htmlspecialchars(__('page.login.form.register_link')) ?></a>
        </div>

        <div class="small-muted">
          <?= htmlspecialchars(__('page.login.card.footer_note')) ?>
          <a href="<?= htmlspecialchars(mhk_url('logout')) ?>" class="btn-link"><?= htmlspecialchars(__('page.login.card.logout_link')) ?></a>.
        </div>
      </form>
    </section>
  </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 form = document.getElementById('loginForm');
    form.setAttribute('autocomplete','off');

    window.addEventListener('load', () => {
      setTimeout(() => {
        const phone = document.getElementById('phone_local');
        const pass  = document.getElementById('password');
        if (phone) { phone.value = phone.value ? phone.value.trim() : ''; }
        if (pass)  { pass.value = ''; }
      }, 60);
    });

    window.addEventListener('pagehide', () => {
      try {
        const phone = document.getElementById('phone_local');
        const pass  = document.getElementById('password');
        if (phone) phone.value = '';
        if (pass) pass.value = '';
      } catch(e){}
    });

    document.querySelectorAll('input').forEach(input => {
      input.addEventListener('focus', () => {
        setTimeout(() => {
          if (input && input.id === 'password') input.value = '';
        }, 30);
      });
    });

    const phoneField = document.getElementById('phone_local');
    if (phoneField) {
      phoneField.addEventListener('input', function(){
        this.value = this.value.replace(/\D/g,'').slice(0,8);
      });
    }
  } catch(e){
    
  }
})();
</script>
</body>
</html>