<?php
require __DIR__ . '/../lib/bootstrap.php';
handle_cors_preflight();

$input = input_json();
$device = get_or_create_device($input['mac'] ?? '');
$action = strtolower(trim($input['action'] ?? ''));

function normalize_playlist_input(array $input): array
{
    $type = strtolower(trim($input['type'] ?? ''));
    $name = trim($input['name'] ?? $input['playlist_name'] ?? $input['title'] ?? 'Main IPTV') ?: 'Main IPTV';
    $enabled = array_key_exists('enabled', $input) ? (bool) $input['enabled'] : true;

    if (!in_array($type, ['m3u', 'xtream'], true)) {
        json_response(['ok' => false, 'error' => 'Invalid playlist type'], 422);
    }

    $playlist = [
        'id' => isset($input['id']) ? (int) $input['id'] : (int) ($input['playlist_id'] ?? 0),
        'name' => $name,
        'type' => $type,
        'playlist_url' => null,
        'server_url' => null,
        'username' => null,
        'password' => null,
        'output' => trim($input['output'] ?? 'm3u8') ?: 'm3u8',
        'enabled' => $enabled ? 1 : 0,
    ];

    if ($type === 'm3u') {
        $playlistUrl = trim($input['playlist_url'] ?? $input['url'] ?? '');
        if (!filter_var($playlistUrl, FILTER_VALIDATE_URL)) {
            json_response(['ok' => false, 'error' => 'Valid playlist_url is required'], 422);
        }
        $playlist['playlist_url'] = $playlistUrl;
        return $playlist;
    }

    $serverUrl = rtrim(trim($input['server_url'] ?? $input['server'] ?? ''), '/');
    $username = trim($input['username'] ?? '');
    $password = trim($input['password'] ?? '');

    if (!filter_var($serverUrl, FILTER_VALIDATE_URL) || $username === '' || $password === '') {
        json_response(['ok' => false, 'error' => 'server_url, username and password are required'], 422);
    }

    $playlist['server_url'] = $serverUrl;
    $playlist['username'] = $username;
    $playlist['password'] = $password;

    return $playlist;
}

function save_playlist_for_device(int $deviceId, array $playlist): void
{
    $pdo = db();

    if (!empty($playlist['enabled'])) {
        $pdo->prepare('UPDATE playlists SET enabled = 0 WHERE device_id = ?')->execute([$deviceId]);
    }

    if (!empty($playlist['id'])) {
        $stmt = $pdo->prepare(
            'UPDATE playlists
             SET playlist_name = ?, playlist_type = ?, playlist_url = ?, server_url = ?, username = ?,
                 password = ?, output_format = ?, enabled = ?, updated_at = NOW()
             WHERE id = ? AND device_id = ?'
        );
        $stmt->execute([
            $playlist['name'],
            $playlist['type'],
            $playlist['playlist_url'],
            $playlist['server_url'],
            $playlist['username'],
            $playlist['password'],
            $playlist['output'],
            $playlist['enabled'],
            $playlist['id'],
            $deviceId,
        ]);

        if ($stmt->rowCount() > 0) {
            return;
        }
    }

    $pdo->prepare(
        'INSERT INTO playlists
         (device_id, playlist_name, playlist_type, playlist_url, server_url, username, password, output_format, enabled)
         VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'
    )->execute([
        $deviceId,
        $playlist['name'],
        $playlist['type'],
        $playlist['playlist_url'],
        $playlist['server_url'],
        $playlist['username'],
        $playlist['password'],
        $playlist['output'],
        $playlist['enabled'],
    ]);
}

function keep_only_one_enabled(array $playlists): array
{
    $hasEnabled = false;

    foreach ($playlists as &$playlist) {
        if (!empty($playlist['enabled']) && !$hasEnabled) {
            $playlist['enabled'] = 1;
            $hasEnabled = true;
        } else {
            $playlist['enabled'] = 0;
        }
    }
    unset($playlist);

    return $playlists;
}

if ($action === 'delete') {
    $playlistId = (int) ($input['id'] ?? $input['playlist_id'] ?? 0);
    if ($playlistId > 0) {
        db()->prepare('DELETE FROM playlists WHERE device_id = ? AND id = ?')->execute([(int) $device['id'], $playlistId]);
    } else {
        db()->prepare('DELETE FROM playlists WHERE device_id = ?')->execute([(int) $device['id']]);
    }
    json_response([
        'ok' => true,
        'playlist' => public_playlist_payload(get_device_playlist((int) $device['id'])),
        'playlists' => public_playlists_payload(get_device_playlists((int) $device['id'])),
    ]);
}

if ($action === 'save_many') {
    $playlists = $input['playlists'] ?? [];
    if (!is_array($playlists)) {
        json_response(['ok' => false, 'error' => 'playlists must be an array'], 422);
    }

    $pdo = db();
    $pdo->beginTransaction();
    try {
        $normalizedPlaylists = [];
        foreach ($playlists as $playlistInput) {
            if (is_array($playlistInput)) {
                $normalizedPlaylists[] = normalize_playlist_input($playlistInput);
            }
        }
        $normalizedPlaylists = keep_only_one_enabled($normalizedPlaylists);

        $pdo->prepare('DELETE FROM playlists WHERE device_id = ?')->execute([(int) $device['id']]);
        foreach ($normalizedPlaylists as $playlist) {
            save_playlist_for_device((int) $device['id'], $playlist);
        }
        $pdo->commit();
    } catch (Throwable $error) {
        $pdo->rollBack();
        json_response(['ok' => false, 'error' => $error->getMessage()], 500);
    }

    $saved = get_device_playlists((int) $device['id']);
    json_response([
        'ok' => true,
        'playlist' => public_playlist_payload(get_device_playlist((int) $device['id'])),
        'playlists' => public_playlists_payload($saved),
    ]);
}

save_playlist_for_device((int) $device['id'], normalize_playlist_input($input));

$saved = get_device_playlists((int) $device['id']);
json_response([
    'ok' => true,
    'playlist' => public_playlist_payload(get_device_playlist((int) $device['id'])),
    'playlists' => public_playlists_payload($saved),
]);
