<?php
// ============================================================
//  profile.php  —  Author Profile: View & Edit
// ============================================================
error_reporting(E_ALL & ~E_NOTICE & ~E_WARNING);
ini_set("display_errors", 0);
require_once __DIR__ . '/config/db.php';
startSession();

$user    = getCurrentUser();
$user_id = $user['user_id'];

$pageTitle  = 'My Profile';
$activePage = 'profile';

// ── Handle AJAX save ─────────────────────────────────────────
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_save'])) {
    header('Content-Type: application/json');
    try {
        $first    = trim($_POST['first_name']          ?? '');
        $last     = trim($_POST['last_name']            ?? '');
        $title    = trim($_POST['title']               ?? '');
        $phone_c  = trim($_POST['phone_country_code']  ?? '');
        $phone    = trim($_POST['phone_number']        ?? '');
        $inst     = trim($_POST['institutional_email'] ?? '');
        $bio      = trim($_POST['bio']                 ?? '');
        $interests= trim($_POST['reviewing_interests'] ?? '');
        $website  = trim($_POST['website']             ?? '');
        $country  = trim($_POST['country']             ?? '');

        if (!$first || !$last) {
            echo json_encode(['success' => false, 'message' => 'First and last name are required.']);
            exit;
        }

        $optionals = [
            'title'               => $title,
            'phone_country_code'  => $phone_c,
            'phone_number'        => $phone,
            'institutional_email' => $inst,
            'bio'                 => $bio,
            'reviewing_interests' => $interests,
            'website'             => $website,
            'country'             => $country,
        ];

        $setParts = ['first_name=?', 'last_name=?'];
        $vals     = [$first, $last];

        foreach ($optionals as $col => $val) {
            $setParts[] = "$col=?";
            $vals[]     = $val ?: null;
        }

        $vals[] = $user_id;
        $sql = "UPDATE users SET " . implode(', ', $setParts) . " WHERE user_id=?";

        try {
            db()->prepare($sql)->execute($vals);
            echo json_encode(['success' => true, 'first_name' => $first, 'last_name' => $last, 'country' => $country]);
        } catch (PDOException $e) {
            // Fallback: minimal update without optional columns
            db()->prepare("UPDATE users SET first_name=?, last_name=?, country=? WHERE user_id=?")
                ->execute([$first, $last, $country ?: null, $user_id]);
            echo json_encode(['success' => true, 'first_name' => $first, 'last_name' => $last, 'country' => $country]);
        }
    } catch (Exception $e) {
        echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    }
    exit;
}

// ── Load fresh user data ──────────────────────────────────────
try {
    $stmt = db()->prepare("SELECT * FROM users WHERE user_id=?");
    $stmt->execute([$user_id]);
    $u = $stmt->fetch(PDO::FETCH_ASSOC) ?: $user;
} catch (PDOException $e) { $u = $user; }

// ── Load affiliation ──────────────────────────────────────────
$affilName = '';
try {
    if (!empty($u['affiliation_id'])) {
        $aq = db()->prepare("SELECT name, city, country FROM affiliations WHERE affiliation_id=?");
        $aq->execute([$u['affiliation_id']]);
        $affil = $aq->fetch(PDO::FETCH_ASSOC);
        if ($affil) {
            $affilName = implode(', ', array_filter([$affil['name'], $affil['city'], $affil['country']]));
        }
    }
} catch (PDOException $e) {}

// ── Stats ─────────────────────────────────────────────────────
try {
    $qs = db()->prepare("SELECT COUNT(*) FROM submissions WHERE user_id=?");
    $qs->execute([$user_id]); $totalSubs = (int)$qs->fetchColumn();
} catch (PDOException $e) { $totalSubs = 0; }

try {
    $qa = db()->prepare(
        "SELECT COUNT(*) FROM submission_authors sa
         JOIN submissions s ON s.submission_id = sa.submission_id
         WHERE sa.user_id=? AND sa.is_corresponding=1"
    );
    $qa->execute([$user_id]); $corrCount = (int)$qa->fetchColumn();
} catch (PDOException $e) { $corrCount = 0; }

try {
    $qp = db()->prepare(
        "SELECT COUNT(*) FROM submissions WHERE user_id=? AND submission_status='accepted'"
    );
    $qp->execute([$user_id]); $acceptedCount = (int)$qp->fetchColumn();
} catch (PDOException $e) { $acceptedCount = 0; }

