<?php

include "../lib/json-headers.php";
include "../lib/cors-headers.php";
include "../lib/remote.php";
include "functions.php";

$blob_encoded = get_or_create($dom)['nosql'];

/*
 * GET
 *
 * sin parametros
 */

if ($_SERVER['REQUEST_METHOD'] === 'GET') {

    if (!$blob_encoded) {
        http_response_code(404);
        die('{ "error": "No encontrado" }');
    }

    die($blob_encoded);
}

/*
 * POST
 *
 * params:
 *      - name
 *      - val
 *      - options?: Si se requiere realizar una tarea extra, especificada en functions.php
 */

$post_encoded = file_get_contents('php://input');
$post = json_decode($post_encoded, TRUE); //convert JSON into array

if (!isset($post['name']) or !isset($post['val'])) {
    http_response_code(400);
    die('{ "error": "Mal solititado el posteo" }');
}

$blob = json_decode($blob_encoded, True); // stdclass object to array
if (!$blob) {
    $blob = [];
}

$blob[$post['name']] = $post['val'];

//$blob = array_map('utf8_encode', $blob);
$blob_encoded = json_encode($blob, JSON_UNESCAPED_UNICODE);

if (!$blob_encoded) {
    http_response_code(409);
    die('{ "error": "Conflicto al guardar" }');
}

remote_query("UPDATE radios SET nosql='$blob_encoded' WHERE website='$dom'");

if (isset($post['options'])) {
    // Realizar tarea extra
    do_options($post['options'], $blob);
}

die($blob_encoded);
