<?php
require_once __DIR__ . '/../includes/bootstrap_api.php';

header('Content-Type: application/json; charset=utf-8');

$cacheDir = dirname(__DIR__) . '/cache/iptv_monitor';
if (!is_dir($cacheDir)) {
    @mkdir($cacheDir, 0755, true);
}

function monitor_fail($message, $code = 400) {
    http_response_code($code);
    echo json_encode([
        'success' => 0,
        'message' => $message,
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);

if (!is_array($data)) {
    monitor_fail('invalid_json');
}

$mac = strtoupper(trim((string)($data['mac'] ?? '')));
$mac = preg_replace('/[^A-F0-9:]/', '', $mac);
$contentName = trim((string)($data['content_name'] ?? ''));
$contentType = strtolower(trim((string)($data['content_type'] ?? '')));
$contentIcon = trim((string)($data['content_icon'] ?? ''));
$device = trim((string)($data['device'] ?? 'Android'));
$state = strtolower(trim((string)($data['state'] ?? 'active')));

if ($mac === '' || !preg_match('/^([A-F0-9]{2}:){5}[A-F0-9]{2}$/', $mac)) {
    monitor_fail('invalid_mac');
}

$fileKey = preg_replace('/[^A-F0-9]/', '', $mac);
$filePath = $cacheDir . '/' . $fileKey . '.json';

if ($state === 'stop') {
    if (file_exists($filePath)) {
        @unlink($filePath);
    }
    echo json_encode([
        'success' => 1,
        'status' => 'removed',
    ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    exit;
}

if ($contentName === '') {
    monitor_fail('content_name_required');
}

if (!in_array($contentType, ['live', 'movie', 'series'], true)) {
    monitor_fail('invalid_content_type');
}

$now = time();
$existing = [];
if (is_file($filePath)) {
    $existingRaw = @file_get_contents($filePath);
    $existingDecoded = json_decode((string)$existingRaw, true);
    if (is_array($existingDecoded)) {
        $existing = $existingDecoded;
    }
}

$firstSeen = (int)($existing['first_seen'] ?? $now);
if ($firstSeen <= 0) {
    $firstSeen = $now;
}

$payload = [
    'mac' => substr($mac, 0, 17),
    'content_name' => substr($contentName, 0, 180),
    'content_type' => $contentType,
    'content_icon' => substr($contentIcon, 0, 500),
    'device' => substr($device, 0, 80),
    'first_seen' => $firstSeen,
    'first_seen_iso' => date('c', $firstSeen),
    'updated_at' => $now,
    'updated_at_iso' => date('c', $now),
];

$tmpPath = $filePath . '.tmp';
@file_put_contents($tmpPath, json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES), LOCK_EX);
@rename($tmpPath, $filePath);

if (function_exists('touch')) {
    @touch($filePath, $payload['updated_at']);
}

echo json_encode([
    'success' => 1,
    'status' => 'ok',
    'ttl_seconds' => 120,
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
