<?php
/**
 * modules/turnero/api/delete_tv_media.php
 * Elimina un ítem de la playlist de la Pantalla TV (archivo + fila).
 * POST JSON: { id: int }
 */

require_once __DIR__ . '/../../../config/config.php';

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

if (!isUserLoggedIn()) {
    http_response_code(401);
    echo json_encode(['ok' => false, 'error' => 'No autenticado']);
    exit;
}

$pdo  = Database::getInstance()->getConnection();
$body = json_decode(file_get_contents('php://input'), true) ?? [];
$id   = (int)($body['id'] ?? 0);

if (!$id) {
    echo json_encode(['ok' => false, 'error' => 'id requerido']);
    exit;
}

$stmt = $pdo->prepare("SELECT url FROM turnero_tv_media WHERE id = ?");
$stmt->execute([$id]);
$row = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$row) {
    echo json_encode(['ok' => false, 'error' => 'No encontrado']);
    exit;
}

$uploadDir = dirname(__DIR__, 3) . '/uploads/turnero/tv_media/';
$filename  = basename(parse_url($row['url'], PHP_URL_PATH));
$filepath  = $uploadDir . $filename;
if (is_file($filepath)) {
    @unlink($filepath);
}

$pdo->prepare("DELETE FROM turnero_tv_media WHERE id = ?")->execute([$id]);

echo json_encode(['ok' => true]);
