<?php
/**
 * api/device/playlist_add.php — POST /api/device/playlist_add
 */

declare(strict_types=1);

require_once __DIR__ . '/../../lib/helpers.php';
require_once __DIR__ . '/../../lib/device.php';

if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') {
    json_out(['ok' => false, 'error' => 'method_not_allowed'], 405);
}

$body = read_json_body();

$macInput = isset($body['mac']) ? (string) $body['mac'] : null;

// Normalization attempt (if MAC address)
$mac = normalize_mac($macInput);

if ($mac === null && !empty($macInput)) {
    $devCheck = db()->prepare('SELECT mac FROM devices WHERE device_key = ? LIMIT 1');
    $devCheck->execute([$macInput]);
    $foundMac = $devCheck->fetchColumn();
    if ($foundMac) {
        $mac = (string) $foundMac;
    }
}

if ($mac === null) {
    json_out(['ok' => false, 'error' => 'invalid mac'], 400);
}

$rawUrl = trim((string) ($body['url'] ?? ''));
if ($rawUrl === '') {
    json_out(['ok' => false, 'error' => 'url required'], 400);
}

// --- DNS MASKING RESOLVER (ID -> Real URL) ---
$url = '';

if (is_numeric($rawUrl)) {
    // Sadece DNS ID gönderildiyse veritabanından adresi alıyoruz
    $dnsStmt = db()->prepare('SELECT url FROM dns WHERE id = ? LIMIT 1');
    $dnsStmt->execute([(int)$rawUrl]);
    $realUrl = $dnsStmt->fetchColumn();
    if ($realUrl) {
        $url = (string) $realUrl;
    } else {
        json_out(['ok' => false, 'error' => 'server not found'], 400);
    }
} elseif (strpos($rawUrl, '|') !== false) {
    // ID ve M3U ek yolu gönderildiyse (örn: "1|get.php?auth=xyz")
    list($dnsId, $m3uPath) = explode('|', $rawUrl, 2);
    if (is_numeric($dnsId)) {
        $dnsStmt = db()->prepare('SELECT url FROM dns WHERE id = ? LIMIT 1');
        $dnsStmt->execute([(int)$dnsId]);
        $baseUrl = $dnsStmt->fetchColumn();
        if ($baseUrl) {
            $url = rtrim((string)$baseUrl, '/') . '/' . ltrim($m3uPath, '/');
        }
    }
}

if ($url === '') {
    // Doğrudan http/https ile başlayan tam M3U URL'si girildiyse
    $url = $rawUrl;
}

$name     = trim((string) ($body['name'] ?? '')) ?: 'My playlist';
$type     = (string) ($body['type'] ?? 'xtream');
$username = (string) ($body['username'] ?? '');
$password = (string) ($body['password'] ?? '');
$editId   = (int) ($body['playlist_id'] ?? 0);

try {
    $device = device_find_by_mac($mac);
    
    if ($device === null) {
        // Cihaz yoksa otomatik oluştur
        $deviceKey = 'IBO-' . strtoupper(substr(md5($mac . time()), 0, 8));
        $stmtIns = db()->prepare('INSERT INTO devices (mac, device_key, account_name, created_at) VALUES (?, ?, ?, NOW())');
        $stmtIns->execute([$mac, $deviceKey, $name]);
        $deviceId = (int) db()->lastInsertId();
    } else {
        $deviceId = (int) $device['id'];
    }

    if ($editId > 0) {
        db()->prepare('UPDATE playlists SET name=?, type=?, url=?, username=?, password=? WHERE id=? AND device_id=?')
            ->execute([$name, $type, $url, $username, $password, $editId, $deviceId]);
        $id = $editId;
    } else {
        $chk = db()->prepare('SELECT id FROM playlists WHERE device_id=? AND type=? AND url=? AND username=? LIMIT 1');
        $chk->execute([$deviceId, $type, $url, $username]);
        $existing = $chk->fetchColumn();
        if ($existing !== false) {
            $id = (int) $existing;
            db()->prepare('UPDATE playlists SET name=?, password=? WHERE id=?')->execute([$name, $password, $id]);
        } else {
            $sortStmt = db()->prepare('SELECT COALESCE(MAX(sort), -1) + 1 FROM playlists WHERE device_id = ?');
            $sortStmt->execute([$deviceId]);
            $sort = (int) $sortStmt->fetchColumn();
            db()->prepare('INSERT INTO playlists (device_id, name, type, url, username, password, protected, sort) VALUES (?, ?, ?, ?, ?, ?, 0, ?)')
                ->execute([$deviceId, $name, $type, $url, $username, $password, $sort]);
            $id = (int) db()->lastInsertId();
        }
    }

    db()->prepare('UPDATE devices SET account_name = ? WHERE id = ? AND (account_name IS NULL OR account_name = "" OR account_name = "-")')
        ->execute([$name, $deviceId]);

    json_out(['ok' => true, 'id' => $id, 'name' => $name], 200);
} catch (Throwable $ex) {
    error_log('[api/device/playlist_add] ' . $ex->getMessage());
    json_out(['ok' => false, 'error' => 'server_error'], 500);
}