<?php
require_once __DIR__ . '/../includes/bootstrap_api.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/api_helpers.php';

$request = api_read_request();
if (!isset($request['data'])) {
    api_json_response(['success' => 0, 'status' => false, 'message' => 'Missing field: data'], 400);
}

$data = api_decode_app_data($request['data']);
if (!is_array($data)) {
    api_json_response(['success' => 0, 'status' => false, 'message' => 'Invalid decoded data'], 400);
}

$mac = api_mac_from_payload($data);
if ($mac === '') {
    api_json_response(['success' => 0, 'status' => false, 'message' => 'mac_address/app_device_id not provided'], 400);
}

$deviceType = strtolower(trim((string)($data['device_type'] ?? '')));
if (!in_array($deviceType, ['tv', 'mobile'], true)) $deviceType = '';
$device = api_get_or_create_device($db, $mac, $deviceType);

// Atualização do controle parental usa o mesmo endpoint do aplicativo.
if (array_key_exists('parent_control', $data)) {
    $pin = trim((string)$data['parent_control']);
    if ($pin === '') $pin = '0000';

    $db->update('devices', ['parent_control' => $pin, 'last_seen' => date('Y-m-d H:i:s')], 'mac_address = :mac', [':mac' => $mac]);
    $db->update('playlist', ['pin' => $pin], 'mac_address = :mac', [':mac' => $mac]);

    api_json_response([
        'success' => 1,
        'status' => true,
        'message' => 'Parental Pin updated Successfully',
        'mac_address' => $mac
    ]);
}

$playlistUrl = trim((string)($data['playlist_url'] ?? ''));
$dnsId = (int)($data['playlist_id'] ?? 0);
$playlistName = trim((string)($data['playlist_name'] ?? ''));

if ($playlistUrl === '' || $dnsId <= 0) {
    api_json_response([
        'success' => 0,
        'status' => false,
        'message' => 'Missing playlist_url or valid playlist_id',
        'mac_address' => $mac
    ], 400);
}

$dnsRows = $db->select('dns', '*', 'id = :id', '', [':id' => $dnsId]);
if (empty($dnsRows)) {
    api_json_response(['success' => 0, 'status' => false, 'message' => 'Unknown playlist_id', 'id' => $dnsId], 404);
}

$query = parse_url(html_entity_decode($playlistUrl, ENT_QUOTES | ENT_HTML5, 'UTF-8'), PHP_URL_QUERY);
$parsed = [];
if (is_string($query) && $query !== '') parse_str($query, $parsed);
$username = trim((string)($parsed['username'] ?? ''));
$password = trim((string)($parsed['password'] ?? ''));

if ($username === '' || $password === '') {
    api_json_response([
        'success' => 0,
        'status' => false,
        'message' => 'Could not extract username/password from playlist_url',
        'mac_address' => $mac,
        'id' => $dnsId
    ], 400);
}

$existing = $db->select('playlist', '*', 'dns_id = :dns AND mac_address = :mac', '', [':dns' => $dnsId, ':mac' => $mac]);
$record = [
    'username' => $username,
    'password' => $password,
    'pin' => (string)($device['parent_control'] ?? '0000'),
    'link' => $playlistUrl,
    'device_key' => (string)$device['device_key'],
    'last_used' => time()
];

if (!empty($existing)) {
    $db->update('playlist', $record, 'dns_id = :dns AND mac_address = :mac', [':dns' => $dnsId, ':mac' => $mac]);
    $mode = 'updated';
} else {
    $record['dns_id'] = $dnsId;
    $record['mac_address'] = $mac;
    $db->insert('playlist', $record);
    $mode = 'inserted';
}

api_json_response([
    'success' => 1,
    'status' => true,
    'id' => $dnsId,
    'name' => $playlistName !== '' ? $playlistName : (string)$dnsRows[0]['title'],
    'url' => $playlistUrl,
    'mac_address' => $mac,
    $mode => 1
]);