$fullName = trim(($u['first_name'] ?? '') . ' ' . ($u['last_name'] ?? ''));
$initials = strtoupper(substr($u['first_name'] ?? 'A', 0, 1) . substr($u['last_name'] ?? 'A', 0, 1));

function p($v) { return htmlspecialchars($v ?? ''); }

$titles = ['', 'Mr', 'Mrs', 'Ms', 'Dr', 'Prof'];

$phoneCodes = [
    '+1'=>'US','+7'=>'RU','+20'=>'EG','+27'=>'ZA','+30'=>'GR','+31'=>'NL',
    '+32'=>'BE','+33'=>'FR','+34'=>'ES','+39'=>'IT','+40'=>'RO','+41'=>'CH',
    '+43'=>'AT','+44'=>'UK','+45'=>'DK','+46'=>'SE','+47'=>'NO','+48'=>'PL',
    '+49'=>'DE','+52'=>'MX','+55'=>'BR','+60'=>'MY','+61'=>'AU','+62'=>'ID',
    '+65'=>'SG','+81'=>'JP','+82'=>'KR','+86'=>'CN','+90'=>'TR','+91'=>'IN',
    '+92'=>'PK','+94'=>'LK','+98'=>'IR','+212'=>'MA','+234'=>'NG','+254'=>'KE',
    '+966'=>'SA','+971'=>'AE','+972'=>'IL'
];

$countries = [
    'Afghanistan','Albania','Algeria','Argentina','Armenia','Australia','Austria',
    'Azerbaijan','Bangladesh','Belarus','Belgium','Bolivia','Bosnia and Herzegovina',
    'Brazil','Bulgaria','Cambodia','Cameroon','Canada','Chile','China','Colombia',
    'Costa Rica','Croatia','Cuba','Czech Republic','Denmark','Dominican Republic',
    'Ecuador','Egypt','El Salvador','Estonia','Ethiopia','Finland','France','Georgia',
    'Germany','Ghana','Greece','Guatemala','Honduras','Hungary','India','Indonesia',
    'Iran','Iraq','Ireland','Israel','Italy','Jamaica','Japan','Jordan','Kazakhstan',
    'Kenya','Kosovo','Kuwait','Kyrgyzstan','Latvia','Lebanon','Libya','Lithuania',
    'Luxembourg','Malaysia','Mexico','Moldova','Mongolia','Morocco','Mozambique',
    'Myanmar','Nepal','Netherlands','New Zealand','Nicaragua','Nigeria','Norway',
    'Oman','Pakistan','Panama','Paraguay','Peru','Philippines','Poland','Portugal',
    'Qatar','Romania','Russia','Saudi Arabia','Senegal','Serbia','Singapore',
    'Slovakia','Slovenia','Somalia','South Africa','South Korea','South Sudan',
    'Spain','Sri Lanka','Sudan','Sweden','Switzerland','Syria','Taiwan','Tajikistan',
    'Tanzania','Thailand','Tunisia','Turkey','Turkmenistan','Uganda','Ukraine',
    'United Arab Emirates','United Kingdom','United States','Uruguay','Uzbekistan',
    'Venezuela','Vietnam','Yemen','Zambia','Zimbabwe'
];

// Currency info per country for display hint
$country_currency_hint = [
    'India' => 'INR ₹ — Razorpay only',
    'Bangladesh' => 'BDT ৳ — All gateways',
    'Nigeria' => 'NGN ₦ — All gateways',
    'Pakistan' => 'PKR Rs — All gateways',
    'Philippines' => 'PHP ₱ — All gateways + GCash',
    'United States' => 'USD $ — All gateways',
    'United Kingdom' => 'USD $ — All gateways',
];

require_once __DIR__ . '/_layout.php';
?>

<style>
.au-main { padding: 24px 28px 60px; }

.profile-container {
  max-width: 780px;
  margin: 0 auto;
}

