<?php
/**
 * api/device/parental.php — POST /api/device/parental
 *
 * Cambia el PIN parental del dispositivo (equivalente a parent_control.php).
 *
 * Request:  { "mac", "pin" }
 * Response: { "ok": true }  o  { "ok": false, "error": "..." }
 */

declare(strict_types=1);

require_once __DIR__ . '/../../lib/helpers.php';
require_once __DIR__ . '/../../lib/device.php';

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
    json_out(['ok' => false, 'error' => 'method_not_allowed'], 405);
}

$body = read_json_body();

$mac = normalize_mac(isset($body['mac']) ? (string) $body['mac'] : null);
if ($mac === null) {
    json_out(['ok' => false, 'error' => 'mac inválida'], 400);
}

// El PIN debe ser numérico de 4 a 8 dígitos.
$pin = trim((string) ($body['pin'] ?? ''));
if (!preg_match('/^\d{4,8}$/', $pin)) {
    json_out(['ok' => false, 'error' => 'pin inválido (4-8 dígitos)'], 400);
}

try {
    $device = device_find_by_mac($mac);
    if ($device === null) {
        // Si el dispositivo no existe, lo creamos para no perder el PIN.
        $device = device_create($mac, null, null, null);
    }

    $stmt = db()->prepare(
        'UPDATE devices SET parent_pin = ?, parent_synced = 1 WHERE id = ?'
    );
    $stmt->execute([$pin, (int) $device['id']]);

    json_out(['ok' => true], 200);
} catch (Throwable $ex) {
    error_log('[api/device/parental] ' . $ex->getMessage());
    json_out(['ok' => false, 'error' => 'server_error'], 500);
}
