<?php
// json-organiser.php
// Drag & drop JSON organiser, cleaner, merger, and M3U generator

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    header('Content-Type: application/json; charset=utf-8');

    $target = $_POST['target'] ?? 'json';
    $all = [];

    // Normalizer: convert ANY JSON format into a unified channel object
    function normalize($item, $group = null) {
        return [
            'name'   => $item['name'] ?? $item['title'] ?? '',
            'url'    => $item['url'] ?? $item['location'] ?? '',
            'id'     => $item['id'] ?? $item['slug'] ?? null,
            'group'  => $group,
            'logo'   => $item['logo'] ?? $item['thumb'] ?? null,
            'tags'   => $item['tags'] ?? [],
            'extra'  => $item
        ];
    }

    // Parse JSON file content
    function parseJson($content) {
        $data = json_decode($content, true);
        $out = [];

        if (!$data) return $out;

        // Format A: { items: [] }
        if (isset($data['items']) && is_array($data['items'])) {
            $group = $data['category'] ?? null;
            foreach ($data['items'] as $item) {
                $out[] = normalize($item, $group);
            }
        }
        // Format B: array of channels
        elseif (isset($data[0]) && is_array($data[0])) {
            foreach ($data as $item) {
                $out[] = normalize($item);
            }
        }

        return $out;
    }

    // Collect uploaded files
    if (!isset($_FILES['files'])) {
        echo json_encode(['error' => 'No files uploaded']);
        exit;
    }

    $files = $_FILES['files'];
    for ($i = 0; $i < count($files['name']); $i++) {
        if ($files['error'][$i] !== UPLOAD_ERR_OK) continue;

        $content = file_get_contents($files['tmp_name'][$i]);
        $ext = strtolower(pathinfo($files['name'][$i], PATHINFO_EXTENSION));

        if ($ext === 'json') {
            foreach (parseJson($content) as $ch) {
                if (!empty($ch['url'])) $all[] = $ch;
            }
        }
    }

    // Deduplicate by URL
    $unique = [];
    $seen = [];
    foreach ($all as $ch) {
        if (!isset($seen[$ch['url']])) {
            $seen[$ch['url']] = true;
            $unique[] = $ch;
        }
    }
    $all = $unique;

    // Output formats
    if ($target === 'm3u') {
        $lines = ["#EXTM3U"];
        foreach ($all as $ch) {
            $attrs = [];
            if ($ch['id']) $attrs[] = 'tvg-id="' . addslashes($ch['id']) . '"';
            if ($ch['logo']) $attrs[] = 'tvg-logo="' . addslashes($ch['logo']) . '"';
            if ($ch['group']) $attrs[] = 'group-title="' . addslashes($ch['group']) . '"';

            $lines[] = "#EXTINF:-1 " . implode(" ", $attrs) . "," . $ch['name'];
            $lines[] = $ch['url'];
        }

        echo json_encode([
            'format' => 'm3u',
            'content' => implode("\n", $lines),
            'count' => count($all)
        ]);
    } else {
        echo json_encode([
            'format' => 'json',
            'items' => $all,
            'count' => count($all)
        ]);
    }

    exit;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSON Organiser & M3U Generator</title>
<style>
body {
    background:#0b0c10;
    color:#fff;
    font-family:Arial, sans-serif;
    display:flex;
    justify-content:center;
    padding:40px;
}
.box {
    width:600px;
    background:#1f2833;
    padding:20px;
    border-radius:12px;
    box-shadow:0 0 20px rgba(0,0,0,0.5);
}
.drop {
    border:2px dashed #45a29e;
    padding:30px;
    text-align:center;
    border-radius:10px;
    cursor:pointer;
}
.drop.dragover {
    background:#45a29e33;
}
textarea {
    width:100%;
    height:250px;
    margin-top:15px;
    background:#0b0c10;
    color:#fff;
    border-radius:8px;
    padding:10px;
    border:none;
    font-family:monospace;
}
button, select {
    padding:10px 15px;
    border-radius:8px;
    border:none;
    margin-top:10px;
}
button {
    background:#66fcf1;
    cursor:pointer;
}
</style>
</head>
<body>
<div class="box">
    <h2>JSON Database Organiser & M3U Generator</h2>

    <div id="drop" class="drop">
        Drop JSON files here<br>
        or click to browse
        <input id="fileInput" type="file" multiple accept=".json" style="display:none;">
    </div>

    <div style="margin-top:10px;">
        Output format:
        <select id="format">
            <option value="json">JSON</option>
            <option value="m3u">M3U Playlist</option>
        </select>
    </div>

    <button id="convert">Combine & Convert</button>

    <textarea id="output" placeholder="Output will appear here..."></textarea>
</div>

<script>
const drop = document.getElementById('drop');
const fileInput = document.getElementById('fileInput');
const convertBtn = document.getElementById('convert');
const output = document.getElementById('output');
let files = [];

drop.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', () => {
    files = Array.from(fileInput.files);
    drop.innerHTML = files.length + " file(s) selected";
});

drop.addEventListener('dragover', e => {
    e.preventDefault();
    drop.classList.add('dragover');
});
drop.addEventListener('dragleave', () => drop.classList.remove('dragover'));
drop.addEventListener('drop', e => {
    e.preventDefault();
    drop.classList.remove('dragover');
    files = Array.from(e.dataTransfer.files);
    drop.innerHTML = files.length + " file(s) selected";
});

convertBtn.addEventListener('click', async () => {
    if (!files.length) {
        output.value = "No files selected";
        return;
    }

    const form = new FormData();
    files.forEach(f => form.append('files[]', f));
    form.append('target', document.getElementById('format').value);

    const res = await fetch("", { method:"POST", body:form });
    const data = await res.json();

    output.value = data.content || JSON.stringify(data, null, 2);
});
</script>
</body>
</html>