<?php
// backend-engine.php
header('Content-Type: application/json; charset=utf-8');

$action = $_GET['action'] ?? 'list';
$q      = $_GET['q'] ?? '';
$channelId = $_GET['channel'] ?? '';
$network = $_GET['network'] ?? '';

$iptvFile      = __DIR__ . '/iptv.json';
$networksFile  = __DIR__ . '/networks.json';
$jsonDir       = __DIR__ . '/json';
$epgBase       = 'https://epg.pw/xmltv/'; // example base, adjust per provider

function loadJsonFile($path) {
    if (!file_exists($path)) return null;
    $data = file_get_contents($path);
    return json_decode($data, true);
}

function saveJsonFile($path, $data) {
    file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

function listNetworks($networksFile) {
    $networks = loadJsonFile($networksFile);
    return $networks ?: ['files' => []];
}

function loadCatalog($iptvFile, $jsonDir, $networksFile) {
    // iptv.json is your merged catalog; if missing, build from networks.json
    $iptv = loadJsonFile($iptvFile);
    if ($iptv) return $iptv;

    $networks = listNetworks($networksFile);
    $catalog = [];
    foreach ($networks['files'] as $file) {
        $path = $jsonDir . '/' . $file;
        $data = loadJsonFile($path);
        if (is_array($data)) {
            $catalog = array_merge($catalog, $data);
        }
    }
    return $catalog;
}

function searchCatalog($catalog, $q) {
    $q = mb_strtolower($q);
    return array_values(array_filter($catalog, function($ch) use ($q) {
        $name = mb_strtolower($ch['name'] ?? '');
        $id   = mb_strtolower($ch['id'] ?? '');
        $tags = mb_strtolower(implode(' ', $ch['tags'] ?? []));
        return (strpos($name, $q) !== false) ||
               (strpos($id, $q) !== false) ||
               (strpos($tags, $q) !== false);
    }));
}

function getChannelById($catalog, $id) {
    foreach ($catalog as $ch) {
        if (($ch['id'] ?? '') === $id) return $ch;
    }
    return null;
}

// Simple EPG proxy (XMLTV -> JSON-ish)
function fetchEpg($channelId, $country = 'nz') {
    // Example: epg.pw or iptv-org/epg; you’ll adapt URL format
    // For demo, we just return a stub
    return [
        'channel' => $channelId,
        'country' => $country,
        'programs' => [
            [
                'title' => 'Sample Show',
                'start' => gmdate('c', time() - 1800),
                'stop'  => gmdate('c', time() + 1800),
                'desc'  => 'Demo EPG entry'
            ]
        ]
    ];
}

// Auto-refresh iptv.json from network JSONs
function refreshCatalog($iptvFile, $jsonDir, $networksFile) {
    $catalog = loadCatalog(null, $jsonDir, $networksFile);
    saveJsonFile($iptvFile, $catalog);
    return ['status' => 'ok', 'count' => count($catalog)];
}

// Pluto/Tubi/etc auto-updater stub (you’d call i.mjh.nz or similar)
function updateExternalProviders() {
    // Example only; you’d fetch remote M3U, convert to JSON, save into /json/*.json
    return ['status' => 'not_implemented', 'message' => 'Wire i.mjh.nz or other scrapers here'];
}

$catalog = loadCatalog($iptvFile, $jsonDir, $networksFile);

switch ($action) {
    case 'list':
        echo json_encode([
            'networks' => listNetworks($networksFile),
            'channels' => $catalog
        ]);
        break;

    case 'search':
        echo json_encode([
            'q' => $q,
            'results' => searchCatalog($catalog, $q)
        ]);
        break;

    case 'channel':
        $ch = getChannelById($catalog, $channelId);
        echo json_encode(['channel' => $ch]);
        break;

    case 'epg':
        $country = $_GET['country'] ?? 'nz';
        echo json_encode(fetchEpg($channelId, $country));
        break;

    case 'refresh':
        echo json_encode(refreshCatalog($iptvFile, $jsonDir, $networksFile));
        break;

    case 'update_providers':
        echo json_encode(updateExternalProviders());
        break;

    default:
        http_response_code(400);
        echo json_encode(['error' => 'Unknown action']);
}