<?php

require_once __DIR__ . '/../../src/Classes/User.php';

$method = $_SERVER['REQUEST_METHOD'];

if ($method === 'POST') {
    $input = json_decode(file_get_contents('php://input'), true);

    $apiPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    if (strpos($apiPath, 'register') !== false) {
        try {
            $user = User::register($input['email'], $input['password']);

            // Generate a simple token (in production use JWT)
            $token = bin2hex(random_bytes(32));
            $_SESSION['user_id'] = $user->getId();
            $_SESSION['token'] = $token;

            echo json_encode([
                'success' => true,
                'user' => [
                    'id' => $user->getId(),
                    'email' => $user->getEmail(),
                    'token' => $token
                ]
            ]);
        } catch (\Exception $e) {
            http_response_code(400);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    } elseif (strpos($apiPath, 'login') !== false) {
        try {
            $user = User::login($input['email'], $input['password']);

            $token = bin2hex(random_bytes(32));
            $_SESSION['user_id'] = $user->getId();
            $_SESSION['token'] = $token;

            echo json_encode([
                'success' => true,
                'user' => [
                    'id' => $user->getId(),
                    'email' => $user->getEmail(),
                    'token' => $token
                ]
            ]);
        } catch (\Exception $e) {
            http_response_code(401);
            echo json_encode([
                'success' => false,
                'error' => $e->getMessage()
            ]);
        }
    }
} elseif ($method === 'GET') {
    $apiPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);

    if (strpos($apiPath, 'logout') !== false) {
        session_destroy();
        echo json_encode(['success' => true]);
    }
}
