<?php
require_once __DIR__ . '/_common.php';
require_csrf_unless_get();
list($action, $body) = read_action();

function check_dev($device_id) {
    $d = db_one('SELECT id FROM devices WHERE id = ?', [$device_id]);
    if (!$d) json_error('device not found', 404);
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (!empty($_GET['device_id'])) {
        check_dev((int)$_GET['device_id']);
        $row = db_one('SELECT * FROM parent_control WHERE device_id = ?', [(int)$_GET['device_id']]);
        // PIN unlocks the parent-control gate — viewers must not see it.
        if ($row && !auth_is_admin() && array_key_exists('pin_code', $row)) {
            $row['pin_code'] = '<hidden>';
        }
        json_response(['parent_control' => $row]);
    }
    json_error('device_id required', 400);
}

if ($action === 'update') {
    if (empty($body['device_id'])) json_error('device_id required');
    check_dev((int)$body['device_id']);
    $exists = db_one('SELECT device_id FROM parent_control WHERE device_id = ?', [(int)$body['device_id']]);
    if (!$exists) {
        db_exec('INSERT INTO parent_control (device_id) VALUES (?)', [(int)$body['device_id']]);
    }
    db_exec(
        'UPDATE parent_control SET pin_code = ?, parent_control = ?, parent_synced = ?, updated_at = ?
         WHERE device_id = ?',
        [$body['pin_code']       ?? '',
         $body['parent_control'] ?? '',
         truthy($body['parent_synced'] ?? 1),
         unix_now(),
         (int)$body['device_id']]
    );
    json_response(['ok' => true]);
}

json_error('unknown action', 400);
