<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

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

require_once '../config.php';

$data = json_decode(file_get_contents('php://input'), true);

if (empty($data['email']) || empty($data['machine_id'])) {
    http_response_code(400);
    echo json_encode(['error' => 'Missing required fields']);
    exit;
}

try {
    $db = getDB();
    $stmt = $db->prepare("SELECT id, status FROM users WHERE email = ? OR machine_id = ?");
    $stmt->execute([$data['email'], $data['machine_id']]);
    $existing = $stmt->fetch();
    
    if ($existing) {
        if ($existing['status'] === 'blocked') {
            http_response_code(403);
            echo json_encode(['error' => 'User is blocked']);
            exit;
        }
        echo json_encode(['success' => true, 'message' => 'User exists', 'user_id' => $existing['id']]);
        exit;
    }
    
    $stmt = $db->prepare("INSERT INTO users (email, username, machine_id, computer_name, windows_user, os, os_version, app_version, registered_at, last_active) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())");
    $stmt->execute([$data['email'], $data['username'], $data['machine_id'], $data['computer_name'] ?? null, $data['windows_user'] ?? null, $data['os'] ?? null, $data['os_version'] ?? null, $data['app_version'] ?? null, $data['registered_at']]);
    
    http_response_code(201);
    echo json_encode(['success' => true, 'user_id' => $db->lastInsertId()]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => 'Server error']);
}
