<?php
/**
 * Registro automático do dispositivo (app Android na primeira abertura)
 * POST JSON: { "device_id": "uuid", "label": "...", "model": "..." }
 */
require_once __DIR__ . '/../../includes/db.php';
require_once __DIR__ . '/../../includes/helpers.php';

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    json_response(['success' => false, 'error' => 'Método não permitido'], 405);
}

try {
    $raw = file_get_contents('php://input');
    $data = json_decode($raw, true);
    if (!is_array($data)) {
        throw new InvalidArgumentException('JSON inválido.');
    }

    $deviceId = trim($data['device_id'] ?? '');
    if (!is_valid_device_id($deviceId)) {
        throw new InvalidArgumentException('device_id inválido (UUID esperado).');
    }

    $label = trim($data['label'] ?? '') ?: null;
    $model = trim($data['model'] ?? '') ?: null;

    register_device($deviceId, $label, $model);
    ensure_device_upload_dirs($deviceId);

    json_response([
        'success' => true,
        'device_id' => $deviceId,
        'registered_at' => date('c'),
    ]);
} catch (Throwable $e) {
    json_response([
        'success' => false,
        'error' => $e->getMessage(),
    ], 400);
}
