<?php
session_start();
require_once 'db.php'; // Your PDO connection file

header('Content-Type: application/json');

$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';

if (empty($email) || empty($password)) {
    echo json_encode(['success' => false, 'error' => 'Email and password are required.']);
    exit;
}

try {
    $stmt = $pdo->prepare("SELECT id, username, password, points, level FROM users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();

    if (!$user) {
        echo json_encode(['success' => false, 'error' => 'User not found.']);
        exit;
    }

    if (!password_verify($password, $user['password'])) {
        echo json_encode(['success' => false, 'error' => 'Incorrect password.']);
        exit;
    }

    $_SESSION['username'] = $user['username'];

    echo json_encode([
        'success' => true,
        'user' => [
            'username' => $user['username'],
            'points' => $user['points'],
            'level' => $user['level']
        ]
    ]);
} catch (Exception $e) {
    echo json_encode(['success' => false, 'error' => 'Server error.']);
}
