<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

include(__DIR__ . "/config/db.php");
require_once __DIR__ . "/includes/rate_limit.php";

$step  = 1;
$phone = '';
$error = '';

// Country codes list
$countries = [
    ['code' => '+60',  'flag' => '🇲🇾', 'name' => 'Malaysia',     'digits' => '9,10',  'placeholder' => '123456789'],
    ['code' => '+65',  'flag' => '🇸🇬', 'name' => 'Singapore',    'digits' => '8',     'placeholder' => '81234567'],
    ['code' => '+62',  'flag' => '🇮🇩', 'name' => 'Indonesia',    'digits' => '9,13',  'placeholder' => '81234567890'],
    ['code' => '+66',  'flag' => '🇹🇭', 'name' => 'Thailand',     'digits' => '9',     'placeholder' => '812345678'],
    ['code' => '+44',  'flag' => '🇬🇧', 'name' => 'UK',           'digits' => '10',    'placeholder' => '7911123456'],
    ['code' => '+1',   'flag' => '🇺🇸', 'name' => 'USA/Canada',   'digits' => '10',    'placeholder' => '2025551234'],
    ['code' => '+61',  'flag' => '🇦🇺', 'name' => 'Australia',    'digits' => '9',     'placeholder' => '412345678'],
    ['code' => '+91',  'flag' => '🇮🇳', 'name' => 'India',        'digits' => '10',    'placeholder' => '9876543210'],
    ['code' => '+86',  'flag' => '🇨🇳', 'name' => 'China',        'digits' => '11',    'placeholder' => '13812345678'],
    ['code' => '+81',  'flag' => '🇯🇵', 'name' => 'Japan',        'digits' => '10,11', 'placeholder' => '9012345678'],
];

$countriesForJs = array_map(function ($c) {
    return [
        'code'        => $c['code'],
        'flag'        => $c['flag'],
        'name'        => $c['name'],
        'placeholder' => $c['placeholder'],
    ];
}, $countries);

if ($_POST) {

    $ip = $_SERVER['REMOTE_ADDR'] ?? 'unknown';
    $retry = rate_limit_check('user_login', $ip, 10, 300);
    if ($retry !== null) {
        rate_limit_respond($retry, 'html');
    }

    if (isset($_POST['check_phone'])) {
        $dialCode = trim($_POST['dial_code'] ?? '+60');
        $local    = preg_replace('/\D/', '', trim($_POST['phone'] ?? ''));

        // Strip leading zero from local number (e.g. 0123 → 123 before prepending +60)
        $localStripped = ltrim($local, '0');

        // Full E.164-style number stored without +, e.g. 60123456789
        $fullPhone = ltrim($dialCode, '+') . $localStripped;

        if (empty($local) || strlen($local) < 7 || strlen($local) > 15) {
            $error = "Please enter a valid phone number.";
        } else {
            $phone = $local; // keep local for display in step 2
            $_POST['dial_code_saved'] = $dialCode;

            $stmt = $conn->prepare("SELECT * FROM customers WHERE phone=?");
            $stmt->bind_param("s", $fullPhone);
            $stmt->execute();
            $result = $stmt->get_result();
            if ($result->num_rows > 0) {
                $user = $result->fetch_assoc();
                $_SESSION['user'] = $user;
                header("Location: user/index.php");
                exit();
            } else {
                // Also try matching against old local format in DB
                $stmt2 = $conn->prepare("SELECT * FROM customers WHERE phone=?");
                $stmt2->bind_param("s", $local);
                $stmt2->execute();
                $result2 = $stmt2->get_result();
                if ($result2->num_rows > 0) {
                    $user = $result2->fetch_assoc();
                    $_SESSION['user'] = $user;
                    header("Location: user/index.php");
                    exit();
                }
                $step = 2;
            }
        }
    }

    if (isset($_POST['create_user'])) {
        $dialCode  = trim($_POST['dial_code'] ?? '+60');
        $local     = preg_replace('/\D/', '', trim($_POST['phone'] ?? ''));
        $localStripped = ltrim($local, '0');
        $fullPhone = ltrim($dialCode, '+') . $localStripped;
        $phone     = $local;

        if (empty($local) || strlen($local) < 7) {
            $error = "Invalid phone number.";
            $step  = 1;
        } else {
            $name = substr(strip_tags(trim($_POST['name'] ?? '')), 0, 100);
            if (empty($name)) {
                $error = "Name is required.";
                $step  = 2;
            } else {
                $chk = $conn->prepare("SELECT id FROM customers WHERE phone=? OR phone=? LIMIT 1");
                $chk->bind_param("ss", $fullPhone, $local);
                $chk->execute();
                if ($chk->get_result()->num_rows > 0) {
                    $stmt = $conn->prepare("SELECT * FROM customers WHERE phone=? OR phone=? LIMIT 1");
                    $stmt->bind_param("ss", $fullPhone, $local);
                    $stmt->execute();
                    $user = $stmt->get_result()->fetch_assoc();
                    $_SESSION['user'] = $user;
                } else {
                    $stmt = $conn->prepare("INSERT INTO customers (name, phone) VALUES (?, ?)");
                    $stmt->bind_param("ss", $name, $fullPhone);
                    $stmt->execute();
                    $_SESSION['user'] = ['name' => $name, 'phone' => $fullPhone];
                }
                header("Location: user/index.php");
                exit();
            }
        }
    }
}

