<?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 = $data['email'] ?? '';
$password = $data['password'] ?? '';

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

$hashed = password_hash($password, PASSWORD_DEFAULT);

try {
    $stmt = $pdo->prepare("INSERT INTO users (email, password, role_id, status) VALUES (?, ?, 3, 'active')");
    $stmt->execute([$email, $hashed]);
    $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 user_tokens (user_id, token, expires_at) VALUES (?, ?, ?)");
    $stmt->execute([$userId, $token, $expires]);
    
    sendSuccess(['token' => $token, 'user_id' => $userId], 'Account created');
    
} catch (PDOException $e) {
    if ($e->errorInfo[1] == 1062) {
        sendError('Email already exists', 400);
    }
    sendError('Signup failed: ' . $e->getMessage(), 500);
}
?>