<?php
require_once __DIR__ . '/_common.php';
require_csrf_unless_get();
list($action, $body) = read_action();

function check_device($device_id) {
    $d = db_one('SELECT id FROM devices WHERE id = ?', [$device_id]);
    if (!$d) json_error('device not found', 404);
}

// Playlist rows store the buyer's IPTV portal credentials (username/password).
// Hide those from viewers — they can still see counts, names, URLs, etc.
function playlists_redact_for_viewer(array $row) {
    $row['username'] = '<hidden>';
    $row['password'] = '<hidden>';
    return $row;
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    if (!empty($_GET['id'])) {
        $row = db_one('SELECT * FROM playlists WHERE id = ?', [(int)$_GET['id']]);
        if (!$row) json_error('playlist not found', 404);
        if (!auth_is_admin()) $row = playlists_redact_for_viewer($row);
        json_response(['playlist' => $row]);
    }
    if (!empty($_GET['device_id'])) {
        check_device((int)$_GET['device_id']);
        $rows = db_all('SELECT * FROM playlists WHERE device_id = ? ORDER BY sort_order ASC, id ASC',
                        [(int)$_GET['device_id']]);
        if (!auth_is_admin()) $rows = array_map('playlists_redact_for_viewer', $rows);
        json_response(['playlists' => $rows]);
    }
    $rows = db_all(
        'SELECT p.*, d.mac_address AS device_mac
         FROM playlists p
         JOIN devices d ON d.id = p.device_id
         ORDER BY p.updated_at DESC'
    );
    if (!auth_is_admin()) $rows = array_map('playlists_redact_for_viewer', $rows);
    json_response(['playlists' => $rows]);
}

if ($action === 'create') {
    $field_labels = ['device_id' => 'a device', 'name' => 'a name', 'url' => 'a playlist URL'];
    foreach (['device_id','name','url'] as $f) {
        if (empty($body[$f])) json_error('Please choose ' . $field_labels[$f] . '.');
    }
    if (!preg_match('#^https?://#i', trim((string)$body['url']))) {
        json_error('Playlist URL must start with http:// or https://.');
    }
    check_device((int)$body['device_id']);
    $public_id = !empty($body['public_id']) ? $body['public_id']
                : next_public_id('playlists', 'device_id = ?', [(int)$body['device_id']]);
    try {
        $id = db_insert(
            'INSERT INTO playlists (device_id, public_id, name, type, url, username, password, is_protected, sort_order)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
            [(int)$body['device_id'], $public_id,
             trim((string)$body['name']),
             $body['type'] ?? 'xtream',
             trim((string)$body['url']),
             $body['username'] ?? '',
             $body['password'] ?? '',
             ($body['is_protected'] ?? '0') ? '1' : '0',
             (int)($body['sort_order'] ?? 0)]
        );
        json_response(['ok' => true, 'id' => $id, 'public_id' => $public_id]);
    } catch (Exception $e) {
        panel_log_exception($e, ['context' => 'playlists.create', 'device_id' => (int)$body['device_id']]);
        json_error('Could not save the playlist. Try again.');
    }
}

if ($action === 'update') {
    if (empty($body['id'])) json_error('missing id');
    $row = db_one('SELECT * FROM playlists WHERE id = ?', [(int)$body['id']]);
    if (!$row) json_error('playlist not found', 404);
    if (array_key_exists('url', $body) && !preg_match('#^https?://#i', trim((string)$body['url']))) {
        json_error('Playlist URL must start with http:// or https://.');
    }
    db_exec(
        'UPDATE playlists SET name = ?, type = ?, url = ?, username = ?, password = ?,
                              is_protected = ?, sort_order = ?
         WHERE id = ?',
        [isset($body['name']) ? trim((string)$body['name']) : $row['name'],
         $body['type']     ?? $row['type'],
         isset($body['url']) ? trim((string)$body['url']) : $row['url'],
         $body['username'] ?? $row['username'],
         $body['password'] ?? $row['password'],
         ($body['is_protected'] ?? $row['is_protected']) ? '1' : '0',
         (int)($body['sort_order'] ?? $row['sort_order']),
         (int)$body['id']]
    );
    json_response(['ok' => true]);
}

if ($action === 'delete') {
    if (empty($body['id'])) json_error('missing id');
    db_exec('DELETE FROM playlists WHERE id = ?', [(int)$body['id']]);
    json_response(['ok' => true]);
}

json_error('unknown action', 400);
