<?php
// =============================================================================
// /api/find_duplicates.php — server-side duplicate detection.
//
// scope=playlist_url  — playlists with the same URL across multiple devices
// scope=username      — playlists with the same username across multiple devices
// scope=mac           — devices sharing a normalised android_id under different MACs
// =============================================================================
require_once __DIR__ . '/_common.php';
require_csrf_unless_get();

$scope = (string)($_GET['scope'] ?? 'playlist_url');

if ($scope === 'playlist_url') {
    $rows = db_all(
        'SELECT url AS dup_key,
                COUNT(*) AS count,
                GROUP_CONCAT(d.mac_address, "|") AS macs,
                GROUP_CONCAT(p.id, ",") AS ids
         FROM playlists p
         JOIN devices d ON d.id = p.device_id
         WHERE p.url != ""
         GROUP BY p.url
         HAVING count > 1
         ORDER BY count DESC, p.url'
    );
} elseif ($scope === 'username') {
    $rows = db_all(
        'SELECT username AS dup_key,
                COUNT(*) AS count,
                GROUP_CONCAT(d.mac_address, "|") AS macs,
                GROUP_CONCAT(p.id, ",") AS ids
         FROM playlists p
         JOIN devices d ON d.id = p.device_id
         WHERE p.username != ""
         GROUP BY p.username
         HAVING count > 1
         ORDER BY count DESC, p.username'
    );
} elseif ($scope === 'mac') {
    $rows = db_all(
        'SELECT android_id AS dup_key,
                COUNT(*) AS count,
                GROUP_CONCAT(mac_address, "|") AS macs,
                GROUP_CONCAT(id, ",") AS ids
         FROM devices
         WHERE android_id != ""
         GROUP BY android_id
         HAVING count > 1
         ORDER BY count DESC'
    );
} else {
    json_error('unknown scope', 400);
}

$out = [];
foreach ($rows as $r) {
    $out[] = [
        'key'   => (string)$r['dup_key'],
        'count' => (int)$r['count'],
        'macs'  => array_filter(explode('|', (string)$r['macs'])),
        'ids'   => array_map('intval', array_filter(explode(',', (string)$r['ids']))),
    ];
}
json_response(['scope' => $scope, 'groups' => $out, 'total_groups' => count($out)]);