/* Profile header card */
.profile-header-card {
  background: var(--white);
  border: 1px solid var(--border);
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
  box-shadow: 0 1px 4px rgba(0,0,0,.06);
}
.profile-avatar-lg {
  width: 64px; height: 64px;
  border-radius: 50%;
  background: var(--blue);
  color: #fff;
  display: flex; align-items: center; justify-content: center;
  font-size: 22px; font-weight: 700; flex-shrink: 0;
}
.profile-header-info { flex: 1; }
.profile-header-name  { font-size: 20px; font-weight: 700; color: var(--text); }
.profile-header-email { font-size: 13px; color: var(--muted); margin-top: 3px; }
.profile-header-affil { font-size: 12.5px; color: var(--muted); margin-top: 2px; }
.profile-header-country {
  display: inline-flex; align-items: center; gap: 5px;
  margin-top: 6px; background: #EFF6FF;
  border: 1px solid #BFDBFE; color: #1D4ED8;
  border-radius: 20px; padding: 3px 10px;
  font-size: 12px; font-weight: 600;
}

/* Stats row */
.profile-stats {
  display: flex; gap: 1px;
  background: var(--border); border-radius: 8px;
  overflow: hidden; margin-bottom: 20px;
}
.profile-stat { flex: 1; background: var(--white); text-align: center; padding: 16px 12px; }
.profile-stat-val { font-size: 22px; font-weight: 700; color: var(--text); }
.profile-stat-lbl { font-size: 12px; color: var(--muted); margin-top: 3px; }

/* Form card */
.form-card {
  background: var(--white); border: 1px solid var(--border);
  border-radius: 12px; overflow: hidden;
  box-shadow: 0 1px 4px rgba(0,0,0,.06);
}
.form-card-body { padding: 24px; }

.form-row-2 { display: grid; grid-template-columns: 1fr 1fr; gap: 16px; margin-bottom: 16px; }
.form-row-phone { display: grid; grid-template-columns: 130px 1fr; gap: 10px; }
@media(max-width:600px) {
  .form-row-2 { grid-template-columns: 1fr; }
  .form-row-phone { grid-template-columns: 1fr; }
}

