<?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'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

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

if ($macAddress === '' || $username === '' || $password === '') {
    echo json_encode([
        'success' => 0,
        'message' => 'mac_address, username and password are required'
    ], 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 ($dnsId === '' && $baseUrl === '') {
    echo json_encode(['success' => 0, 'message' => 'Missing playlist_id/dns_id/base_url'], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

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

$syncResult = mdns_sync_playlist_to_other_dns($db, $macAddress, $username, $password, [
    '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, '0000', $link);
    $savedIds = [(int)$dnsId];
}

$response = [
    'success' => 1,
    'id' => $dnsId,
    'name' => $playlistName,
    'url' => $playlistUrl,
    '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);
