<?php
ini_set('display_errors', 1);
include(__DIR__ . '/../includes/functions.php');

$infos = explode("{}", base64_decode($_GET['info']));
$dnsId = $infos[0];
$username = $infos[1];
$password = $infos[2];
$macAddress = base64_decode($infos[3]);
$macAddress = strtoupper(implode(":", str_split(substr(str_replace("afea", "", $macAddress), 0, 12), 2)));

$result = $db->select('playlist', '*', 'dns_id = :dns_id AND mac_address = :mac_address', '', [
    ':dns_id' => $dnsId,
    ':mac_address' => $macAddress
]);

if (!empty($result)) {
    // Já existe, apenas retorna os dados existentes
    $response = [
        'success' => 1,
        'id' => $result[0]['dns_id'],
        'name' => $result[0]['username'],
        'url' => $result[0]['password'],
        'message' => 'Registro já existente, sem alteração.'
    ];
} else {
    // Não existe, insere
    $data = [
        'dns_id' => $dnsId,
        'mac_address' => $macAddress,
        'username' => $username,
        'password' => $password,
        'pin' => '0000'
    ];
    $db->insert('playlist', $data);

    $response = [
        'success' => 1,
        'id' => $dnsId,
        'name' => $username,
        'url' => $password,
        'message' => 'Novo registro criado.'
    ];
}

echo json_encode($response);
