<?php
require_once '../includes/header.php';

// Handle logout
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    redirect(SITE_URL . '/index.php');
}

$message = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = sanitizeInput($_POST['email']);
    $password = $_POST['password'];
    
    // Validation
    if (empty($email) || empty($password)) {
        $message = '<div class="message error">جميع الحقول مطلوبة.</div>';
    } else {
        // Get user by email
        $user = getUserByEmail($pdo, $email);
        
        if ($user && verifyPassword($password, $user['password'])) {
            // Set session variables
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['role'] = $user['role']; // Store user role in session
            
            // Redirect to intended page or home
            $redirect_url = $_SESSION['redirect_after_login'] ?? SITE_URL . '/index.php';
            unset($_SESSION['redirect_after_login']);
            
            redirect($redirect_url);
        } else {
            $message = '<div class="message error">البريد الإلكتروني أو كلمة المرور غير صحيحة.</div>';
        }
    }
}
?>

<div class="container">
    <div class="form-container">
        <h2 style="text-align: center; margin-bottom: 30px;">تسجيل الدخول</h2>
        
        <?php echo $message; ?>
        
        <form method="POST" action="">
            <div class="form-group">
                <label for="email">البريد الإلكتروني</label>
                <input type="email" id="email" name="email" required>
            </div>
            
            <div class="form-group">
                <label for="password">كلمة المرور</label>
                <input type="password" id="password" name="password" required>
            </div>
            
            <button type="submit" class="btn btn-primary btn-large btn-block">تسجيل الدخول</button>
        </form>
        
        <p style="text-align: center; margin-top: 20px;">
            ليس لديك حساب؟ <a href="<?php echo SITE_URL; ?>/auth/register.php">سجل هنا</a>
        </p>
    </div>
</div>

<?php require_once '../includes/footer.php'; ?>