<?php
require 'config.php';

if (isset($_SESSION['user_id'])) {
    header("Location: dashboard.php");
    exit;
}

$message = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Check if both username and password are provided
    if (isset($_POST['username'], $_POST['password'])) {
        $username = trim($_POST['username']);
        $password = $_POST['password'];

        // Check if the database connection is valid before proceeding
        if (!$conn) {
            $message = "خطأ في الاتصال بقاعدة البيانات.";
        } else {
            // استعلام لجلب بيانات المستخدم
            $stmt = $conn->prepare("SELECT * FROM users WHERE username = :username LIMIT 1");
            $stmt->execute(['username' => $username]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
            if ($user && password_verify($password, $user['password'])) {
                $_SESSION['user_id'] = $user['id'];
        $_SESSION['username'] = $user['username'];
        $_SESSION['role'] = $user['role'];

        // --- إضافة منطق تذكرني --- 
        if (isset($_POST['remember_me']) && $_POST['remember_me'] == 'on') {
            $selector = bin2hex(random_bytes(16));
            $token = bin2hex(random_bytes(32));
            $hashed_token = password_hash($token, PASSWORD_DEFAULT);
            $expires = time() + (86400 * 30); // 30 يومًا

            try {
                $stmt_token = $conn->prepare("INSERT INTO auth_tokens (selector, hashed_token, user_id, expires) VALUES (:selector, :hashed_token, :user_id, :expires)");
                $stmt_token->execute([
                    ':selector' => $selector,
                    ':hashed_token' => $hashed_token,
                    ':user_id' => $user['id'],
                    ':expires' => date('Y-m-d H:i:s', $expires)
                ]);

                // تعيين ملفات تعريف الارتباط (آمنة إذا كان HTTPS متاحًا)
                setcookie('remember_selector', $selector, $expires, '/', '', isset($_SERVER['HTTPS']), true); // HttpOnly
                setcookie('remember_token', $token, $expires, '/', '', isset($_SERVER['HTTPS']), true); // HttpOnly

            } catch (PDOException $e) {
                // يمكنك تسجيل الخطأ هنا إذا لزم الأمر، لكن لا توقف تسجيل الدخول
                error_log("Error saving auth token: " . $e->getMessage());
            }
        }
        // --- نهاية منطق تذكرني ---

                header("Location: dashboard.php");
                exit;
            } else {
                $message = "اسم المستخدم أو كلمة المرور غير صحيحة.";
            }
        } // End of the 'if ($conn)' block
    } else {
        // Handle missing username or password
        $message = "الرجاء إدخال اسم المستخدم وكلمة المرور.";
    }
}
?>
<!DOCTYPE html>
<html lang="ar">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>تسجيل الدخول</title>
    <style>
        /* Reset والأنماط الأساسية */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: #121212;
            color: #e0e0e0;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            padding: 20px;
        }
        .login-container {
            background: #1e1e1e;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.5);
            width: 100%;
            max-width: 400px;
        }
        .login-container h2 {
            text-align: center;
            margin-bottom: 20px;
            font-size: 24px;
            font-weight: 500;
        }
        .login-container form {
            display: flex;
            flex-direction: column;
        }
        .login-container input {
            width: 100%;
            padding: 12px;
            margin-bottom: 15px;
            border-radius: 4px;
            border: 1px solid #444;
            background: #2c2c2c;
            color: #e0e0e0;
            font-size: 16px;
        }
        .login-container button {
            padding: 12px;
            background: #007BFF;
            border: none;
            color: #fff;
            border-radius: 4px;
            font-size: 16px;
            cursor: pointer;
            transition: background 0.3s ease;
        }
        .login-container button:hover {
            background: #0056b3;
        }
        .error {
            text-align: center;
            color: #ff6b6b;
            margin-bottom: 15px;
            font-size: 16px;
        }
        @media (max-width: 480px) {
            .login-container {
                padding: 20px;
            }
            .login-container h2 {
                font-size: 20px;
            }
            .login-container input, .login-container button {
                font-size: 14px;
            }
        }
        .password-container {
            position: relative;
            display: flex;
            align-items: center;
            margin-bottom: 15px; /* Match other inputs */
        }
        .password-container input {
            padding-right: 40px; /* Space for the icon */
            margin-bottom: 0; /* Remove bottom margin as it's on the container */
        }
        .toggle-password {
            position: absolute;
            right: 10px;
            top: 50%;
            transform: translateY(-50%);
            cursor: pointer;
            color: #aaa; /* Icon color */
            font-size: 18px; /* Adjust icon size */
            user-select: none; /* Prevent text selection */
        }
    </style>
    <!-- Include Font Awesome for icons -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>
    <div class="login-container">
        <h2>تسجيل الدخول</h2>
        <?php if ($message): ?>
            <p class="error"><?= $message ?></p>
        <?php endif; ?>
        <form method="POST" action="login.php">
            <input type="text" name="username" placeholder="اسم المستخدم" required>
            <div class="password-container">
                <input type="password" name="password" id="password" placeholder="كلمة المرور" required>
                <i class="fas fa-eye toggle-password" id="togglePassword"></i>
            </div>
            <div style="margin-bottom: 15px; display: flex; align-items: center;">
                <input type="checkbox" name="remember_me" id="remember_me" style="width: auto; margin-right: 8px;">
                <label for="remember_me" style="font-size: 14px; color: #ccc;">تذكرني</label>
            </div>
            <button type="submit">دخول</button>
        </form>
    </div>

    <script>
        const passwordInput = document.getElementById('password');
        const togglePasswordIcon = document.getElementById('togglePassword');

        togglePasswordIcon.addEventListener('click', function () {
            // Toggle the type attribute
            const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
            passwordInput.setAttribute('type', type);

            // Toggle the icon
            this.classList.toggle('fa-eye');
            this.classList.toggle('fa-eye-slash');
        });
    </script>
</body>
</html>
