<?php
// ========================================
// صفحه ورود — شیشه‌ای + کپچای محلی
// ========================================
require_once 'config/database.php';
require_once 'config/settings.php';
require_once 'includes/auth.php';
require_once 'includes/functions.php';

$pageTitle = 'ورود | کیف‌لند';
$error = '';
if (Auth::isLoggedIn()) { header('Location: index.php'); exit; }

$ip = $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';

// ساخت کپچا
function generateCaptcha(): array {
    $ops = [
        [rand(1,9), rand(1,9), '+'],
        [rand(5,15), rand(1,9), '-'],
        [rand(2,9), rand(2,5), '×'],
    ];
    $op  = $ops[array_rand($ops)];
    $ans = match($op[2]) {
        '+' => $op[0] + $op[1],
        '-' => $op[0] - $op[1],
        '×' => $op[0] * $op[1],
    };
    return ['q' => $op[0] . ' ' . $op[2] . ' ' . $op[1], 'a' => $ans];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // بررسی CSRF
    if (!Auth::verifyCSRFToken($_POST['csrf_token'] ?? '')) {
        $error = 'خطای امنیتی. صفحه را رفرش کنید.';
    }
    // rate limit
    elseif (Auth::isRateLimited($ip)) {
        $mins  = Auth::getRemainingLockout($ip);
        $error = "حساب موقتاً قفل شده. $mins دقیقه دیگر تلاش کنید.";
    }
    // بررسی کپچا
    elseif ((int)($_POST['captcha'] ?? -999) !== (int)($_SESSION['captcha_answer'] ?? -1)) {
        $error = 'پاسخ سوال امنیتی اشتباه است.';
        Auth::recordFailedLogin($ip);
    }
    else {
        $email    = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
        $password = $_POST['password'] ?? '';
        $remember = isset($_POST['remember']);

        if (empty($email) || empty($password)) {
            $error = 'ایمیل و رمز عبور را وارد کنید.';
        } elseif (!Auth::validateEmail($email)) {
            $error = 'ایمیل معتبر نیست.';
        } else {
            $result = Auth::login($email, $password, $remember);
            if ($result === true) {
                unset($_SESSION['captcha_answer']);
                $redirect = $_SESSION['redirect_after_login'] ?? 'index.php';
                unset($_SESSION['redirect_after_login']);
                header('Location: ' . $redirect); exit;
            } elseif ($result === 'inactive') {
                $error = 'حساب شما غیرفعال شده. با پشتیبانی تماس بگیرید.';
            } elseif ($result === 'rate_limited') {
                $mins  = Auth::getRemainingLockout($ip);
                $error = "حساب قفل شده. $mins دقیقه دیگر تلاش کنید.";
            } else {
                $error = 'ایمیل یا رمز عبور اشتباه است.';
            }
        }
    }
}

// ساخت کپچای جدید
$captcha = generateCaptcha();
$_SESSION['captcha_answer'] = $captcha['a'];
$csrfToken = Auth::generateCSRFToken();
?>
<!DOCTYPE html>
<html lang="fa" dir="rtl" data-theme="light">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><?= htmlspecialchars($pageTitle) ?></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<link href="https://cdn.jsdelivr.net/gh/rastikerdar/vazirmatn@v33.003/Vazirmatn-font-face.css" rel="stylesheet">
<style>
*, *::before, *::after { margin:0; padding:0; box-sizing:border-box; }
:root {
    --primary: #7c3aed;
    --primary-hover: #6d28d9;
    --primary-glow: rgba(124,58,237,0.25);
    --danger: #ef4444;
    --text-primary: #1e1b4b;
    --text-secondary: #6b7280;
    --glass-border: rgba(255,255,255,0.7);
}
body {
    font-family: 'Vazirmatn', system-ui, sans-serif;
    min-height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 20px;
    position: relative;
    overflow: hidden;
    background: #f3f0ff;
    color: var(--text-primary);
}