.form-group { display: flex; flex-direction: column; gap: 5px; margin-bottom: 16px; }
.form-group:last-child { margin-bottom: 0; }
.form-label {
  font-size: 13px; font-weight: 600; color: var(--text);
  display: flex; align-items: center; gap: 5px;
}
.form-label .req { color: #DC2626; font-size: 11px; }
.form-label .lbl-opt { font-weight: 400; color: var(--muted); font-size: 11.5px; }
.form-input, .form-select, .form-textarea {
  width: 100%; padding: 9px 13px;
  border: 1.5px solid var(--border);
  border-radius: 8px;
  font-family: var(--font); font-size: 13.5px;
  color: var(--text); background: var(--white);
  outline: none; transition: border-color .15s;
}
.form-input:focus, .form-select:focus, .form-textarea:focus {
  border-color: var(--teal);
  box-shadow: 0 0 0 3px rgba(26,127,142,.1);
}
.form-input[readonly], .form-input:disabled {
  background: #F9FAFB; color: var(--muted); cursor: default;
}
.form-textarea { resize: vertical; min-height: 88px; line-height: 1.6; }

/* Country hint box */
.country-hint {
  display: none;
  margin-top: 8px;
  background: #F0FDF4; border: 1px solid #BBF7D0;
  border-radius: 8px; padding: 8px 12px;
  font-size: 12px; color: #15803D; font-weight: 500;
}
.country-hint.show { display: flex; align-items: center; gap: 6px; }

/* Save button */
.btn-save-profile {
  width: 100%; padding: 13px;
  background: var(--blue); color: #fff; border: none;
  border-radius: 8px;
  font-family: var(--font); font-size: 14px; font-weight: 700;
  cursor: pointer; transition: background .15s;
  display: flex; align-items: center; justify-content: center; gap: 8px;
  margin-top: 20px;
}
.btn-save-profile:hover { background: #132B50; }
.btn-save-profile:disabled { opacity: .6; cursor: not-allowed; }

.form-section-title {
  font-size: 12px; font-weight: 700; color: var(--muted);
  text-transform: uppercase; letter-spacing: .5px;
  padding-bottom: 10px; border-bottom: 1px solid var(--border);
  margin-bottom: 16px;
}

.form-err { font-size: 12px; color: #DC2626; margin-top: 3px; display: none; }
.form-err.show { display: block; }
.save-success { display: none; align-items: center; gap: 8px; font-size: 13px; color: #16A34A; font-weight: 600; margin-top: 10px; }
.save-success.show { display: flex; }

.toast-wrap { position: fixed; bottom: 24px; right: 24px; display: flex; flex-direction: column; gap: 8px; z-index: 9999; }
.toast { padding: 11px 16px; border-radius: 8px; font-size: 13px; font-weight: 500; color: #fff; box-shadow: 0 4px 14px rgba(0,0,0,.18); display: flex; align-items: center; gap: 8px; animation: tup .25s ease; }
.ts { background: #1D8A5E; } .te { background: #DC2626; } .ti { background: var(--blue); }
@keyframes tup { from{opacity:0;transform:translateY(8px)} to{opacity:1;transform:translateY(0)} }
.spinner { display: inline-block; width: 16px; height: 16px; border: 2px solid rgba(255,255,255,.3); border-top-color: #fff; border-radius: 50%; animation: spin .6s linear infinite; }
@keyframes spin { to{transform:rotate(360deg)} }
</style>

<div class="profile-container">

  <!-- Profile header -->
  <div class="profile-header-card">
    <div class="profile-avatar-lg" id="avatarLg"><?= p($initials) ?></div>
    <div class="profile-header-info">
      <div class="profile-header-name" id="headerName"><?= p($fullName) ?></div>
      <div class="profile-header-email"><?= p($u['email'] ?? '') ?></div>
      <?php if ($affilName): ?>
      <div class="profile-header-affil">🏛 <?= p($affilName) ?></div>
      <?php endif; ?>
      <?php if (!empty($u['country'])): ?>
      <div class="profile-header-country" id="headerCountry">
        🌍 <?= p($u['country']) ?>
      </div>
      <?php else: ?>
      <div class="profile-header-country" id="headerCountry" style="display:none">
        🌍 <span id="headerCountryText"></span>
      </div>
      <?php endif; ?>
    </div>
  </div>

  <!-- Stats -->
  <div class="profile-stats">
    <div class="profile-stat">
      <div class="profile-stat-val"><?= $totalSubs ?></div>
      <div class="profile-stat-lbl">Submissions</div>
    </div>
    <div class="profile-stat">
      <div class="profile-stat-val"><?= $corrCount ?></div>
      <div class="profile-stat-lbl">Corresponding</div>
    </div>
    <div class="profile-stat">
      <div class="profile-stat-val"><?= $acceptedCount ?></div>
      <div class="profile-stat-lbl">Accepted</div>
    </div>
  </div>

  <!-- Edit form -->
  <div class="form-card">
    <div class="form-card-body">

      <div class="form-section-title">Personal Information</div>

      <!-- Name row -->
      <div class="form-row-2">
        <div class="form-group">
          <label class="form-label" for="firstName">First Name <span class="req">*</span></label>
          <input type="text" class="form-input" id="firstName"
                 placeholder="First name" value="<?= p($u['first_name'] ?? '') ?>"
                 oninput="clearNameErr()">
          <div class="form-err" id="firstNameErr">Please enter your first name</div>
        </div>
        <div class="form-group">
          <label class="form-label" for="lastName">Last Name <span class="req">*</span></label>
          <input type="text" class="form-input" id="lastName"
                 placeholder="Last name" value="<?= p($u['last_name'] ?? '') ?>"
                 oninput="clearNameErr()">
          <div class="form-err" id="lastNameErr">Please enter your last name</div>
        </div>
      </div>

      <!-- Title + Email row -->
      <div class="form-row-2">
        <div class="form-group">
          <label class="form-label" for="title">Title</label>
          <select class="form-select" id="title">
            <?php foreach ($titles as $t): ?>
            <option value="<?= $t ?>" <?= ($u['title'] ?? '') === $t ? 'selected' : '' ?>>
              <?= $t ?: '— Select title —' ?>
            </option>
            <?php endforeach; ?>
          </select>
        </div>
        <div class="form-group">
          <label class="form-label">Email <span class="lbl-opt">(read-only)</span></label>
          <input type="email" class="form-input" value="<?= p($u['email'] ?? '') ?>" readonly>
        </div>
      </div>

      <!-- Phone row -->
      <div class="form-group">
        <label class="form-label" for="phoneNum">Phone Number</label>
        <div class="form-row-phone">
          <select class="form-select" id="phoneCode">
            <?php foreach ($phoneCodes as $code => $label): ?>
            <option value="<?= $code ?>"
              <?= ($u['phone_country_code'] ?? '+91') === $code ? 'selected' : '' ?>>
              <?= $code ?> <?= $label ?>
            </option>
            <?php endforeach; ?>
          </select>
          <input type="tel" class="form-input" id="phoneNum"
                 placeholder="Phone number"
                 value="<?= p($u['phone_number'] ?? '') ?>">
        </div>
      </div>

      <!-- Institutional Email -->
      <div class="form-group">
        <label class="form-label" for="instEmail">Institutional Email <span class="lbl-opt">(optional)</span></label>
        <input type="email" class="form-input" id="instEmail"
               placeholder="your@institution.edu"
               value="<?= p($u['institutional_email'] ?? '') ?>">
      </div>

      <!-- Country -->
      <div class="form-group">
        <label class="form-label" for="country">
          Country <span class="req">*</span>
          <span class="lbl-opt">(determines payment currency)</span>
        </label>
        <select class="form-select" id="country" onchange="updateCountryHint()">
          <option value="">— Select your country —</option>
          <?php foreach ($countries as $c): ?>
          <option value="<?= p($c) ?>"
            <?= ($u['country'] ?? '') === $c ? 'selected' : '' ?>>
            <?= p($c) ?>
          </option>
          <?php endforeach; ?>
        </select>
        <div class="country-hint <?= !empty($u['country']) ? 'show' : '' ?>" id="countryHint">
          💳 <span id="countryHintText">
            <?php
            $ch = $country_currency_hint[$u['country'] ?? ''] ?? null;
            echo $ch ? p($ch) : ($u['country'] ? 'USD $ — All gateways' : '');
            ?>
          </span>
        </div>
        <div style="font-size:11.5px;color:var(--muted);margin-top:4px">
          Your country is used to show correct payment methods and local currency during fee payment.
        </div>
      </div>

      <div class="form-section-title" style="margin-top:24px">Additional Information</div>

      <!-- Reviewing Interests -->
      <div class="form-group">
        <label class="form-label" for="reviewingInterests">
          Reviewing Interests <span class="lbl-opt">(optional)</span>
        </label>
        <textarea class="form-textarea" id="reviewingInterests"
                  placeholder="e.g. Machine Learning, Climate Science"><?= p($u['reviewing_interests'] ?? '') ?></textarea>
        <div style="font-size:11.5px;color:var(--muted);margin-top:4px">Comma-separated topics</div>
      </div>

      <!-- Bio -->
      <div class="form-group">
        <label class="form-label" for="bio">Biography <span class="lbl-opt">(optional)</span></label>
        <textarea class="form-textarea" id="bio"
                  placeholder="Short professional biography..."><?= p($u['bio'] ?? '') ?></textarea>
      </div>

      <!-- Website -->
      <div class="form-group">
        <label class="form-label" for="website">Website / ORCID <span class="lbl-opt">(optional)</span></label>
        <input type="text" class="form-input" id="website"
               placeholder="https://orcid.org/0000-0000-0000-0000"
               value="<?= p($u['website'] ?? '') ?>">
      </div>

      <!-- Save button -->
      <button type="button" class="btn-save-profile" id="saveProfileBtn" onclick="saveProfile()">
        💾 Save Profile
      </button>

      <div class="save-success" id="saveSuccess">
        <span>✅</span> Profile saved successfully!
      </div>

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

<div class="toast-wrap" id="toastWrap"></div>

<script>
// Country currency hints
const countryCurrencyHints = {
    'India':                 '₹ INR — Razorpay only',
    'Bangladesh':            '৳ BDT — All gateways',
    'Nigeria':               '₦ NGN — All gateways + NGN Bank',
    'Pakistan':              'Rs PKR — All gateways',
    'Philippines':           '₱ PHP — All gateways + GCash',
    'Malaysia':              'RM MYR — All gateways',
    'Indonesia':             'Rp IDR — All gateways',
    'Sri Lanka':             'LKR — All gateways',
    'Kenya':                 'KSh KES — All gateways',
    'Ghana':                 '₵ GHS — All gateways',
    'Nepal':                 'Rs NPR — All gateways',
    'Ethiopia':              'Br ETB — All gateways',
    'Tanzania':              'TSh TZS — All gateways',
    'South Africa':          'R ZAR — All gateways',
    'Vietnam':               '₫ VND — All gateways',
    'China':                 '¥ CNY — All gateways',
    'Turkey':                '₺ TRY — All gateways',
    'Hungary':               'Ft HUF — All gateways',
    'Argentina':             'AR$ ARS — All gateways',
    'Uganda':                '$ USD $30 — All gateways',
};

function updateCountryHint() {
    const sel     = document.getElementById('country');
    const country = sel.value;
    const hint    = document.getElementById('countryHint');
    const hintTxt = document.getElementById('countryHintText');
    const hdrCountry     = document.getElementById('headerCountry');
    const hdrCountryText = document.getElementById('headerCountryText');

    if (country) {
        const msg = countryCurrencyHints[country] || '$ USD — All gateways';
        hintTxt.textContent = msg;
        hint.classList.add('show');
        // Update header badge
        hdrCountryText.textContent = country;
        hdrCountry.style.display = 'inline-flex';
        // If badge has direct text (not via span)
        if (!hdrCountry.querySelector('span')) {
            hdrCountry.textContent = '🌍 ' + country;
        }
    } else {
        hint.classList.remove('show');
    }
}

function clearNameErr() {
    document.getElementById('firstNameErr').classList.remove('show');
    document.getElementById('lastNameErr').classList.remove('show');
}

function saveProfile() {
    const firstName = document.getElementById('firstName').value.trim();
    const lastName  = document.getElementById('lastName').value.trim();
    let ok = true;

    if (!firstName) { document.getElementById('firstNameErr').classList.add('show'); ok = false; }
    else { document.getElementById('firstNameErr').classList.remove('show'); }
    if (!lastName)  { document.getElementById('lastNameErr').classList.add('show'); ok = false; }
    else { document.getElementById('lastNameErr').classList.remove('show'); }
    if (!ok) return;

    const btn = document.getElementById('saveProfileBtn');
    btn.disabled = true;
    btn.innerHTML = '<span class="spinner"></span> Saving...';
    document.getElementById('saveSuccess').classList.remove('show');

    const fd = new FormData();
    fd.append('ajax_save',           '1');
    fd.append('first_name',          firstName);
    fd.append('last_name',           lastName);
    fd.append('title',               document.getElementById('title').value);
    fd.append('phone_country_code',  document.getElementById('phoneCode').value);
    fd.append('phone_number',        document.getElementById('phoneNum').value.trim());
    fd.append('institutional_email', document.getElementById('instEmail').value.trim());
    fd.append('reviewing_interests', document.getElementById('reviewingInterests').value.trim());
    fd.append('bio',                 document.getElementById('bio').value.trim());
    fd.append('website',             document.getElementById('website').value.trim());
    fd.append('country',             document.getElementById('country').value);

    fetch('profile.php', { method: 'POST', body: fd })
    .then(r => r.json())
    .then(data => {
        btn.disabled = false;
        btn.innerHTML = '💾 Save Profile';
        if (data.success) {
            const fullName = (data.first_name + ' ' + data.last_name).trim();
            document.getElementById('headerName').textContent = fullName;
            const ini = ((data.first_name[0] || '') + (data.last_name[0] || '')).toUpperCase();
            document.getElementById('avatarLg').textContent = ini;

            // Update country badge in header
            const hdrCountry = document.getElementById('headerCountry');
            if (data.country) {
                hdrCountry.textContent = '🌍 ' + data.country;
                hdrCountry.style.display = 'inline-flex';
            }

            document.getElementById('saveSuccess').classList.add('show');
            setTimeout(() => document.getElementById('saveSuccess').classList.remove('show'), 4000);
            showToast('✅ Profile saved successfully!', 's');
        } else {
            showToast('❌ ' + (data.message || 'Save failed'), 'e');
        }
    })
    .catch(() => {
        btn.disabled = false;
        btn.innerHTML = '💾 Save Profile';
        showToast('❌ Network error — please try again', 'e');
    });
}

function showToast(msg, t = 'i') {
    const w = document.getElementById('toastWrap');
    const d = document.createElement('div');
    d.className = 'toast t' + t;
    d.textContent = msg;
    w.appendChild(d);
    setTimeout(() => d.remove(), 3500);
}
</script>

<?php layoutEnd(); ?>