<?php

function slugify($text) {
    $text = strtolower($text);
    $text = preg_replace('/[^a-z0-9]+/', '-', $text);
    $text = trim($text, '-');
    return $text;
}

function detectTags($title) {
    $tags = [];

    $keywords = [
        "news" => "news",
        "sport" => "sports",
        "movie" => "movies",
        "cinema" => "movies",
        "crime" => "crime",
        "comedy" => "comedy",
        "kids" => "kids",
        "music" => "music",
        "documentary" => "documentary",
        "reality" => "reality",
        "car" => "automotive",
        "motor" => "automotive",
        "nature" => "nature",
        "history" => "history"
    ];

    foreach ($keywords as $key => $tag) {
        if (stripos($title, $key) !== false) {
            $tags[] = $tag;
        }
    }

    if (empty($tags)) {
        $tags[] = "tv";
    }

    return array_values(array_unique($tags));
}

function parseM3U($content) {

    $lines = explode("\n", $content);

    $items = [];
    $id = 1;

    $currentTitle = "";

    foreach ($lines as $line) {

        $line = trim($line);

        if (strpos($line, "#EXTINF") === 0) {

            preg_match('/,(.*)$/', $line, $matches);

            $currentTitle = isset($matches[1]) ? trim($matches[1]) : "Unknown";

        } elseif (strpos($line, "http") === 0) {

            $title = $currentTitle ?: "Unknown Channel";

            $items[] = [
                "id" => "med-" . str_pad($id, 3, "0", STR_PAD_LEFT),
                "title" => $title,
                "slug" => slugify($title),
                "type" => "stream",
                "location" => $line,
                "full" => "",
                "thumb" => "",
                "format" => "M3U8",
                "duration" => "Live",
                "description" => $title . " live stream.",
                "tags" => detectTags($title),
                "isLive" => true
            ];

            $id++;
        }
    }

    return $items;
}

$jsonOutput = null;

if ($_SERVER["REQUEST_METHOD"] === "POST") {

    $m3u = $_POST["m3u"] ?? "";

    $items = parseM3U($m3u);

    $jsonOutput = [
        "category" => "media",
        "totalItems" => count($items),
        "items" => $items
    ];
}

?>

<!DOCTYPE html>
<html>
<head>
    <title>M3U → Media.JSON Converter</title>

    <style>
        body {
            font-family: Arial;
            background: #0b0f1a;
            color: white;
            padding: 20px;
        }

        textarea {
            width: 100%;
            height: 300px;
            background: #111827;
            color: white;
            border: 1px solid #333;
            padding: 10px;
        }

        button {
            padding: 12px 20px;
            background: #ff365f;
            color: white;
            border: none;
            cursor: pointer;
            margin-top: 10px;
        }

        pre {
            background: #111827;
            padding: 15px;
            overflow: auto;
            border: 1px solid #333;
        }

        .container {
            max-width: 900px;
            margin: auto;
        }
    </style>
</head>

<body>

<div class="container">

    <h1>M3U → media.json Converter</h1>

    <form method="POST">

        <textarea name="m3u" placeholder="Paste M3U playlist here..."></textarea>

        <button type="submit">Convert</button>

    </form>

<?php if ($jsonOutput): ?>

    <h2>Output JSON</h2>

    <pre id="jsonData"><?php echo json_encode($jsonOutput, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); ?></pre>

    <button onclick="downloadJSON()">Download media.json</button>

    <script>
        function downloadJSON() {

            const data = document.getElementById("jsonData").innerText;

            const blob = new Blob([data], { type: "application/json" });

            const url = URL.createObjectURL(blob);

            const a = document.createElement("a");

            a.href = url;
            a.download = "media.json";

            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);

        }
    </script>

<?php endif; ?>

</div>

</body>
</html>