<?php
require_once dirname(__DIR__) . '/_app_guard.php';
app_guard_validate();
require_once dirname(__DIR__) . '/_device_access.php';
header("Content-Type: application/json");

$dbPath = dirname(__DIR__) . "/db.db";

try {
    $db = new PDO("sqlite:" . $dbPath);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
da_ensure_schema($db);
} catch (Exception $e) {
    echo json_encode(["status" => "erro_db"]);
    exit;
}

$mac = trim($_POST["mac"] ?? "");

if ($mac === "") {
    echo json_encode(["status" => "erro_mac"]);
    exit;
}

/* NORMALIZA MAC (sempre 12 digitos -> AA:BB:CC:DD:EE:FF) */
$mac_clean = preg_replace("/[^A-Fa-f0-9]/", "", $mac);
$mac_clean = strtoupper(substr($mac_clean, 0, 12));

if (strlen($mac_clean) !== 12) {
    echo json_encode(["status" => "erro_mac"]);
    exit;
}

$mac_db = implode(":", str_split($mac_clean, 2));

$content_type  = trim($_POST["content_type"] ?? "");
$content_title = trim($_POST["content_title"] ?? "");
$content_logo  = trim($_POST["content_logo"] ?? "");
$content_url   = trim($_POST["content_url"] ?? "");
$position_ms   = intval($_POST["position_ms"] ?? 0);
$duration_ms   = intval($_POST["duration_ms"] ?? 0);
$is_playing    = intval($_POST["is_playing"] ?? 0);
$app_screen    = trim($_POST["app_screen"] ?? "");
$app_version   = trim($_POST["app_version"] ?? "");
$device_type   = da_normalize_device_type((string)($_POST['device_type'] ?? 'tv'));

$ip  = $_SERVER["REMOTE_ADDR"] ?? "";
$now = time();
$userRow = da_find_user_by_mac($db, $mac_db) ?: null;
$userKey = $userRow ? da_user_key($userRow['username'] ?? '', $userRow['password'] ?? '') : '';
da_update_last_device($db, $mac_db, $device_type);

/* GARANTE TABELA */
$db->exec("
CREATE TABLE IF NOT EXISTS online_status (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    mac TEXT NOT NULL UNIQUE,
    usuario_id INTEGER,
    is_online INTEGER NOT NULL DEFAULT 0,
    content_type TEXT,
    content_title TEXT,
    content_logo TEXT,
    content_url TEXT,
    position_ms INTEGER,
    duration_ms INTEGER,
    is_playing INTEGER,
    app_screen TEXT,
    app_version TEXT,
    ip TEXT,
    last_seen INTEGER,
    created_at INTEGER,
    updated_at INTEGER
);
");

/* GARANTE COLUNA device_type */
try {
    $hasDeviceType = false;
    $st = $db->query("PRAGMA table_info(online_status)");
    while ($r = $st->fetch(PDO::FETCH_ASSOC)) {
        if (($r['name'] ?? '') === 'device_type') { $hasDeviceType = true; break; }
    }
    if (!$hasDeviceType) {
        $db->exec("ALTER TABLE online_status ADD COLUMN device_type TEXT DEFAULT 'tv'");
    }
} catch (Throwable $e) {}

/* VERIFICA SE EXISTE */
$check = $db->prepare("SELECT id FROM online_status WHERE mac = ?");
$check->execute([$mac_db]);
$exists = $check->fetch(PDO::FETCH_ASSOC);

if ($exists) {

    $up = $db->prepare("
        UPDATE online_status SET
            is_online = 1,
            content_type = ?,
            content_title = ?,
            content_logo = ?,
            content_url = ?,
            position_ms = ?,
            duration_ms = ?,
            is_playing = ?,
            app_screen = ?,
            app_version = ?,
            ip = ?,
            device_type = ?,
            last_seen = ?,
            updated_at = ?
        WHERE mac = ?
    ");

    $up->execute([
        $content_type,
        $content_title,
        $content_logo,
        $content_url,
        $position_ms,
        $duration_ms,
        $is_playing,
        $app_screen,
        $app_version,
        $ip,
        $device_type,
        $now,
        $now,
        $mac_db
    ]);

} else {

    $ins = $db->prepare("
        INSERT INTO online_status (
            mac, is_online,
            content_type, content_title, content_logo, content_url,
            position_ms, duration_ms, is_playing,
            app_screen, app_version, ip, device_type,
            last_seen, created_at, updated_at
        ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
    ");

    $ins->execute([
        $mac_db,
        1,
        $content_type,
        $content_title,
        $content_logo,
        $content_url,
        $position_ms,
        $duration_ms,
        $is_playing,
        $app_screen,
        $app_version,
        $ip,
        $device_type,
        $now,
        $now,
        $now
    ]);
}


if ($userKey !== '' && $content_url !== '' && in_array($content_type, ['movie','series','live'], true)) {
    try {
        $sync = $db->prepare("INSERT INTO continue_watching_sync
            (user_key, tipo, nome, logo, url, category, position, duration, last_watched, last_device_type, updated_at)
            VALUES (?, ?, ?, ?, ?, '', ?, ?, ?, ?, ?)
            ON CONFLICT(user_key, tipo, url) DO UPDATE SET
                nome=excluded.nome,
                logo=excluded.logo,
                position=excluded.position,
                duration=excluded.duration,
                last_watched=excluded.last_watched,
                last_device_type=excluded.last_device_type,
                updated_at=excluded.updated_at");
        $sync->execute([$userKey, $content_type, $content_title, $content_logo, $content_url, $position_ms, $duration_ms, $now, $device_type, $now]);
    } catch (Throwable $e) {}
}

echo json_encode([
    "status" => "ok",
    "mac" => $mac_db
]);
