<?php
declare(strict_types=1);

require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/auth.php';

if (is_admin_logged_in()) {
    redirect_to(admin_url('index.php'));
}

$page_title = 'تسجيل دخول الأدمن';
$error_message = '';

if (is_post()) {
    $username = trim((string) post('username'));
    $password = (string) post('password');

    if ($username === '' || $password === '') {
        $error_message = 'يرجى إدخال اسم المستخدم وكلمة المرور.';
    } else {
        $lockMeta = admin_login_lock_meta($username);
        if (!empty($lockMeta['locked'])) {
            $minutes = max(1, (int) ceil(((int) ($lockMeta['remaining_seconds'] ?? 0)) / 60));
            $error_message = 'تم قفل تسجيل الدخول مؤقتاً. حاول مرة أخرى بعد ' . $minutes . ' دقيقة.';
        } else {
            $stmt = $conn->prepare("SELECT id, full_name, username, password_hash, role, status FROM admins WHERE username = ? LIMIT 1");
            if (!$stmt) {
                $error_message = 'تعذر تنفيذ عملية تسجيل الدخول حالياً.';
            } else {
                $stmt->bind_param('s', $username);
                $stmt->execute();
                $result = $stmt->get_result();
                $admin = $result ? $result->fetch_assoc() : null;
                $stmt->close();

                if (!$admin) {
                    $error_message = 'اسم المستخدم غير موجود.';
                    admin_register_login_failure($username, 'username_not_found');
                } elseif ((int) ($admin['status'] ?? 0) !== 1) {
                    $error_message = 'هذا الحساب غير مفعل.';
                    admin_register_login_failure($username, 'inactive_account');
                } elseif (!password_verify($password, (string) ($admin['password_hash'] ?? ''))) {
                    $error_message = 'كلمة المرور غير صحيحة.';
                    admin_register_login_failure($username, 'wrong_password');
                } else {
                    admin_clear_login_failures($username);
                    $_SESSION['admin_id'] = (int) $admin['id'];
                    $_SESSION['admin_name'] = (string) ($admin['full_name'] ?? '');
                    $_SESSION['admin_username'] = (string) ($admin['username'] ?? '');
                    $_SESSION['admin_role'] = (string) ($admin['role'] ?? '');
                    $_SESSION['admin_last_activity_at'] = time();

                    $ip = admin_setting_enabled('admin_track_ip_enabled', true) ? admin_client_ip() : '';
                    $lastLoginSql = $ip !== ''
                        ? "UPDATE admins SET last_login_at = NOW(), last_login_ip = ?, last_seen_ip = ? WHERE id = ?"
                        : "UPDATE admins SET last_login_at = NOW() WHERE id = ?";
                    $up = $conn->prepare($lastLoginSql);
                    if ($up) {
                        $adminId = (int) $admin['id'];
                        if ($ip !== '') {
                            $up->bind_param('ssi', $ip, $ip, $adminId);
                        } else {
                            $up->bind_param('i', $adminId);
                        }
                        $up->execute();
                        $up->close();
                    }

                    admin_log_activity(
                        'admin.login_success',
                        'تسجيل دخول الأدمن',
                        'تم تسجيل الدخول بنجاح.',
                        'admin',
                        (int) $admin['id'],
                        ['username' => (string) ($admin['username'] ?? '')],
                        true
                    );
                    set_flash('success', 'تم تسجيل الدخول بنجاح.');
                    redirect_to(admin_url('index.php'));
                }
            }
        }
    }
}


$flash = get_flash();
?>
<!DOCTYPE html>
<html lang="ar" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?= e($page_title) ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css">
    <style>
        *{box-sizing:border-box;margin:0;padding:0}
        body{
            font-family:Tahoma, Arial, sans-serif;
            background:linear-gradient(180deg,#d7e3ee 0%, #eef3f8 32%, #d8e4ef 100%);
            min-height:100vh;
            display:flex;
            align-items:center;
            justify-content:center;
            padding:20px;
            color:#111827;
        }
        .login-card{
            width:100%;
            max-width:460px;
            background:linear-gradient(180deg,#ffffff 0%,#f8fbfd 100%);
            border-radius:24px;
            padding:34px;
            box-shadow:0 24px 60px rgba(22,38,56,0.16);
            border:1px solid #d6e0ea;
        }
        .brand{
            text-align:center;
            margin-bottom:26px;
        }
        .brand-icon{
            width:74px;
            height:74px;
            border-radius:22px;
            margin:0 auto 14px;
            background:linear-gradient(180deg,#6f93b0 0%,#315a7d 100%);
            display:flex;
            align-items:center;
            justify-content:center;
            color:#fff;
            font-size:30px;
            color:#264968;
        }
        .brand h1{
            font-size:30px;
            color:#264968;
            margin-bottom:6px;
        }
        .brand p{
            color:#6b7280;
            font-size:14px;
        }
        .form-group{
            margin-bottom:16px;
        }
        label{
            display:block;
            margin-bottom:8px;
            font-size:14px;
            font-weight:700;
        }
        input{
            width:100%;
            padding:14px 16px;
            border:1px solid #d1d5db;
            border-radius:14px;
            font-size:15px;
            outline:none;
        }
        input:focus{
            border-color:#7aa0bb;
            box-shadow:0 0 0 4px rgba(49,91,127,.12);
        }
        .btn{
            width:100%;
            border:none;
            background:linear-gradient(180deg,#6f93b0 0%,#315a7d 100%);
            color:#fff;
            padding:14px 16px;
            border-radius:14px;
            font-size:15px;
            font-weight:800;
            cursor:pointer;
        }
        .btn:hover{
            filter:brightness(1.02);
        }
        .alert{
            padding:14px 16px;
            border-radius:14px;
            margin-bottom:16px;
            font-size:14px;
            font-weight:700;
        }
        .alert.error{
            background:#fef2f2;
            color:#991b1b;
            border:1px solid #fecaca;
        }
        .alert.success{
            background:#ecfdf5;
            color:#065f46;
            border:1px solid #a7f3d0;
        }
        .login-note{
            text-align:center;
            margin-top:18px;
            color:#6b7280;
            font-size:13px;
        }
    </style>
</head>
<body>
    <div class="login-card">
        <div class="brand">
            <div class="brand-icon">
                <i class="fa-solid fa-shield-halved"></i>
            </div>
            <h1>Nay Store</h1>
            <p>لوحة تحكم الإدارة بنسخة احترافية موحّدة</p>
        </div>

        <?php if ($flash): ?>
            <div class="alert <?= e($flash['type']) ?>">
                <?= e($flash['message']) ?>
            </div>
        <?php endif; ?>

        <?php if ($error_message !== ''): ?>
            <div class="alert error">
                <?= e($error_message) ?>
            </div>
        <?php endif; ?>

        <form method="post">
            <div class="form-group">
                <label for="username">اسم المستخدم</label>
                <input type="text" id="username" name="username" value="<?= e((string) old('username')) ?>" required>
            </div>

            <div class="form-group">
                <label for="password">كلمة المرور</label>
                <input type="password" id="password" name="password" required>
            </div>

            <button type="submit" class="btn">
                <i class="fa-solid fa-right-to-bracket"></i>
                تسجيل الدخول
            </button>
        </form>

        <div class="login-note">
            دخول خاص بالإدارة فقط
        </div>
    </div>
</body>
</html>