<?php
ini_set('display_errors', 0);
header('Content-Type: application/json; charset=utf-8');

include(__DIR__ . '/../includes/functions.php');
include(__DIR__ . '/../includes/multidns.php');

$jsonIn = file_get_contents('php://input');
$resonse = json_decode($jsonIn, true);

if (!is_array($resonse) || !isset($resonse['data'])) {
    echo json_encode([
        'success' => 0,
        'message' => 'Missing field: data'
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$decoded = getDecodedString((string)$resonse['data']);
$playlistData = json_decode($decoded, true);

if (!is_array($playlistData)) {
    echo json_encode([
        'success' => 0,
        'message' => 'Invalid decoded data',
        'raw_decoded' => $decoded
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$macAddress = '';
if (!empty($playlistData['mac_address'])) {
    $macAddress = strtoupper(trim((string)$playlistData['mac_address']));
} elseif (!empty($playlistData['app_device_id'])) {
    $macRaw = base64_decode((string)$playlistData['app_device_id'], true);
    if (!is_string($macRaw)) $macRaw = '';
    $macRaw = substr($macRaw, 0, 12);
    if ($macRaw !== '') {
        $macAddress = strtoupper(preg_replace('/..(?!$)/', '$0:', $macRaw));
    }
}

if ($macAddress === '') {
    echo json_encode([
        'success' => 0,
        'message' => 'mac_address/app_device_id not provided'
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$pin = isset($playlistData['parent_control']) ? trim((string)$playlistData['parent_control']) : '';

if ($pin !== '' && $pin !== '0') {
    $result = $db->select('playlist', '*', 'mac_address = :mac_address', '', [':mac_address' => $macAddress]);

    if (!empty($result)) {
        $db->update('playlist', ['pin' => $pin], 'mac_address = :mac_address', [':mac_address' => $macAddress]);
        echo json_encode([
            'success' => 1,
            'status' => true,
            'message' => 'Parental Pin updated Successfully',
            'mac_address' => $macAddress
        ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        exit;
    }

    $db->insert('playlist', [
        'dns_id' => 0,
        'mac_address' => $macAddress,
        'username' => '',
        'password' => '',
        'pin' => $pin,
        'last_used' => time(),
    ]);

    echo json_encode([
        'success' => 1,
        'status' => true,
        'message' => 'Parental Pin Set',
        'mac_address' => $macAddress
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$credentials = mdns_extract_credentials($playlistData);
$newURL = $credentials['playlist_url'];
$baseUrl = $credentials['base_url'];
$username = $credentials['username'];
$password = $credentials['password'];
$link = isset($playlistData['link']) ? trim((string)$playlistData['link']) : null;
$dnsId = trim((string)($playlistData['playlist_id'] ?? $playlistData['dns_id'] ?? $playlistData['id'] ?? ''));
$playlistName = trim((string)($playlistData['playlist_name'] ?? $playlistData['name'] ?? ''));
$allBaseUrls = $playlistData['all_base_urls'] ?? $playlistData['all_urls'] ?? [];

if (($username === '' || $password === '') && $newURL === '') {
    echo json_encode([
        'success' => 0,
        'message' => 'Missing playlist_url/credentials',
        'mac_address' => $macAddress
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$dnsRows = $db->select('dns', '*', '', 'id ASC');
$primaryDns = mdns_find_dns_row($dnsRows, $dnsId !== '' ? $dnsId : null, $baseUrl, $playlistName);
if ($primaryDns) {
    $dnsId = (string)$primaryDns['id'];
    if ($playlistName === '') {
        $playlistName = (string)($primaryDns['title'] ?? '');
    }
    if ($baseUrl === '') {
        $baseUrl = mdns_normalize_base_url((string)($primaryDns['url'] ?? ''));
    }
}

if ($username === '' || $password === '') {
    echo json_encode([
        'success' => 0,
        'message' => 'Could not extract username/password from playlist_url',
        'playlist_url' => $newURL,
        'mac_address' => $macAddress,
        'dns_id' => $dnsId
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if ($dnsId === '' && $baseUrl === '') {
    echo json_encode([
        'success' => 0,
        'message' => 'Missing playlist_id/dns_id/base_url',
        'mac_address' => $macAddress
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if ($newURL === '' && $baseUrl !== '') {
    $newURL = mdns_build_playlist_url($baseUrl, $username, $password);
}

$syncResult = mdns_sync_playlist_to_other_dns($db, $macAddress, $username, $password, [
    'pin' => ($pin !== '' ? $pin : '0000'),
    'link' => $link,
    'primary_dns_id' => ($dnsId !== '' ? (int)$dnsId : 0),
    'primary_base_url' => $baseUrl,
    'all_base_urls' => $allBaseUrls,
]);

$savedIds = $syncResult['saved_dns_ids'] ?? [];
if (empty($savedIds) && $dnsId !== '') {
    mdns_upsert_playlist($db, (int)$dnsId, $macAddress, $username, $password, ($pin !== '' ? $pin : '0000'), $link);
    $savedIds = [(int)$dnsId];
}

$response = [
    'success' => 1,
    'id' => $dnsId,
    'name' => $playlistName,
    'url' => $newURL,
    'mac_address' => $macAddress,
    'updated' => 1,
    'saved_count' => count($savedIds),
    'synced_dns_ids' => array_values($savedIds),
    'tested_dns_ids' => array_values($syncResult['tested_dns_ids'] ?? []),
    'sync_mode' => $syncResult['mode'] ?? 'primary_only',
];

echo json_encode($response, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
exit;