$savedDial  = htmlspecialchars($_POST['dial_code_saved'] ?? $_POST['dial_code'] ?? '+60');
$savedLocal = htmlspecialchars($phone);
?>
<!DOCTYPE html>
<html lang="ms">
<head>
    <title>VoucherHub</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
    <style>
        *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }

        :root {
            --bg: #f5f6fa;
            --white: #ffffff;
            --accent: #4f46e5;
            --accent-hover: #4338ca;
            --accent-light: rgba(79,70,229,0.08);
            --text: #111827;
            --muted: #6b7280;
            --border: #e5e7eb;
            --red: #dc2626;
            --red-bg: #fef2f2;
            --red-border: #fecaca;
            --font: 'Inter', sans-serif;
        }

        body {
            font-family: var(--font);
            background: var(--bg);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
            padding: 20px;
            -webkit-font-smoothing: antialiased;
        }

        .card {
            background: var(--white);
            border: 1px solid var(--border);
            border-radius: 20px;
            padding: 36px 32px 32px;
            width: 100%;
            max-width: 380px;
            box-shadow: 0 4px 24px rgba(0,0,0,.06);
        }

        /* Brand */
        .brand { text-align: center; margin-bottom: 28px; }
        .brand-icon {
            width: 56px; height: 56px;
            background: var(--accent);
            border-radius: 16px;
            display: inline-grid; place-items: center;
            margin-bottom: 14px;
        }
        .brand-icon i { font-size: 24px; color: #fff; }
        .brand-title { font-size: 20px; font-weight: 700; color: var(--text); letter-spacing: -.3px; }
        .brand-sub { font-size: 13.5px; color: var(--muted); margin-top: 4px; }

        /* Steps */
        .steps { display: flex; align-items: center; gap: 6px; justify-content: center; margin-bottom: 24px; }
        .step-dot { height: 6px; width: 6px; border-radius: 3px; background: var(--border); transition: background .2s, width .25s; }
        .step-dot.active { background: var(--accent); width: 22px; }

        /* Headings */
        .section-title { font-size: 15px; font-weight: 600; color: var(--text); margin-bottom: 4px; }
        .section-sub { font-size: 13px; color: var(--muted); margin-bottom: 20px; line-height: 1.5; }

        /* Back */
        .back-link {
            display: inline-flex; align-items: center; gap: 5px;
            font-size: 12.5px; font-weight: 600; color: var(--muted);
            text-decoration: none; margin-bottom: 16px; transition: color .15s;
        }
        .back-link:hover { color: var(--text); }

        /* Phone chip (step 2) */
        .phone-chip {
            display: inline-flex; align-items: center; gap: 7px;
            background: var(--accent-light);
            border: 1px solid rgba(79,70,229,.18);
            border-radius: 100px;
            padding: 5px 13px 5px 9px;
            font-size: 13px; font-weight: 600; color: var(--accent);
            margin-bottom: 16px;
        }
        .phone-chip i { font-size: 13px; }

        /* Error */
        .alert-error {
            background: var(--red-bg); border: 1px solid var(--red-border);
            color: var(--red); border-radius: 10px; padding: 10px 14px;
            font-size: 13px; font-weight: 500;
            display: flex; align-items: flex-start; gap: 9px;
            margin-bottom: 16px; line-height: 1.5;
        }
        .alert-error i { flex-shrink: 0; margin-top: 1px; font-size: 14px; }

        /* Label */
        label {
            display: block; font-size: 11.5px; font-weight: 600;
            text-transform: uppercase; letter-spacing: .55px;
            color: var(--muted); margin-bottom: 7px;
        }

        /* ── Phone row: country selector + number input ── */
        .phone-row { display: flex; gap: 8px; margin-bottom: 14px; }

        .country-btn {
            flex-shrink: 0;
            display: flex; align-items: center; gap: 6px;
            border: 1.5px solid var(--border);
            border-radius: 10px;
            background: var(--white);
            padding: 0 12px;
            height: 48px;
            cursor: pointer;
            font-family: var(--font);
            font-size: 14px; font-weight: 600;
            color: var(--text);
            transition: border-color .18s, box-shadow .18s;
            white-space: nowrap;
            position: relative;
        }
        .country-btn:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(79,70,229,.12); }
        .country-btn .flag { font-size: 18px; line-height: 1; }
        .country-btn .dial { font-size: 13px; color: var(--muted); }
        .country-btn .chevron { font-size: 11px; color: var(--muted); margin-left: 1px; }

        .phone-input-wrap { flex: 1; position: relative; }
        .phone-input-wrap input {
            width: 100%; height: 48px;
            border: 1.5px solid var(--border);
            border-radius: 10px;
            padding: 0 14px;
            font-size: 15px; font-family: var(--font); color: var(--text);
            background: var(--white);
            transition: border-color .18s, box-shadow .18s;
            -webkit-appearance: none;
        }
        .phone-input-wrap input:focus {
            outline: none; border-color: var(--accent);
            box-shadow: 0 0 0 3px rgba(79,70,229,.12);
        }
        .phone-input-wrap input::placeholder { color: #c4c8d4; }

        /* Country dropdown */
        .country-dropdown {
            position: absolute;
            top: calc(100% + 6px);
            left: 0;
            width: 260px;
            background: var(--white);
            border: 1px solid var(--border);
            border-radius: 12px;
            box-shadow: 0 8px 32px rgba(0,0,0,.12);
            z-index: 100;
            overflow: hidden;
            display: none;
        }
        .country-dropdown.open { display: block; }
        .country-option {
            display: flex; align-items: center; gap: 10px;
            padding: 10px 14px;
            cursor: pointer;
            font-size: 13.5px; font-weight: 500; color: var(--text);
            transition: background .12s;
        }
        .country-option:hover { background: var(--bg); }
        .country-option.selected { background: var(--accent-light); color: var(--accent); }
        .country-option .flag { font-size: 19px; }
        .country-option .name { flex: 1; }
        .country-option .code { font-size: 12px; color: var(--muted); font-weight: 600; }

        /* Generic input wrap (for name field) */
        .input-wrap { position: relative; margin-bottom: 14px; }
        .input-wrap i {
            position: absolute; left: 14px; top: 50%; transform: translateY(-50%);
            color: #c0c4ce; font-size: 16px; pointer-events: none; transition: color .18s;
        }
        .input-wrap:focus-within i { color: var(--accent); }
        .input-wrap input {
            width: 100%; border: 1.5px solid var(--border); border-radius: 10px;
            padding: 12px 14px 12px 42px; font-size: 15px;
            font-family: var(--font); color: var(--text); background: var(--white);
            transition: border-color .18s, box-shadow .18s; -webkit-appearance: none;
        }
        .input-wrap input:focus { outline: none; border-color: var(--accent); box-shadow: 0 0 0 3px rgba(79,70,229,.12); }
        .input-wrap input::placeholder { color: #c4c8d4; }

        /* Button */
        .btn {
            width: 100%; background: var(--accent); color: #fff;
            border: none; border-radius: 10px; padding: 13px;
            font-size: 15px; font-weight: 600; font-family: var(--font);
            cursor: pointer; display: flex; align-items: center; justify-content: center;
            gap: 8px; transition: background .18s, transform .1s, opacity .18s;
            margin-top: 6px; position: relative;
        }
        .btn:hover:not(:disabled) { background: var(--accent-hover); }
        .btn:active:not(:disabled) { transform: scale(.98); }
        .btn:disabled { opacity: .65; cursor: not-allowed; }

        /* Spinner */
        .btn .spinner {
            width: 16px; height: 16px;
            border: 2.5px solid rgba(255,255,255,.35);
            border-top-color: #fff;
            border-radius: 50%;
            animation: spin .65s linear infinite;
            display: none;
            flex-shrink: 0;
        }
        .btn.loading .spinner { display: block; }
        .btn.loading .btn-label { opacity: 0; }
        .btn.loading .btn-icon { display: none; }

        @keyframes spin { to { transform: rotate(360deg); } }

        /* Footer */
        .footer-note {
            text-align: center; font-size: 12px; color: #9ca3af;
            margin-top: 18px; line-height: 1.6; max-width: 300px;
        }

        @media (max-width: 400px) {
            .card { padding: 26px 18px 22px; border-radius: 16px; }
            .country-dropdown { width: 240px; }
        }
    </style>
</head>
<body>

<div class="card">

    <div class="brand">
        <div class="brand-icon"><i class="bi bi-ticket-perforated-fill"></i></div>
        <div class="brand-title">VoucherHub</div>
        <div class="brand-sub">Access your exclusive vouchers</div>
    </div>

    <div class="steps">
        <div class="step-dot <?= $step == 1 ? 'active' : '' ?>"></div>
        <div class="step-dot <?= $step == 2 ? 'active' : '' ?>"></div>
    </div>

    <?php if ($error): ?>
    <div class="alert-error">
        <i class="bi bi-exclamation-circle-fill"></i>
        <?= htmlspecialchars($error) ?>
    </div>
    <?php endif; ?>

    <!-- STEP 1 -->
    <?php if ($step == 1): ?>
    <div class="section-title">Enter your phone number</div>
    <div class="section-sub">We'll look up your account or help you create one.</div>
    <form method="POST" id="form1" onsubmit="submitWithLoading(this, 'btn1')">
        <input type="hidden" name="check_phone" value="1">
        <input type="hidden" name="dial_code" id="dial_code_input" value="<?= $savedDial ?>">
        <label>Phone Number</label>
        <div class="phone-row">
            <!-- Country selector -->
            <div style="position:relative">
                <button type="button" class="country-btn" id="country-btn" onclick="toggleDropdown()" aria-haspopup="listbox">
                    <span class="flag" id="sel-flag">🇲🇾</span>
                    <span class="dial" id="sel-code">+60</span>
                    <i class="bi bi-chevron-down chevron"></i>
                </button>
                <div class="country-dropdown" id="country-dropdown" role="listbox">
                    <?php foreach ($countries as $c): ?>
                    <div class="country-option <?= ($savedDial === $c['code']) ? 'selected' : '' ?>"
                         role="option"
                         onclick="selectCountry('<?= $c['code'] ?>','<?= $c['flag'] ?>','<?= addslashes($c['name']) ?>','<?= $c['placeholder'] ?>')">
                        <span class="flag"><?= $c['flag'] ?></span>
                        <span class="name"><?= htmlspecialchars($c['name']) ?></span>
                        <span class="code"><?= $c['code'] ?></span>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <!-- Number input -->
            <div class="phone-input-wrap">
                <input type="tel" name="phone" id="phone-input"
                    placeholder="123456789"
                    value="<?= $savedLocal ?>"
                    inputmode="numeric"
                    autocomplete="tel-national"
                    required>
            </div>
        </div>
        <button type="submit" id="btn1" class="btn">
            <span class="spinner"></span>
            <span class="btn-label">Continue</span>
            <i class="bi bi-arrow-right btn-icon"></i>
        </button>
    </form>
    <?php endif; ?>

    <!-- STEP 2 -->
    <?php if ($step == 2): ?>
    <a href="?" class="back-link"><i class="bi bi-arrow-left"></i> Back</a>
    <div class="phone-chip">
        <i class="bi bi-telephone-fill"></i>
        <?= htmlspecialchars($savedDial) ?> <?= htmlspecialchars($phone) ?>
    </div>
    <div class="section-title">Create your account</div>
    <div class="section-sub">This number isn't registered yet. Enter your name to get started.</div>
    <form method="POST" id="form2" onsubmit="submitWithLoading(this, 'btn2')">
        <input type="hidden" name="create_user" value="1">
        <input type="hidden" name="phone" value="<?= htmlspecialchars($phone) ?>">
        <input type="hidden" name="dial_code" value="<?= $savedDial ?>">
        <label for="name">Full Name</label>
        <div class="input-wrap">
            <i class="bi bi-person-fill"></i>
            <input type="text" id="name" name="name"
                placeholder="Your full name"
                maxlength="100"
                autocomplete="name"
                required>
        </div>
        <button type="submit" id="btn2" class="btn">
            <span class="spinner"></span>
            <span class="btn-label">Create Account</span>
            <i class="bi bi-check2 btn-icon"></i>
        </button>
    </form>
    <?php endif; ?>

</div>

<div class="footer-note">
    Your phone number is only used to access your vouchers.
</div>

<script>
// ── Country selector ──
const countries = <?= json_encode($countriesForJs, JSON_UNESCAPED_UNICODE) ?>;

let selectedCode = '<?= $savedDial ?>';

function toggleDropdown() {
    document.getElementById('country-dropdown').classList.toggle('open');
}

function selectCountry(code, flag, name, placeholder) {
    selectedCode = code;
    document.getElementById('sel-flag').textContent = flag;
    document.getElementById('sel-code').textContent = code;
    document.getElementById('dial_code_input').value = code;
    document.getElementById('phone-input').placeholder = placeholder;
    document.querySelectorAll('.country-option').forEach(el => el.classList.remove('selected'));
    event.currentTarget.classList.add('selected');
    document.getElementById('country-dropdown').classList.remove('open');
    document.getElementById('phone-input').focus();
}

// Close dropdown when clicking outside
document.addEventListener('click', function(e) {
    if (!e.target.closest('#country-btn') && !e.target.closest('#country-dropdown')) {
        document.getElementById('country-dropdown')?.classList.remove('open');
    }
});

// ── Button loading state ──
function submitWithLoading(form, btnId) {
    const btn = document.getElementById(btnId);
    if (!form.checkValidity()) return;
    btn.disabled = true;
    btn.classList.add('loading');
}

// Init: set correct flag/code from saved value
(function() {
    const saved = '<?= $savedDial ?>';
    const match = countries.find(c => c.code === saved);
    if (match && document.getElementById('sel-flag')) {
        document.getElementById('sel-flag').textContent = match.flag;
        document.getElementById('sel-code').textContent = match.code;
        document.getElementById('phone-input').placeholder = match.placeholder;
    }
})();
</script>

</body>
</html>
