<?php
include 'db.php';

header('Content-Type: application/json'); // Set response header to JSON

$upload_folder = "https://quiztest.store/web/webb/uploads/"; // Replace with your actual image directory URL

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $email = $_POST['email'];
    $password = $_POST['password'];

    // Fetch the user by email with category name
    $stmt = $pdo->prepare("
        SELECT users.*, categories.name AS category_name 
        FROM users 
        LEFT JOIN categories ON users.category_id = categories.id 
        WHERE users.email = ?
    ");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    // Check if the user exists and the password is correct
    if ($user && password_verify($password, $user['password'])) {
        $image_url = !empty($user['image']) ? $user['image'] : null;

        echo json_encode([
            'status' => 'success',
            'user_id' => $user['id'],
            'name' => $user['name'],
            'image' => $image_url,
            'category_id' => $user['category_id'],
            'category_name' => $user['category_name'], // Add category name
            'message' => 'Login successful'
        ]);
    } else {
        echo json_encode([
            'status' => 'error',
            'message' => 'Invalid email or password'
        ]);
    }
} else {
    echo json_encode([
        'status' => 'error',
        'message' => 'Invalid request method'
    ]);
}
?>