<?php
// =============================================================================
// POST /parent-control/update — sync the device's parental-control PIN.
//
// This path is NOT touched by the Glass UrlRewriter (it has no path-mapping
// entry for /parent-control/update), so the URL passes through unchanged.
//
// Inner JSON (built by t2.g.h):
//   { "mac_address": "...",
//     "parent_control": "<payload>",
//     "app_type": "phone",
//     "version": "4.3" }
//
// We mark parent_synced = 1 so the client stops calling this on every
// HomeActivity onCreate.
// =============================================================================

require_once __DIR__ . '/../includes/client_common.php';

require_method('POST');

$inner = client_decoded_body();
if (!is_array($inner)) {
    json_error('invalid envelope', 400);
}

$mac    = (string)($inner['mac_address']    ?? '');
$device = client_device_by_mac($mac);
if (!$device) {
    client_log_request(null, 'POST', '/parent-control/update', client_request_headers(), $inner, 404, ['error' => 'unknown device']);
    json_error('unknown device', 404);
}

$pc_payload = (string)($inner['parent_control'] ?? '');

db_exec(
    'UPDATE parent_control SET parent_control = ?, parent_synced = 1, updated_at = ?
     WHERE device_id = ?',
    [$pc_payload, unix_now(), (int)$device['id']]
);

$resp = ['success' => true];
client_log_request((int)$device['id'], 'POST', '/parent-control/update',
                   client_request_headers(), $inner, 200, $resp);
json_response($resp);
