<?php
require_once '../../config/cors.php';
require_once '../../config/db.php';
require_once '../../helpers/response.php';

$data = json_decode(file_get_contents('php://input'), true);
$email = filter_var($data['email'] ?? '', FILTER_VALIDATE_EMAIL);
$password = $data['password'] ?? '';

if (!$email || !$password) {
    sendError('Valid email and password required', 400);
}

if (strlen($password) < 6) {
    sendError('Password must be at least 6 characters', 400);
}

$hashed = password_hash($password, PASSWORD_DEFAULT);

try {
    // Check if email exists
    $stmt = $pdo->prepare("SELECT id FROM public_users WHERE email = ?");
    $stmt->execute([$email]);
    if ($stmt->fetch()) {
        sendError('Email already exists', 400);
    }
    
    // Create user
    $stmt = $pdo->prepare("INSERT INTO public_users (email, password, status, display_name) VALUES (?, ?, 'active', ?)");
    $displayName = explode('@', $email)[0];
    $stmt->execute([$email, $hashed, $displayName]);
    $userId = $pdo->lastInsertId();
    
    // Generate token
    $token = bin2hex(random_bytes(32));
    $expires = date('Y-m-d H:i:s', strtotime('+30 days'));
    
    $stmt = $pdo->prepare("INSERT INTO public_user_tokens (user_id, token, expires_at) VALUES (?, ?, ?)");
    $stmt->execute([$userId, $token, $expires]);
    
    sendSuccess([
        'token' => $token,
        'user_id' => $userId,
        'email' => $email,
        'display_name' => $displayName
    ], 'Account created successfully');
    
} catch (PDOException $e) {
    sendError('Database error: ' . $e->getMessage(), 500);
}
?>