<?php
// api/tools_api.php
session_start();
require_once '../includes/db.php';
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) { echo json_encode(['status'=>false, 'msg'=>'Sessão expirada']); exit; }

$action = $_REQUEST['action'] ?? '';

if ($action == 'mass_replace') {
    $find = $_POST['find'] ?? '';
    $replace = $_POST['replace'] ?? '';
    $targets = $_POST['targets'] ?? []; // Array: ['channels', 'movies', 'series']

    if (empty($find) || empty($targets)) {
        echo json_encode(['status'=>false, 'msg'=>'Preencha o campo de busca e selecione onde aplicar.']);
        exit;
    }

    try {
        $total_changed = 0;
        $pdo->beginTransaction();

        // 1. CANAIS
        if (in_array('channels', $targets)) {
            $stmt = $pdo->prepare("UPDATE channels SET stream_url = REPLACE(stream_url, ?, ?)");
            $stmt->execute([$find, $replace]);
            $total_changed += $stmt->rowCount();
        }

        // 2. FILMES
        if (in_array('movies', $targets)) {
            $stmt = $pdo->prepare("UPDATE movies SET stream_url = REPLACE(stream_url, ?, ?)");
            $stmt->execute([$find, $replace]);
            $total_changed += $stmt->rowCount();
        }

        // 3. SÉRIES (Na verdade, atualiza a tabela episodes)
        if (in_array('series', $targets)) {
            $stmt = $pdo->prepare("UPDATE episodes SET stream_url = REPLACE(stream_url, ?, ?)");
            $stmt->execute([$find, $replace]);
            $total_changed += $stmt->rowCount();
        }

        $pdo->commit();
        echo json_encode(['status'=>true, 'msg'=>"Sucesso! Links atualizados em $total_changed conteúdos."]);

    } catch (Exception $e) {
        $pdo->rollBack();
        echo json_encode(['status'=>false, 'msg'=>'Erro: ' . $e->getMessage()]);
    }
    exit;
}
?>
