<?php
// /linkstorm/auth.php
header('Content-Type: application/json; charset=utf-8');
require_once __DIR__ . '/inc/db.php';

$action = $_POST['action'] ?? $_GET['action'] ?? '';

try {
    $pdo = ls_pdo();
} catch (Exception $e) {
    echo json_encode(['error' => 'DB connection failed.']);
    exit;
}

if ($action === 'register') {
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

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

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
        echo json_encode(['error' => 'Invalid email format.']);
        exit;
    }

    $stmt = $pdo->prepare("SELECT id FROM ls_users WHERE email = ?");
    $stmt->execute([$email]);
    if ($stmt->fetch()) {
        echo json_encode(['error' => 'Email already registered.']);
        exit;
    }

    $hash = password_hash($password, PASSWORD_DEFAULT);
    $stmt = $pdo->prepare("INSERT INTO ls_users (email, password_hash) VALUES (?, ?)");
    $stmt->execute([$email, $hash]);
    $userId = (int)$pdo->lastInsertId();

    $_SESSION['user_id'] = $userId;
    $_SESSION['user_email'] = $email;

    echo json_encode(['success' => true, 'user' => ['id' => $userId, 'email' => $email]]);
    exit;
}

if ($action === 'login') {
    $email = trim($_POST['email'] ?? '');
    $password = $_POST['password'] ?? '';

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

    $stmt = $pdo->prepare("SELECT id, password_hash FROM ls_users WHERE email = ?");
    $stmt->execute([$email]);
    $user = $stmt->fetch();
    if (!$user || !password_verify($password, $user['password_hash'])) {
        echo json_encode(['error' => 'Invalid login.']);
        exit;
    }

    $_SESSION['user_id'] = (int)$user['id'];
    $_SESSION['user_email'] = $email;

    echo json_encode(['success' => true, 'user' => ['id' => (int)$user['id'], 'email' => $email]]);
    exit;
}

if ($action === 'logout') {
    session_destroy();
    echo json_encode(['success' => true]);
    exit;
}

if ($action === 'me') {
    $u = ls_current_user();
    echo json_encode(['user' => $u]);
    exit;
}

echo json_encode(['error' => 'Invalid action.']);