/* پس‌زمینه زنده */
body::before {
    content: '';
    position: fixed;
    inset: -20%;
    width: 140%; height: 140%;
    background:
        radial-gradient(ellipse at 20% 20%, rgba(139,92,246,0.22) 0%, transparent 50%),
        radial-gradient(ellipse at 80% 80%, rgba(99,102,241,0.18) 0%, transparent 50%),
        radial-gradient(ellipse at 60% 10%, rgba(167,139,250,0.15) 0%, transparent 45%),
        linear-gradient(160deg, #ede9fe 0%, #f3f0ff 50%, #fdf4ff 100%);
    z-index: -1;
    animation: bgMove 20s ease-in-out infinite alternate;
}
@keyframes bgMove {
    0%   { transform: translate(0,0) scale(1); }
    100% { transform: translate(-2%,-2%) scale(1.03); }
}

/* ذرات شناور */
.particles { position:fixed; inset:0; z-index:0; pointer-events:none; overflow:hidden; }
.particle {
    position: absolute;
    border-radius: 50%;
    background: rgba(139,92,246,0.12);
    animation: particleFloat linear infinite;
}

@keyframes particleFloat {
    0%   { transform: translateY(100vh) scale(0); opacity:0; }
    10%  { opacity:1; }
    90%  { opacity:1; }
    100% { transform: translateY(-100px) scale(1); opacity:0; }
}

/* کارت اصلی */
.login-wrap {
    position: relative;
    z-index: 1;
    width: 100%;
    max-width: 420px;
}

.login-card {
    background: rgba(255,255,255,0.52);
    backdrop-filter: blur(32px) saturate(200%);
    -webkit-backdrop-filter: blur(32px) saturate(200%);
    border: 1px solid rgba(255,255,255,0.75);
    border-radius: 28px;
    padding: 40px 36px 36px;
    box-shadow:
        0 8px 40px rgba(109,40,217,0.1),
        0 2px 8px rgba(0,0,0,0.04),
        inset 0 1px 0 rgba(255,255,255,0.98);
    position: relative;
    overflow: hidden;
}

/* خط نور بالا */
.login-card::before {
    content: '';
    position: absolute;
    top: 0; left: 10%; right: 10%; height: 1px;
    background: linear-gradient(90deg, transparent, rgba(139,92,246,0.5), transparent);
}

/* دایره تزئینی */
.login-card::after {
    content: '';
    position: absolute;
    bottom: -80px; left: -80px;
    width: 200px; height: 200px;
    background: radial-gradient(circle, rgba(139,92,246,0.08), transparent 70%);
    border-radius: 50%;
    pointer-events: none;
}

/* لوگو */
.login-logo {
    text-align: center;
    margin-bottom: 28px;
}
.logo-icon {
    width: 64px; height: 64px;
    background: linear-gradient(135deg, #8b5cf6, #7c3aed);
    border-radius: 18px;
    display: inline-flex;
    align-items: center;
    justify-content: center;
    font-size: 1.6rem;
    color: #fff;
    margin-bottom: 12px;
    box-shadow: 0 8px 24px rgba(124,58,237,0.35), inset 0 1px 0 rgba(255,255,255,0.2);
}
.login-logo h1 {
    font-size: 1.3rem;
    font-weight: 800;
    background: linear-gradient(135deg, #7c3aed, #4f46e5);
    -webkit-background-clip: text;
    background-clip: text;
    color: transparent;
    margin-bottom: 4px;
}
.login-logo p {
    font-size: 0.82rem;
    color: var(--text-secondary);
}

/* alert */
.alert-err {
    background: rgba(239,68,68,0.08);
    border: 1px solid rgba(239,68,68,0.25);
    color: #b91c1c;
    padding: 11px 14px;
    border-radius: 12px;
    font-size: 0.83rem;
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    gap: 8px;
    animation: shake 0.4s ease;
}
@keyframes shake {
    0%,100%{transform:translateX(0)}
    20%{transform:translateX(-6px)}
    40%{transform:translateX(6px)}
    60%{transform:translateX(-4px)}
    80%{transform:translateX(4px)}
}

/* فرم */
.form { display:flex; flex-direction:column; gap:16px; }

.field { display:flex; flex-direction:column; gap:6px; }
.field label {
    font-size: 0.8rem;
    font-weight: 600;
    color: var(--text-secondary);
    padding-right: 4px;
}

.input-wrap {
    position: relative;
    display: flex;
    align-items: center;
}
.input-wrap .fi {
    position: absolute;
    right: 14px;
    color: rgba(124,58,237,0.45);
    font-size: 0.9rem;
    pointer-events: none;
    transition: color 0.2s;
}
.input-wrap input {
    width: 100%;
    padding: 12px 40px 12px 14px;
    background: rgba(255,255,255,0.55);
    border: 1.5px solid rgba(139,92,246,0.15);
    border-radius: 14px;
    font-family: inherit;
    font-size: 0.92rem;
    color: var(--text-primary);
    transition: all 0.25s;
    outline: none;
}
.input-wrap input::placeholder { color: rgba(107,114,128,0.5); }
.input-wrap input:focus {
    border-color: var(--primary);
    background: rgba(255,255,255,0.8);
    box-shadow: 0 0 0 4px rgba(124,58,237,0.1), 0 2px 8px rgba(124,58,237,0.08);
}
.input-wrap input:focus + .fi { color: var(--primary); }
.input-wrap .fi { right: 14px; left: auto; }
/* آیکون چشم */
.eye-btn {
    position: absolute;
    left: 12px;
    background: none;
    border: none;
    color: var(--text-secondary);
    cursor: pointer;
    font-size: 0.85rem;
    padding: 4px;
    transition: color 0.2s;
}
.eye-btn:hover { color: var(--primary); }

/* ردیف چک‌باکس + فراموشی */
.row-between {
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.check-label {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 0.8rem;
    color: var(--text-secondary);
    cursor: pointer;
    user-select: none;
}
.check-label input[type=checkbox] { display:none; }
.custom-check {
    width: 18px; height: 18px;
    border: 1.5px solid rgba(139,92,246,0.3);
    border-radius: 6px;
    background: rgba(255,255,255,0.6);
    display: flex; align-items:center; justify-content:center;
    transition: all 0.2s;
    flex-shrink: 0;
}
.check-label input:checked ~ .custom-check {
    background: var(--primary);
    border-color: var(--primary);
}
.check-label input:checked ~ .custom-check::after {
    content: '✓';
    color: #fff;
    font-size: 0.7rem;
    font-weight: 700;
}
.forgot-link {
    font-size: 0.8rem;
    color: var(--primary);
    text-decoration: none;
    font-weight: 600;
    transition: opacity 0.2s;
}
.forgot-link:hover { opacity: 0.75; }

/* کپچا */
.captcha-box {
    background: rgba(255,255,255,0.4);
    border: 1.5px solid rgba(139,92,246,0.15);
    border-radius: 14px;
    padding: 14px;
    display: flex;
    align-items: center;
    gap: 12px;
}
.captcha-question {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 10px;
}
.captcha-math {
    background: linear-gradient(135deg, #7c3aed, #4f46e5);
    color: #fff;
    padding: 10px 16px;
    border-radius: 10px;
    font-size: 1.1rem;
    font-weight: 800;
    letter-spacing: 2px;
    box-shadow: 0 4px 12px rgba(124,58,237,0.3);
    font-family: monospace;
    white-space: nowrap;
    position: relative;
    overflow: hidden;
    user-select: none;
}
/* نویز روی کپچا */
.captcha-math::before {
    content: '';
    position: absolute;
    inset: 0;
    background: repeating-linear-gradient(
        45deg,
        rgba(255,255,255,0.05) 0px,
        rgba(255,255,255,0.05) 1px,
        transparent 1px,
        transparent 6px
    );
}
.captcha-math::after {
    content: '= ?';
    display: block;
    font-size: 0.7rem;
    opacity: 0.7;
    margin-top: 2px;
    letter-spacing: 1px;
}
.captcha-input {
    width: 80px;
    padding: 10px 12px;
    background: rgba(255,255,255,0.7);
    border: 1.5px solid rgba(139,92,246,0.2);
    border-radius: 10px;
    font-family: monospace;
    font-size: 1.1rem;
    font-weight: 700;
    text-align: center;
    color: var(--text-primary);
    transition: all 0.2s;
    outline: none;
    -moz-appearance: textfield;
}
.captcha-input::-webkit-inner-spin-button { display:none; }
.captcha-input:focus {
    border-color: var(--primary);
    box-shadow: 0 0 0 3px rgba(124,58,237,0.12);
    background: #fff;
}
.captcha-refresh {
    width: 36px; height: 36px;
    border-radius: 10px;
    background: rgba(139,92,246,0.08);
    border: 1px solid rgba(139,92,246,0.2);
    color: var(--primary);
    display: flex; align-items:center; justify-content:center;
    cursor: pointer;
    font-size: 0.85rem;
    transition: all 0.2s;
    text-decoration: none;
    flex-shrink: 0;
}
.captcha-refresh:hover {
    background: rgba(139,92,246,0.15);
    transform: rotate(180deg);
}
.captcha-hint {
    font-size: 0.72rem;
    color: var(--text-secondary);
    margin-top: 6px;
    display: flex;
    align-items: center;
    gap: 5px;
}

/* دکمه */
.btn-login {
    width: 100%;
    padding: 14px;
    background: linear-gradient(135deg, #8b5cf6, #7c3aed, #6d28d9);
    color: #fff;
    border: none;
    border-radius: 14px;
    font-family: inherit;
    font-size: 1rem;
    font-weight: 700;
    cursor: pointer;
    transition: all 0.3s;
    box-shadow: 0 6px 24px rgba(124,58,237,0.35), inset 0 1px 0 rgba(255,255,255,0.2);
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    letter-spacing: 0.3px;
    position: relative;
    overflow: hidden;
    margin-top: 4px;
}
.btn-login::before {
    content: '';
    position: absolute;
    top: 0; left: -100%;
    width: 100%; height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255,255,255,0.15), transparent);
    transition: left 0.5s;
}
.btn-login:hover { transform: translateY(-2px); box-shadow: 0 10px 32px rgba(124,58,237,0.45); }
.btn-login:hover::before { left: 100%; }
.btn-login:active { transform: translateY(0); }
.btn-login:disabled { opacity:0.6; cursor:not-allowed; transform:none; }

/* divider */
.divider {
    display: flex;
    align-items: center;
    gap: 12px;
    margin: 4px 0;
}
.divider::before, .divider::after {
    content: '';
    flex: 1;
    height: 1px;
    background: rgba(139,92,246,0.12);
}
.divider span { font-size:0.75rem; color:var(--text-secondary); white-space:nowrap; }

/* لینک ثبت‌نام */
.register-link {
    text-align: center;
    font-size: 0.83rem;
    color: var(--text-secondary);
}
.register-link a {
    color: var(--primary);
    font-weight: 700;
    text-decoration: none;
    transition: opacity 0.2s;
}
.register-link a:hover { opacity: 0.8; }

/* قفل */
.lock-badge {
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
    font-size: 0.72rem;
    color: rgba(107,114,128,0.6);
    margin-top: 16px;
}
.lock-badge i { font-size: 0.7rem; }

@media(max-width:480px) {
    .login-card { padding: 28px 22px 24px; border-radius: 22px; }
    .captcha-math { font-size: 1rem; padding: 8px 12px; }
}
</style>
</head>
<body>

<!-- ذرات شناور -->
<div class="particles" id="particles"></div>

<div class="login-wrap">
    <div class="login-card">

        <!-- لوگو -->
        <div class="login-logo">
            <div class="logo-icon">🛍️</div>
            <h1>کیف‌لند</h1>
            <p>خوش آمدید — وارد حساب خود شوید</p>
        </div>

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

        <?php if(Auth::isRateLimited($ip)): ?>
        <div class="alert-err" style="background:rgba(245,158,11,0.08);border-color:rgba(245,158,11,0.25);color:#92400e;">
            <i class="fas fa-lock"></i>
            حساب موقتاً قفل شده — <?= Auth::getRemainingLockout($ip) ?> دقیقه دیگر تلاش کنید
        </div>
        <?php endif; ?>

        <form method="POST" class="form" id="loginForm">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($csrfToken) ?>">

            <!-- ایمیل -->
            <div class="field">
                <label for="email">آدرس ایمیل</label>
                <div class="input-wrap">
                    <input type="email" name="email" id="email" required
                           placeholder="example@email.com"
                           value="<?= htmlspecialchars($_POST['email'] ?? '') ?>"
                           autocomplete="email" style="direction:ltr;">
                    <i class="fas fa-envelope fi"></i>
                </div>
            </div>

            <!-- رمز عبور -->
            <div class="field">
                <label for="password">رمز عبور</label>
                <div class="input-wrap">
                    <input type="password" name="password" id="password" required
                           placeholder="••••••••"
                           autocomplete="current-password">
                    <i class="fas fa-lock fi"></i>
                    <button type="button" class="eye-btn" onclick="togglePass()" id="eyeBtn">
                        <i class="fas fa-eye" id="eyeIco"></i>
                    </button>
                </div>
            </div>

            <!-- مرا به خاطر بسپار + فراموشی -->
            <div class="row-between">
                <label class="check-label">
                    <input type="checkbox" name="remember">
                    <span class="custom-check"></span>
                    مرا به خاطر بسپار
                </label>
                <a href="forgot-password.php" class="forgot-link">فراموشی رمز؟</a>
            </div>

            <!-- کپچا -->
            <div class="field">
                <label>سوال امنیتی <span style="color:var(--danger)">*</span></label>
                <div class="captcha-box">
                    <div class="captcha-question">
                        <div class="captcha-math" id="captchaMath"><?= htmlspecialchars($captcha['q']) ?></div>
                    </div>
                    <input type="number" name="captcha" class="captcha-input"
                           placeholder="؟" required id="captchaInput"
                           autocomplete="off">
                    <a href="?refresh=1" class="captcha-refresh" title="کپچای جدید" id="refreshCaptcha">
                        <i class="fas fa-sync-alt"></i>
                    </a>
                </div>
                <div class="captcha-hint">
                    <i class="fas fa-shield-alt" style="color:var(--primary);"></i>
                    حاصل عملیات ریاضی را وارد کنید
                </div>
            </div>

            <!-- دکمه ورود -->
            <button type="submit" class="btn-login" id="submitBtn"
                    <?= Auth::isRateLimited($ip) ? 'disabled' : '' ?>>
                <i class="fas fa-sign-in-alt"></i>
                ورود به حساب
            </button>
        </form>

        <div class="divider"><span>حساب ندارید؟</span></div>
        <div class="register-link">
            <a href="register.php"><i class="fas fa-user-plus"></i> ثبت‌نام رایگان</a>
        </div>

        <div class="lock-badge">
            <i class="fas fa-shield-alt"></i>
            اتصال امن و رمزگذاری‌شده
        </div>

    </div>
</div>

<script>
// نمایش/مخفی رمز
function togglePass() {
    const inp = document.getElementById('password');
    const ico = document.getElementById('eyeIco');
    if (inp.type === 'password') { inp.type='text';    ico.className='fas fa-eye-slash'; }
    else                         { inp.type='password'; ico.className='fas fa-eye'; }
}

// جلوگیری از ارسال چندباره
document.getElementById('loginForm').addEventListener('submit', function() {
    const btn = document.getElementById('submitBtn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> در حال ورود...';
});

// ذرات شناور
(function() {
    const container = document.getElementById('particles');
    for (let i = 0; i < 12; i++) {
        const p = document.createElement('div');
        p.className = 'particle';
        const size = Math.random() * 60 + 20;
        p.style.cssText = `
            width: ${size}px; height: ${size}px;
            left: ${Math.random()*100}%;
            animation-duration: ${Math.random()*20+15}s;
            animation-delay: ${Math.random()*-20}s;
            opacity: ${Math.random()*0.15+0.05};
        `;
        container.appendChild(p);
    }
})();

// ورودی عدد فارسی → انگلیسی
document.getElementById('captchaInput').addEventListener('input', function() {
    this.value = this.value.replace(/[۰-۹]/g, d => '۰۱۲۳۴۵۶۷۸۹'.indexOf(d));
});
</script>

</body>
</html>