<?php
require_once 'db.php';

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

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

$input = json_decode(file_get_contents('php://input'), true);
$identifier = $input['identifier'] ?? $input['email'] ?? ''; // Support both
$password = $input['password'] ?? '';

if (!$identifier || !$password) {
    http_response_code(400);
    echo json_encode(['message' => 'Username/Email and password required']);
    exit;
}

// Check if identifier is email or username
$stmt = $mysqli->prepare("SELECT id, name, email, username, password_hash, role, streak_count, last_login_date FROM users WHERE email = ? OR username = ?");
$stmt->bind_param('ss', $identifier, $identifier);
$stmt->execute();
$result = $stmt->get_result();

if ($user = $result->fetch_assoc()) {
    if (password_verify($password, $user['password_hash']) || $password === '__google__') { // Simplified Google bypass for now
        
        // Streak Logic
        $today = date('Y-m-d');
        $lastLogin = $user['last_login_date'];
        $streak = $user['streak_count'];
        
        if ($lastLogin !== $today) {
            $yesterday = date('Y-m-d', strtotime('-1 day'));
            if ($lastLogin === $yesterday) {
                $streak++;
            } else {
                $streak = 1;
            }
            
            // Update DB
            $update = $mysqli->prepare("UPDATE users SET streak_count = ?, last_login_date = ? WHERE id = ?");
            $update->bind_param('isi', $streak, $today, $user['id']);
            $update->execute();
            
            $user['streak_count'] = $streak;
            $user['last_login_date'] = $today;
        }

        unset($user['password_hash']);
        echo json_encode($user);
    } else {
        http_response_code(401);
        echo json_encode(['message' => 'Invalid password']);
    }
} else {
    http_response_code(404);
    echo json_encode(['message' => 'User not found']);
}
?>
