<?php
// Autocarga de Composer (requiere vlucas/phpdotenv)
require __DIR__.'/vendor/autoload.php';
use Dotenv\Dotenv;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

// Carga variables de entorno
$dotenv = Dotenv::createImmutable(__DIR__);
$dotenv->load();

// Configurar Monolog para logs del servidor
$log = new Logger('panel-series');
$log->pushHandler(new StreamHandler(__DIR__.'/panel.log', Logger::DEBUG));
$log->info('Script del panel iniciado.');

// Definir credenciales
define('PANEL_USER', $_ENV['PANEL_USER']);
define('PANEL_PASS', $_ENV['PANEL_PASS']);

// Iniciar sesión
session_start();

// Procesar formulario de login
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['login'])) {
    $u = $_POST['user'] ?? '';
    $p = $_POST['pass'] ?? '';
    if ($u === PANEL_USER && $p === PANEL_PASS) {
        $_SESSION['logged_in'] = true;
        $log->info('Inicio de sesión exitoso.', ['user' => $u]);
        header('Location: ' . $_SERVER['PHP_SELF']);
        exit;
    } else {
        $error = 'Usuario o contraseña incorrectos.';
        $log->warning('Intento de inicio de sesión fallido.', ['user' => $u]);
    }
}

// Si no está autenticado, mostramos login
if (empty($_SESSION['logged_in'])):
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title>Login - Panel Series</title>
  <style>
    body{display:flex;align-items:center;justify-content:center;height:100vh;margin:0;background:#f2f2f2;}
    .box{background:#fff;padding:20px;border-radius:6px;box-shadow:0 0 10px rgba(0,0,0,0.1);}
    input{width:100%;padding:10px;margin:8px 0;border:1px solid #ccc;border-radius:4px;}
    button{width:100%;padding:10px;background:#007bff;color:#fff;border:none;border-radius:4px;cursor:pointer;}
    .error{color:#d9534f;margin-bottom:10px;}
  </style>
</head>
<body>
  <div class="box">
    <h2>Acceso Panel Series</h2>
    <?php if(!empty($error)): ?><div class="error"><?= htmlspecialchars($error) ?></div><?php endif; ?>
    <form method="post">
      <input type="text" name="user" placeholder="Usuario" required autofocus>
      <input type="password" name="pass" placeholder="Contraseña" required>
      <button type="submit" name="login">Ingresar</button>
    </form>
  </div>
</body>
</html>
<?php
  exit;
endif;

/***************************************
 * Configuraciones iniciales
 **************************************/
// --- Archivo JSON local ---
$jsonFilePathLocal = __DIR__ . '/series.json';

// Clave y método de encriptación
define('ENCRYPTION_KEY', 'e72of82ke0gu2o2k');
define('ENCRYPTION_METHOD', 'aes-128-ecb');

// Archivo de bandera para la encriptación única
$encryptionFlagFile = __DIR__ . '/encryption.flag';

// API Key de TMDb
$tmdbApiKey = 'eac6b66d86771fe225dfc28551bde098';

/***************************************
 * Funciones de Encriptación/Desencriptación
 ***************************************/
function encrypt_url($plaintext) {
    if (empty($plaintext)) return '';
    if (base64_decode($plaintext, true) !== false) {
        $decrypted_check = @openssl_decrypt(base64_decode($plaintext, true), ENCRYPTION_METHOD, ENCRYPTION_KEY, OPENSSL_RAW_DATA);
        if ($decrypted_check !== false) return $plaintext; // Ya está encriptado
    }
    $ciphertext = openssl_encrypt($plaintext, ENCRYPTION_METHOD, ENCRYPTION_KEY, OPENSSL_RAW_DATA);
    return base64_encode($ciphertext);
}

function decrypt_url($ciphertext_b64) {
    if (empty($ciphertext_b64)) return '';
    $ciphertext = base64_decode($ciphertext_b64, true);
    if ($ciphertext === false) return $ciphertext_b64;
    $plaintext = openssl_decrypt($ciphertext, ENCRYPTION_METHOD, ENCRYPTION_KEY, OPENSSL_RAW_DATA);
    return ($plaintext !== false) ? $plaintext : $ciphertext_b64;
}

function process_all_urls(array &$data, $mode = 'encrypt') {
    if (!isset($data['categorias']) || !is_array($data['categorias'])) return;
    $function_to_call = ($mode === 'encrypt') ? 'encrypt_url' : 'decrypt_url';
    foreach ($data['categorias'] as &$categoria) {
        if (empty($categoria['series'])) continue;
        foreach ($categoria['series'] as &$serie) {
            if (empty($serie['temporadas'])) continue;
            foreach ($serie['temporadas'] as &$temporada) {
                if (empty($temporada['capitulos'])) continue;
                foreach ($temporada['capitulos'] as &$capitulo) {
                    if (isset($capitulo['url'])) $capitulo['url'] = $function_to_call($capitulo['url']);
                }
            }
        }
    }
}

/***************************************
 * Funciones de Manejo de Archivos JSON (Local)
 ***************************************/
function getJsonLocal($path) {
    global $log;
    if (!file_exists($path)) {
        $log->warning("El archivo JSON no existe en {$path}. Se creará uno nuevo.");
        file_put_contents($path, json_encode(['categorias' => []], JSON_PRETTY_PRINT));
        return ['categorias' => []];
    }
    $content = file_get_contents($path);
    if ($content === false) { $log->error("No se pudo leer el archivo JSON en {$path}."); return null; }
    $jsonArray = json_decode($content, true);
    if (json_last_error() !== JSON_ERROR_NONE) { $log->error("Error al decodificar el JSON de {$path}.", ['error' => json_last_error_msg()]); return null; }
    return $jsonArray;
}

function saveJsonLocal($path, $dataArray) {
    global $log;
    $jsonString = json_encode($dataArray, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if (json_last_error() !== JSON_ERROR_NONE) { $log->error("Error al codificar el JSON para guardar.", ['error' => json_last_error_msg()]); return false; }
    if (file_put_contents($path, $jsonString) === false) { $log->error("No se pudo escribir en el archivo JSON en {$path}."); return false; }
    $log->info("Archivo JSON local guardado exitosamente en {$path}.");
    return true;
}

// Función central para guardar los datos localmente
function saveAllData($data, $message) {
    global $jsonFilePathLocal;
    // El parámetro $message ya no es necesario para un commit, pero se mantiene para compatibilidad
    return saveJsonLocal($jsonFilePathLocal, $data);
}


/***************************************
 * Funciones de TMDb para Series (TV)
 ***************************************/
function getTVDetails($tvId,$tmdbApiKey){$url="https://api.themoviedb.org/3/tv/$tvId?api_key=$tmdbApiKey&language=es-ES&append_to_response=images&include_image_language=es,en,null,*";$response=@file_get_contents($url);if(!$response)return[];return json_decode($response,true);}
function searchTVTMDB($query,$tmdbApiKey){$queryEncoded=urlencode($query);$url="https://api.themoviedb.org/3/search/tv?api_key=$tmdbApiKey&query=$queryEncoded&language=es-ES&page=1&include_adult=false";$response=@file_get_contents($url);if(!$response)return[];$data=json_decode($response,true);return $data['results']??[];}
function getTVSeasonDetails($tvId,$seasonNumber,$tmdbApiKey){$url="https://api.themoviedb.org/3/tv/{$tvId}/season/{$seasonNumber}?api_key={$tmdbApiKey}&language=es-ES";$response=@file_get_contents($url);if(!$response)return null;return json_decode($response,true);}
function buscarPrimerPNG(array $lista){foreach($lista as $img){if(!empty($img['file_path'])){$fileTypeLower=strtolower($img['file_type']??'');$isPng=(strpos($fileTypeLower,'png')!==false)||(stripos($img['file_path'],'.png')!==false);if($isPng){return'https://image.tmdb.org/t/p/original'.$img['file_path'];}}}return null;}
function buscarPrimerPNGEnHTML($tmdbId,$lang='hr'){$url="https://www.themoviedb.org/tv/$tmdbId/images/logos?image_language=$lang&language=es-MX";$html=@file_get_contents($url);if(!$html){return null;}if(preg_match('/<img[^>]+src="([^"]+\.png)"[^>]*>/i',$html,$matches)){$pngUrl=$matches[1];return $pngUrl;}return null;}

/***************************************
 * Cargar JSON inicial (Lógica Local)
 ***************************************/
$jsonArray = [];
$log->info('Iniciando carga de JSON desde archivo local...');

$jsonArray = getJsonLocal($jsonFilePathLocal);

if ($jsonArray === null) {
    $log->critical("Error FATAL al obtener el JSON. El script no puede continuar.");
    die("Error al obtener el archivo JSON. Verifica que 'series.json' exista, sea legible y tenga un formato válido. Revisa 'panel.log' para más detalles.");
}
if (!isset($jsonArray['categorias']) || !is_array($jsonArray['categorias'])) {
    $log->warning('La clave "categorias" no existe o no es un array en el JSON. Se inicializará como un array vacío.');
    $jsonArray['categorias'] = [];
}
$log->info('Carga de JSON finalizada.');

/***************************************
 * Variables de estado
 ***************************************/
$searchResults=[];$selectedSeries=null;$errorMsg="";$successMsg="";$localSearchResults=[];$renameCategoryData=null;$addCategoryData=null;$editCategoryData=null;$rawJsonEditData=null;

/***************************************
 * Manejo de acciones (GET/POST)
 ***************************************/

/* 0) Encriptar todas las URLs (acción de único uso) */
if(isset($_POST['action'])&&$_POST['action']==='encrypt_all'&&!file_exists($encryptionFlagFile)){process_all_urls($jsonArray,'encrypt');if(saveAllData($jsonArray,"Encriptación masiva de URLs")){file_put_contents($encryptionFlagFile,date('Y-m-d H:i:s'));$successMsg="¡Éxito! Todas las URLs han sido encriptadas.";$jsonArray=getJsonLocal($jsonFilePathLocal);}else{$errorMsg="Error al guardar el JSON después de encriptar.";}}

/* 1) Buscar series en TMDb */
if(isset($_GET['action'])&&$_GET['action']==='search'&&!empty($_GET['query'])){$query=trim($_GET['query']);$searchResults=searchTVTMDB($query,$tmdbApiKey);}

/* 2) Seleccionar serie de TMDb */
if(isset($_GET['action'])&&$_GET['action']==='select'&&!empty($_GET['id'])){$tmdbId=(int)$_GET['id'];$details=getTVDetails($tmdbId,$tmdbApiKey);if(empty($details['name'])){$errorMsg="No se encontró la serie en TMDb.";}else{$genreString="";if(!empty($details['genres'])){$genres=[];foreach($details['genres'] as $g){if(!empty($g['name'])){$genres[]=$g['name'];}}$genreString=implode(', ',$genres);}$descripcion=$details['overview']??'';$anio=!empty($details['first_air_date'])?substr($details['first_air_date'],0,4):'';$iconPng='';if(!empty($details['images']['logos'])){$logos=$details['images']['logos'];$foundEs=null;$foundEn=null;$foundAny=null;foreach($logos as $logo){if(empty($logo['file_path']))continue;$fileTypeLower=strtolower($logo['file_type']??'');$isPng=(strpos($fileTypeLower,'png')!==false)||(stripos($logo['file_path'],'.png')!==false);if($isPng){$lang=$logo['iso_639_1']??'';if(!$foundAny){$foundAny='https://image.tmdb.org/t/p/original'.$logo['file_path'];}if($lang==='es'&&!$foundEs){$foundEs='https://image.tmdb.org/t/p/original'.$logo['file_path'];}if($lang==='en'&&!$foundEn){$foundEn='https://image.tmdb.org/t/p/original'.$logo['file_path'];}}}$iconPng=$foundEs?:($foundEn?:($foundAny?:''));}if(!$iconPng){$posters=$details['images']['posters']??[];if($posterPng=buscarPrimerPNG($posters)){$iconPng=$posterPng;}else{$backdrops=$details['images']['backdrops']??[];if($backPng=buscarPrimerPNG($backdrops)){$iconPng=$backPng;}}}if(!$iconPng){if($iconFromHtml=buscarPrimerPNGEnHTML($tmdbId,'hr')){$iconPng=$iconFromHtml;}}$selectedSeries=['nombre'=>$details['name']??'','icono'=>'','logoHorizontal'=>'','tmdb_id'=>$tmdbId,'total_seasons'=>$details['number_of_seasons']??0,'genero'=>$genreString,'descripcion'=>$descripcion,'anio'=>$anio,'iconPng'=>$iconPng];if(!empty($details['poster_path'])){$selectedSeries['icono']='https://image.tmdb.org/t/p/original'.$details['poster_path'];}if(!empty($details['images']['backdrops'][0]['file_path'])){$selectedSeries['logoHorizontal']='https://image.tmdb.org/t/p/original'.$details['images']['backdrops'][0]['file_path'];}elseif(!empty($details['backdrop_path'])){$selectedSeries['logoHorizontal']='https://image.tmdb.org/t/p/original'.$details['backdrop_path'];}}}

/* 3) Guardar Nueva Serie */
if(isset($_POST['action'])&&$_POST['action']==='save_new_series'){$seriesName=trim($_POST['nombre']);$seriesIcon=trim($_POST['icono']);$seriesLogo=trim($_POST['logoHorizontal']);$categoriaElegida=trim($_POST['categoria']);$nuevaCategoria=trim($_POST['categoria_nueva']);$postedTmdbId=isset($_POST['tmdb_id'])?(int)$_POST['tmdb_id']:0;$postedTotalSeasons=isset($_POST['tmdb_total_seasons'])?(int)$_POST['tmdb_total_seasons']:0;$seriesGenre=trim($_POST['genero']);$seriesDescription=trim($_POST['descripcion']);$seriesYear=trim($_POST['anio']);$seriesIconPng=trim($_POST['iconPng']);$tmp_temporadas=[];if(!empty($_POST['temporadas'])&&is_array($_POST['temporadas'])){foreach($_POST['temporadas']as $tData){$tempName=trim($tData['nombre']);if($tempName==='')continue;$tempNumber=isset($tData['numero_temporada'])?(int)$tData['numero_temporada']:0;$caps=[];if(isset($tData['capitulos'])&&is_array($tData['capitulos'])){foreach($tData['capitulos']as $capData){$capNumero=(int)$capData['numero'];$capTitulo=trim($capData['titulo']);$capUrl=trim($capData['url']);if($capNumero>0&&$capTitulo!==''&&$capUrl!==''){$caps[]=["numero"=>$capNumero,"titulo"=>$capTitulo,"url"=>encrypt_url($capUrl)];}}}$tmp_temporadas[]=["nombre"=>$tempName,"numero_temporada"=>$tempNumber,"capitulos"=>$caps];}}$existeSerie=false;foreach($jsonArray['categorias']as $cat){if(!isset($cat['series']))continue;foreach($cat['series']as $serie){if(strcasecmp($serie['nombre'],$seriesName)===0){$existeSerie=true;break;}}if($existeSerie)break;}if($existeSerie){$errorMsg="La serie '$seriesName' ya existe.";}else{$nuevaSerie=["nombre"=>$seriesName,"genero"=>$seriesGenre,"descripcion"=>$seriesDescription,"anio"=>$seriesYear,"iconPng"=>$seriesIconPng,"icono"=>$seriesIcon,"logoHorizontal"=>$seriesLogo,"temporadas"=>$tmp_temporadas,"tmdb_id"=>$postedTmdbId,"total_seasons"=>$postedTotalSeasons];if($categoriaElegida==='nueva'&&$nuevaCategoria!==''){$nuevaCat=["nombre"=>$nuevaCategoria,"series"=>[$nuevaSerie]];array_splice($jsonArray['categorias'],rand(0,count($jsonArray['categorias'])),0,[$nuevaCat]);}else{$indiceCat=-1;foreach($jsonArray['categorias']as $index=>$cat){if($cat['nombre']===$categoriaElegida){$indiceCat=$index;break;}}if($indiceCat>=0){if(!isset($jsonArray['categorias'][$indiceCat]['series'])){$jsonArray['categorias'][$indiceCat]['series']=[];}$jsonArray['categorias'][$indiceCat]['series'][]=$nuevaSerie;}else{$errorMsg="No se encontró la categoría '$categoriaElegida'.";}}if(!$errorMsg){if(saveAllData($jsonArray,"Agregando serie: $seriesName")){$successMsg="¡Serie '$seriesName' agregada!";$jsonArray=getJsonLocal($jsonFilePathLocal);}else{$errorMsg="Error al guardar el JSON.";}}}}

/* 4) Solicitar edición de una serie existente */
$editSerieData=null;if(isset($_GET['action'])&&$_GET['action']==='edit_series'){$catIndex=isset($_GET['cat_index'])?(int)$_GET['cat_index']:-1;$serieIndex=isset($_GET['serie_index'])?(int)$_GET['serie_index']:-1;if(isset($jsonArray['categorias'][$catIndex]['series'][$serieIndex])){$editSerieData=['catIndex'=>$catIndex,'serieIndex'=>$serieIndex,'serie'=>$jsonArray['categorias'][$catIndex]['series'][$serieIndex]];if(!empty($editSerieData['serie']['temporadas'])){foreach($editSerieData['serie']['temporadas']as &$temporada){if(empty($temporada['capitulos']))continue;foreach($temporada['capitulos']as &$capitulo){if(isset($capitulo['url'])){$capitulo['url']=decrypt_url($capitulo['url']);}}}}}else{$errorMsg="No se encontró la serie a editar.";}}

/* 5) Guardar cambios en serie existente */
if(isset($_POST['action'])&&$_POST['action']==='save_edit_series'){$catIndex=(int)$_POST['cat_index'];$serieIndex=(int)$_POST['serie_index'];if(isset($jsonArray['categorias'][$catIndex]['series'][$serieIndex])){$seriesName=trim($_POST['nombre']);$seriesIcon=trim($_POST['icono']);$seriesLogo=trim($_POST['logoHorizontal']);$postedTmdbId=isset($_POST['tmdb_id'])?(int)$_POST['tmdb_id']:0;$postedTotalSeasons=isset($_POST['tmdb_total_seasons'])?(int)$_POST['tmdb_total_seasons']:0;$seriesGenre=trim($_POST['genero']);$seriesDescription=trim($_POST['descripcion']);$seriesYear=trim($_POST['anio']);$seriesIconPng=trim($_POST['iconPng']);$tempDataArr=$_POST['temporadas']??[];$nuevo_array_temporadas=[];if(is_array($tempDataArr)){foreach($tempDataArr as $tData){$tempName=trim($tData['nombre']);if($tempName==='')continue;$tempNumber=isset($tData['numero_temporada'])?(int)$tData['numero_temporada']:0;$caps=[];if(isset($tData['capitulos'])&&is_array($tData['capitulos'])){foreach($tData['capitulos']as $capData){$num=(int)$capData['numero'];$title=trim($capData['titulo']);$url=trim($capData['url']);if($num>0&&$title!==''&&$url!==''){$caps[]=["numero"=>$num,"titulo"=>$title,"url"=>encrypt_url($url)];}}}$nuevo_array_temporadas[]=["nombre"=>$tempName,"numero_temporada"=>$tempNumber,"capitulos"=>$caps];}}$jsonArray['categorias'][$catIndex]['series'][$serieIndex]['nombre']=$seriesName;$jsonArray['categorias'][$catIndex]['series'][$serieIndex]['icono']=$seriesIcon;$jsonArray['categorias'][$catIndex]['series'][$serieIndex]['logoHorizontal']=$seriesLogo;$jsonArray['categorias'][$catIndex]['series'][$serieIndex]['temporadas']=$nuevo_array_temporadas;$jsonArray['categorias'][$catIndex]['series'][$serieIndex]['tmdb_id']=$postedTmdbId;$jsonArray['categorias'][$catIndex]['series'][$serieIndex]['total_seasons']=$postedTotalSeasons;$jsonArray['categorias'][$catIndex]['series'][$serieIndex]['genero']=$seriesGenre;$jsonArray['categorias'][$catIndex]['series'][$serieIndex]['descripcion']=$seriesDescription;$jsonArray['categorias'][$catIndex]['series'][$serieIndex]['anio']=$seriesYear;$jsonArray['categorias'][$catIndex]['series'][$serieIndex]['iconPng']=$seriesIconPng;$newSeriesPositionInput=isset($_POST['new_series_position'])?(int)$_POST['new_series_position']:($serieIndex+1);$newSeriesPosition=$newSeriesPositionInput-1;if($newSeriesPosition!==$serieIndex){$serieData=$jsonArray['categorias'][$catIndex]['series'][$serieIndex];array_splice($jsonArray['categorias'][$catIndex]['series'],$serieIndex,1);$seriesCount=count($jsonArray['categorias'][$catIndex]['series']);if($newSeriesPosition<0)$newSeriesPosition=0;if($newSeriesPosition>$seriesCount)$newSeriesPosition=$seriesCount;array_splice($jsonArray['categorias'][$catIndex]['series'],$newSeriesPosition,0,[$serieData]);}if(saveAllData($jsonArray,"Editando serie: $seriesName")){$successMsg="¡Serie '$seriesName' actualizada!";$jsonArray=getJsonLocal($jsonFilePathLocal);}else{$errorMsg="Error al guardar el JSON.";}}else{$errorMsg="Los índices de categoría/serie no existen.";}}

/* 6) Endpoint AJAX para episodios */
if(isset($_GET['action'])&&$_GET['action']==='fetch_episodes'){if(!empty($_GET['tv_id'])&&!empty($_GET['season_number'])){$tvId=(int)$_GET['tv_id'];$seasonNumber=(int)$_GET['season_number'];$seasonData=getTVSeasonDetails($tvId,$seasonNumber,$tmdbApiKey);if(!$seasonData||empty($seasonData['episodes'])){echo json_encode(['episodes'=>[]]);exit;}$episodesArr=[];foreach($seasonData['episodes']as $ep){$episodesArr[]=['episode_number'=>$ep['episode_number']??0,'name'=>$ep['name']??'Sin título'];}echo json_encode(['episodes'=>$episodesArr]);exit;}else{echo json_encode(['episodes'=>[]]);exit;}}

/* 7) Buscar series en JSON local */
if(isset($_GET['action'])&&$_GET['action']==='local_search'&&!empty($_GET['q'])){$q=strtolower(trim($_GET['q']));foreach($jsonArray['categorias']as $cat_i=>$cat){if(empty($cat['series']))continue;foreach($cat['series']as $ser_i=>$ser){$nombreSerie=strtolower($ser['nombre']??'');if(strpos($nombreSerie,$q)!==false){$localSearchResults[]=['cat_index'=>$cat_i,'serie_index'=>$ser_i,'cat_nombre'=>$cat['nombre'],'nombre'=>$ser['nombre']];}}}}

/* 8) Eliminar una serie */
if(isset($_GET['action'])&&$_GET['action']==='delete_series'){$catIndex=isset($_GET['cat_index'])?(int)$_GET['cat_index']:-1;$serieIndex=isset($_GET['serie_index'])?(int)$_GET['serie_index']:-1;if(isset($jsonArray['categorias'][$catIndex]['series'][$serieIndex])){$serieName=$jsonArray['categorias'][$catIndex]['series'][$serieIndex]['nombre']??'Sin nombre';array_splice($jsonArray['categorias'][$catIndex]['series'],$serieIndex,1);if(saveAllData($jsonArray,"Eliminando serie: $serieName")){$successMsg="¡Serie '$serieName' eliminada!";$jsonArray=getJsonLocal($jsonFilePathLocal);}else{$errorMsg="Error al eliminar la serie.";}}else{$errorMsg="No se encontró la serie para eliminar.";}}

/* 9) Mostrar formulario para copiar serie a otra categoría */
if(isset($_GET['action'])&&$_GET['action']==='add_to_other_category'){$catIndex=isset($_GET['cat_index'])?(int)$_GET['cat_index']:-1;$serieIndex=isset($_GET['serie_index'])?(int)$_GET['serie_index']:-1;if(isset($jsonArray['categorias'][$catIndex]['series'][$serieIndex])){$addCategoryData=['catIndex'=>$catIndex,'serieIndex'=>$serieIndex,'serie'=>$jsonArray['categorias'][$catIndex]['series'][$serieIndex]];}else{$errorMsg="No se encontró la serie para copiar.";}}

/* 10) Copiar serie a otra categoría */
if(isset($_POST['action'])&&$_POST['action']==='do_add_to_category'){$catIndex=(int)$_POST['cat_index'];$serieIndex=(int)$_POST['serie_index'];$categoriaNueva=trim($_POST['categoria_nueva']);if(isset($jsonArray['categorias'][$catIndex]['series'][$serieIndex])){$serieCopiar=$jsonArray['categorias'][$catIndex]['series'][$serieIndex];$nombreSerie=$serieCopiar['nombre']??'Sin nombre';$destIndex=-1;foreach($jsonArray['categorias']as $i=>$cat){if($cat['nombre']===$categoriaNueva){$destIndex=$i;break;}}if($destIndex>=0){$jsonArray['categorias'][$destIndex]['series'][]=$serieCopiar;if(saveAllData($jsonArray,"Copiando serie: $nombreSerie -> $categoriaNueva")){$successMsg="¡Serie '$nombreSerie' copiada a '$categoriaNueva'!";$jsonArray=getJsonLocal($jsonFilePathLocal);}else{$errorMsg="Error al copiar serie.";}}else{$errorMsg="No se encontró la categoría '$categoriaNueva'.";}}else{$errorMsg="No se encontró la serie para copiar.";}}

/* 11) Solicitar edición de posición de categoría */
if(isset($_GET['action'])&&$_GET['action']==='edit_category'){$catIndex=isset($_GET['cat_index'])?(int)$_GET['cat_index']:-1;if($catIndex<0||!isset($jsonArray['categorias'][$catIndex])){$errorMsg="Categoría inválida.";}else{$editCategoryData=['catIndex'=>$catIndex,'categoria'=>$jsonArray['categorias'][$catIndex]];}}

/* 12) Guardar nueva posición de categoría */
if(isset($_POST['action'])&&$_POST['action']==='save_edit_category'){$catIndex=(int)$_POST['cat_index'];$newPositionInput=(int)$_POST['new_position'];$newPosition=$newPositionInput-1;$totalCats=count($jsonArray['categorias']);if($newPosition<0)$newPosition=0;if($newPosition>=$totalCats)$newPosition=$totalCats-1;if(!isset($jsonArray['categorias'][$catIndex])){$errorMsg="Categoría inválida.";}else{if($newPosition!=$catIndex){$movedCategory=$jsonArray['categorias'][$catIndex];array_splice($jsonArray['categorias'],$catIndex,1);array_splice($jsonArray['categorias'],$newPosition,0,[$movedCategory]);if(saveAllData($jsonArray,"Reordenando categorías")){$successMsg="Categoría movida correctamente.";$jsonArray=getJsonLocal($jsonFilePathLocal);}else{$errorMsg="Error al mover categoría.";}}else{$successMsg="La categoría ya está en esa posición.";}}}

/* 13) Solicitar cambio de nombre de categoría */
if(isset($_GET['action'])&&$_GET['action']==='rename_category'){$catIndex=isset($_GET['cat_index'])?(int)$_GET['cat_index']:-1;if($catIndex<0||!isset($jsonArray['categorias'][$catIndex])){$errorMsg="Categoría inválida.";}else{$renameCategoryData=['catIndex'=>$catIndex,'categoria'=>$jsonArray['categorias'][$catIndex]];}}

/* 14) Guardar nuevo nombre de categoría */
if(isset($_POST['action'])&&$_POST['action']==='save_rename_category'){$catIndex=(int)$_POST['cat_index'];$newName=trim($_POST['new_name']);if(!isset($jsonArray['categorias'][$catIndex])){$errorMsg="Categoría inválida.";}else if($newName===''){ $errorMsg="El nuevo nombre no puede estar vacío.";}else{$oldName=$jsonArray['categorias'][$catIndex]['nombre'];$jsonArray['categorias'][$catIndex]['nombre']=$newName;if(saveAllData($jsonArray,"Renombrando categoría: $oldName -> $newName")){$successMsg="¡Categoría renombrada!";$jsonArray=getJsonLocal($jsonFilePathLocal);}else{$errorMsg="Error al renombrar la categoría.";}}}

/* 15) Mostrar el editor de JSON manual */
if(isset($_GET['action'])&&$_GET['action']==='edit_raw_json'){$jsonArrayTemp=$jsonArray;process_all_urls($jsonArrayTemp,'decrypt');$rawJsonEditData=json_encode($jsonArrayTemp,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES);}

/* 16) Guardar el JSON del editor manual */
if(isset($_POST['action'])&&$_POST['action']==='save_raw_json'){
    $rawJson=$_POST['raw_json_content']??'';$newData=json_decode($rawJson,true);
    if(json_last_error()===JSON_ERROR_NONE){
        process_all_urls($newData,'encrypt');
        if(saveJsonLocal($jsonFilePathLocal,$newData)){
            $successMsg="JSON guardado manualmente.";
            $jsonArray=getJsonLocal($jsonFilePathLocal);
        }else{$errorMsg="Error al guardar el archivo JSON local.";}
    }else{$errorMsg="El JSON no es válido. Error: ".json_last_error_msg();$rawJsonEditData=$rawJson;}
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
    <meta charset="UTF-8">
    <title>Panel Admin - Series</title>
    <style>
        body { background: #f4f4f4; margin: 0; padding: 0; font-family: sans-serif; }
        .container { max-width: 1200px; margin: 30px auto; background: #fff; padding: 25px; border-radius: 8px; box-shadow: 0 0 10px rgba(0,0,0,0.1); }
        .error { color: #d9534f; font-weight: bold; margin-bottom: 15px; border: 1px solid #d9534f; padding: 10px; border-radius: 4px; }
        .success { color: #5cb85c; font-weight: bold; margin-bottom: 15px; border: 1px solid #5cb85c; padding: 10px; border-radius: 4px; }
        h1, h2, h3, h4 { margin: 0 0 15px; font-weight: normal; }
        .block { margin-bottom: 30px; border-bottom: 1px solid #dedede; padding-bottom: 20px; }
        .block h2 { font-size: 1.4em; margin-bottom: 10px; border-bottom: 1px solid #ececec; }
        .input-group { margin-bottom: 12px; }
        .label { display: inline-block; width: 200px; font-weight: bold; vertical-align: top; }
        input[type="text"], input[type="number"], select, textarea { width: 70%; padding: 6px; margin-left: 5px; box-sizing: border-box; }
        textarea { resize: vertical; min-height: 150px; }
        button { padding: 8px 16px; background: #007bff; color: #fff; border: none; cursor: pointer; border-radius: 4px; }
        button:hover { background: #0056b3; }
        .category-list h3 { margin-top: 20px; }
        .mini-button { background: #28a745; padding: 4px 8px; font-size: 0.9em; border-radius: 3px; margin-left: 5px; color: #fff; text-decoration: none; }
        .mini-button:hover { background: #218838; }
        ul, li { margin: 0; padding: 0; list-style: none; }
        ul { margin-left: 20px; }
        .episode-block, .season-block { background: #f8f8f8; border: 1px solid #dedede; padding: 10px; margin: 10px 0; position: relative; }
        .episode-block + .episode-block { margin-top: 5px; }
        .btn-add { background: #28a745; margin: 5px 0; }
        .btn-add:hover { background: #218838; }
        .sub-label { display: inline-block; width: 60px; }
        .btn-remove { background: #dc3545; color: #fff; border: none; font-size: 0.9em; padding: 5px 10px; margin-left: 10px; cursor: pointer; border-radius: 3px; }
        .btn-remove:hover { background: #c82333; }
        .season-remove-btn { position: absolute; top: 10px; right: 10px; }
        .episode-remove-btn { margin-left: 10px; }
        .local-search-results { margin-top: 15px; }
        .danger-zone { border: 2px solid #dc3545; padding: 15px; margin-top: 20px; background-color: #fbeaea; }
        .danger-zone h2 { color: #dc3545; }
        .danger-zone button { background: #dc3545; }
        .danger-zone button:hover { background: #c82333; }
    </style>
    <script>
    let seasonCountNew = 0; let nextSeasonNumber = 1; let nextEpisodeNumberBySeason = {}; let episodesCache = {};
    async function loadSeasonEpisodesFromTMDB(tvId, seasonNumber, seasonIndex) { if (tvId <= 0 || seasonNumber <= 0) return; const url = `?action=fetch_episodes&tv_id=${tvId}&season_number=${seasonNumber}`; try { const resp = await fetch(url); const data = await resp.json(); episodesCache[seasonIndex] = data.episodes || []; } catch (err) { console.error("Error fetch_episodes:", err); episodesCache[seasonIndex] = []; } }
    async function addSeason(containerId) { const container = document.getElementById(containerId); if (!container) return; const tmdbIdInput = document.getElementById('tmdb_id_global'); const totalSeasonsIn = document.getElementById('tmdb_total_seasons_global'); const tvId = tmdbIdInput ? parseInt(tmdbIdInput.value) : 0; const totalSeasons = totalSeasonsIn ? parseInt(totalSeasonsIn.value) : 0; const seasonIndex = seasonCountNew++; const seasonDiv = document.createElement('div'); seasonDiv.className = 'season-block'; seasonDiv.id = 'season-block-' + seasonIndex; let assignedSeasonNumber = nextSeasonNumber; if (nextSeasonNumber > totalSeasons && totalSeasons > 0) { assignedSeasonNumber = nextSeasonNumber; } const defaultSeasonName = "Temporada " + nextSeasonNumber; seasonDiv.innerHTML = ` <div class="input-group"> <label><strong>Nombre Temporada:</strong></label> <input type="text" name="temporadas[${seasonIndex}][nombre]" value="${defaultSeasonName}" /> <input type="hidden" name="temporadas[${seasonIndex}][numero_temporada]" id="season-number-${seasonIndex}" value="${assignedSeasonNumber}"> </div> <div><strong>Capítulos:</strong></div> <div id="episodes-container-${seasonIndex}"></div> <button type="button" class="btn-add" onclick="addEpisode(${seasonIndex}, 'episodes-container-${seasonIndex}')"> + Añadir Capítulo </button> <button type="button" class="btn-remove season-remove-btn" onclick="removeSeason(${seasonIndex})"> Eliminar Temporada </button> `; container.appendChild(seasonDiv); nextEpisodeNumberBySeason[seasonIndex] = 1; if (tvId > 0 && assignedSeasonNumber <= totalSeasons) { await loadSeasonEpisodesFromTMDB(tvId, assignedSeasonNumber, seasonIndex); } else { episodesCache[seasonIndex] = []; } addEpisode(seasonIndex, `episodes-container-${seasonIndex}`); nextSeasonNumber++; updateSeasonRemoveButtons(containerId); }
    function removeSeason(seasonIndex) { const seasonDiv = document.getElementById(`season-block-${seasonIndex}`); if (!seasonDiv) return; seasonDiv.parentNode.removeChild(seasonDiv); updateSeasonRemoveButtons(seasonDiv.parentNode.id); }
    function updateSeasonRemoveButtons(containerId) { const container = document.getElementById(containerId); if (!container) return; const seasonBlocks = container.querySelectorAll('.season-block'); if (seasonBlocks.length <= 1) { seasonBlocks.forEach(sb => { const btnRemove = sb.querySelector('.season-remove-btn'); if (btnRemove) btnRemove.style.display = 'none'; }); } else { seasonBlocks.forEach(sb => { const btnRemove = sb.querySelector('.season-remove-btn'); if (btnRemove) btnRemove.style.display = 'inline-block'; }); } }
    function addEpisode(seasonIndex, episodesContainerId, existingNumber=null, existingTitle='', existingUrl='') { const episodesContainer = document.getElementById(episodesContainerId); if (!episodesContainer) return; if (!nextEpisodeNumberBySeason.hasOwnProperty(seasonIndex)) { nextEpisodeNumberBySeason[seasonIndex] = 1; } const subIndex = episodesContainer.querySelectorAll('.episode-block').length; let epNumber = (existingNumber !== null) ? existingNumber : nextEpisodeNumberBySeason[seasonIndex]; let epTitle = existingTitle; let epUrl = existingUrl; if (!epTitle) { const cachedEps = episodesCache[seasonIndex] || []; const foundEp = cachedEps.find(e => e.episode_number === epNumber); if (foundEp) { epTitle = foundEp.name; } } const episodeId = `episode-block-${seasonIndex}-${subIndex}`; const episodeDiv = document.createElement('div'); episodeDiv.className = 'episode-block'; episodeDiv.id = episodeId; episodeDiv.innerHTML = ` <input type="hidden" name="temporadas[${seasonIndex}][capitulos][${subIndex}][numero]" value="${epNumber}"> <div> <label class="sub-label">#${epNumber}</label> <label>Título:</label> <input type="text" name="temporadas[${seasonIndex}][capitulos][${subIndex}][titulo]" value="${escapeHtml(epTitle)}" style="width:200px" placeholder="Cap. X"> <label>URL:</label> <input type="text" name="temporadas[${seasonIndex}][capitulos][${subIndex}][url]" value="${escapeHtml(epUrl)}" style="width:200px" placeholder="http://..."> <button type="button" class="btn-remove episode-remove-btn" onclick="removeEpisode('${seasonIndex}','${episodeId}')">Eliminar Capítulo</button> </div> `; episodesContainer.appendChild(episodeDiv); if (existingNumber === null) { nextEpisodeNumberBySeason[seasonIndex]++; } else { if (existingNumber >= nextEpisodeNumberBySeason[seasonIndex]) { nextEpisodeNumberBySeason[seasonIndex] = existingNumber + 1; } } updateEpisodeRemoveButtons(episodesContainerId); }
    function removeEpisode(seasonIndex, episodeId) { const epBlock = document.getElementById(episodeId); if (!epBlock) return; epBlock.parentNode.removeChild(epBlock); updateEpisodeRemoveButtons(epBlock.parentNode.id); }
    function updateEpisodeRemoveButtons(episodesContainerId) { const episodesContainer = document.getElementById(episodesContainerId); if (!episodesContainer) return; const episodeBlocks = episodesContainer.querySelectorAll('.episode-block'); if (episodeBlocks.length <= 1) { episodeBlocks.forEach(eb => { const btnRemove = eb.querySelector('.episode-remove-btn'); if (btnRemove) btnRemove.style.display = 'none'; }); } else { episodeBlocks.forEach(eb => { const btnRemove = eb.querySelector('.episode-remove-btn'); if (btnRemove) btnRemove.style.display = 'inline-block'; }); } }
    async function initEditForm(existingSeasons, existingTmdbId, existingTotalSeasons) { const container = document.getElementById('edit-seasons-container'); if (!container) return; const tmdbIdGlobal = document.getElementById('tmdb_id_global'); const totalSeasonsGlobal = document.getElementById('tmdb_total_seasons_global'); if (tmdbIdGlobal) tmdbIdGlobal.value = existingTmdbId; if (totalSeasonsGlobal) totalSeasonsGlobal.value = existingTotalSeasons; nextSeasonNumber = existingSeasons.length + 1; for (let i = 0; i < existingSeasons.length; i++) { const temp = existingSeasons[i]; const seasonIndex = seasonCountNew++; const seasonDiv = document.createElement('div'); seasonDiv.className = 'season-block'; seasonDiv.id = 'season-block-' + seasonIndex; let tempNumber = parseInt(temp.numero_temporada) || (i+1); seasonDiv.innerHTML = ` <div class="input-group"> <label><strong>Nombre Temporada:</strong></label> <input type="text" name="temporadas[${seasonIndex}][nombre]" value="${escapeHtml(temp.nombre)}" /> <input type="hidden" name="temporadas[${seasonIndex}][numero_temporada]" id="season-number-${seasonIndex}" value="${tempNumber}"> </div> <div><strong>Capítulos:</strong></div> <div id="episodes-container-${seasonIndex}"></div> <button type="button" class="btn-add" onclick="addEpisode(${seasonIndex}, 'episodes-container-${seasonIndex}')"> + Añadir Capítulo </button> <button type="button" class="btn-remove season-remove-btn" onclick="removeSeason(${seasonIndex})"> Eliminar Temporada </button> `; container.appendChild(seasonDiv); nextEpisodeNumberBySeason[seasonIndex] = 1; episodesCache[seasonIndex] = []; if (existingTmdbId > 0 && tempNumber > 0 && tempNumber <= existingTotalSeasons) { await loadSeasonEpisodesFromTMDB(existingTmdbId, tempNumber, seasonIndex); } if (Array.isArray(temp.capitulos)) { temp.capitulos.forEach(cap => { addEpisode( seasonIndex, `episodes-container-${seasonIndex}`, cap.numero, cap.titulo, cap.url ); }); } else { addEpisode(seasonIndex, `episodes-container-${seasonIndex}`); } updateEpisodeRemoveButtons(`episodes-container-${seasonIndex}`); } updateSeasonRemoveButtons('edit-seasons-container'); }
    function escapeHtml(str) { var p = document.createElement("p"); p.textContent = str; return p.innerHTML; }
    </script>
</head>
<body>

<div class="container">
    <h1>Panel de Administración de Series</h1>
    <?php if ($errorMsg): ?><div class="error"><?= htmlspecialchars($errorMsg) ?></div><?php endif; ?>
    <?php if ($successMsg): ?><div class="success"><?= htmlspecialchars($successMsg) ?></div><?php endif; ?>
    <?php if (isset($rawJsonEditData)): ?>
        <div class="block">
            <h2>Editor Manual de JSON</h2>
            <p><strong>¡Atención!</strong> Estás editando el JSON completo. Las URLs se muestran desencriptadas. Al guardar, serán re-encriptadas y guardadas en el archivo local.</p>
            <form method="post" action=""><input type="hidden" name="action" value="save_raw_json"><textarea name="raw_json_content" style="width: 100%; height: 500px; font-family: monospace;"><?= htmlspecialchars($rawJsonEditData) ?></textarea><br><br><button type="submit">Guardar JSON Manualmente</button><a href="<?= $_SERVER['PHP_SELF'] ?>" style="margin-left: 10px;">Cancelar</a></form>
        </div>
    <?php else: ?>
        <?php if (isset($renameCategoryData) && $renameCategoryData): ?>
            <div class="block">
                <h2>Cambiar Nombre de Categoría: <?= htmlspecialchars($renameCategoryData['categoria']['nombre']) ?></h2>
                <form method="post" action=""><input type="hidden" name="action" value="save_rename_category"><input type="hidden" name="cat_index" value="<?= $renameCategoryData['catIndex'] ?>"><div class="input-group"><label class="label" for="new_name">Nuevo Nombre:</label><input type="text" name="new_name" id="new_name" value="<?= htmlspecialchars($renameCategoryData['categoria']['nombre']) ?>" required></div><button type="submit">Guardar</button></form>
            </div>
        <?php endif; ?>
        <div class="block">
            <h2>1) Buscar Serie (TMDb)</h2>
            <form method="get" action=""><input type="hidden" name="action" value="search" /><div class="input-group"><label class="label" for="query">Título Serie (para agregar nueva):</label><input type="text" name="query" id="query" placeholder="Ej: The Office" required /></div><button type="submit">Buscar en TMDb</button></form>
            <?php if (!empty($searchResults)): ?><h3>Resultados:</h3><ul><?php foreach ($searchResults as $r): $title=$r['name']??'';$year=substr($r['first_air_date']??'',0,4);$tmdbId=$r['id']??0;?><li><?= htmlspecialchars($title) ?> (<?= htmlspecialchars($year) ?>) <a class="mini-button" href="?action=select&id=<?= $tmdbId ?>">[Seleccionar]</a></li><?php endforeach; ?></ul><?php endif; ?>
        </div>
        <div class="block">
            <h2>2) Agregar Nueva Serie</h2>
            <?php if ($selectedSeries): ?>
                <form method="post" action=""><input type="hidden" name="action" value="save_new_series" /><input type="hidden" id="tmdb_id_global" name="tmdb_id" value="<?= $selectedSeries['tmdb_id'] ?? '' ?>"><input type="hidden" id="tmdb_total_seasons_global" name="tmdb_total_seasons" value="<?= $selectedSeries['total_seasons'] ?? 0 ?>">
                <div class="input-group"><label class="label" for="nombre">Título Serie:</label><input type="text" name="nombre" id="nombre" value="<?= htmlspecialchars($selectedSeries['nombre']) ?>" required /></div><div class="input-group"><label class="label" for="genero">Género:</label><input type="text" name="genero" id="genero" value="<?= htmlspecialchars($selectedSeries['genero']) ?>" /></div><div class="input-group"><label class="label" for="descripcion">Sinopsis:</label><textarea name="descripcion" id="descripcion"><?= htmlspecialchars($selectedSeries['descripcion']) ?></textarea></div><div class="input-group"><label class="label" for="anio">Año:</label><input type="text" name="anio" id="anio" value="<?= htmlspecialchars($selectedSeries['anio']) ?>" /></div><div class="input-group"><label class="label" for="iconPng">Icono PNG:</label><input type="text" name="iconPng" id="iconPng" value="<?= htmlspecialchars($selectedSeries['iconPng']) ?>" /></div><div class="input-group"><label class="label" for="icono">Icono (Poster):</label><input type="text" name="icono" id="icono" value="<?= htmlspecialchars($selectedSeries['icono']) ?>" /></div><div class="input-group"><label class="label" for="logoHorizontal">Fondo (Backdrop):</label><input type="text" name="logoHorizontal" id="logoHorizontal" value="<?= htmlspecialchars($selectedSeries['logoHorizontal']) ?>" /></div>
                <h3>Temporadas / Capítulos</h3><p>Puedes agregar temporadas y capítulos (se autocompletarán si hay datos en TMDb).</p><div id="new-seasons-container"></div><button type="button" class="btn-add" onclick="addSeason('new-seasons-container')">+ Añadir Temporada</button>
                <h3>Categoría</h3><div class="input-group"><label class="label" for="categoria">Categoría:</label><select name="categoria" id="categoria"><?php foreach ($jsonArray['categorias'] as $cat): ?><option value="<?= htmlspecialchars($cat['nombre']) ?>"><?= htmlspecialchars($cat['nombre']) ?></option><?php endforeach; ?><option value="nueva">-- Nueva categoría --</option></select></div><div class="input-group"><label class="label" for="categoria_nueva">Nombre Nueva Cat:</label><input type="text" name="categoria_nueva" id="categoria_nueva" placeholder="Solo si elegiste 'nueva'" /></div><br><button type="submit">Guardar Serie</button></form>
                <script>addSeason('new-seasons-container');</script>
            <?php else: ?><p>Busca y selecciona una serie en TMDb para agregarla.</p><?php endif; ?>
        </div>
        <?php if ($editSerieData): $catIndex=$editSerieData['catIndex'];$serieIndex=$editSerieData['serieIndex'];$serieEdit=$editSerieData['serie'];$editTmdbId=isset($serieEdit['tmdb_id'])?(int)$serieEdit['tmdb_id']:0;$editTotalSeasons=isset($serieEdit['total_seasons'])?(int)$serieEdit['total_seasons']:0;?>
        <div class="block">
            <h2>Editar Serie: <?= htmlspecialchars($serieEdit['nombre'] ?? '') ?></h2>
            <form method="post" action=""><input type="hidden" name="action" value="save_edit_series" /><input type="hidden" name="cat_index" value="<?= $catIndex ?>" /><input type="hidden" name="serie_index" value="<?= $serieIndex ?>" /><input type="hidden" id="tmdb_id_global" name="tmdb_id" value="<?= $editTmdbId ?>"><input type="hidden" id="tmdb_total_seasons_global" name="tmdb_total_seasons" value="<?= $editTotalSeasons ?>">
            <div class="input-group"><label class="label" for="nombre">Título Serie:</label><input type="text" name="nombre" id="nombre" value="<?= htmlspecialchars($serieEdit['nombre'] ?? '') ?>" required /></div><div class="input-group"><label class="label" for="genero">Género:</label><input type="text" name="genero" id="genero" value="<?= htmlspecialchars($serieEdit['genero'] ?? '') ?>" /></div><div class="input-group"><label class="label" for="descripcion">Sinopsis:</label><textarea name="descripcion" id="descripcion"><?= htmlspecialchars($serieEdit['descripcion'] ?? '') ?></textarea></div><div class="input-group"><label class="label" for="anio">Año:</label><input type="text" name="anio" id="anio" value="<?= htmlspecialchars($serieEdit['anio'] ?? '') ?>" /></div><div class="input-group"><label class="label" for="iconPng">Icono PNG:</label><input type="text" name="iconPng" id="iconPng" value="<?= htmlspecialchars($serieEdit['iconPng'] ?? '') ?>" /></div><div class="input-group"><label class="label" for="icono">Icono (Poster):</label><input type="text" name="icono" id="icono" value="<?= htmlspecialchars($serieEdit['icono'] ?? '') ?>" /></div><div class="input-group"><label class="label" for="logoHorizontal">Fondo (Backdrop):</label><input type="text" name="logoHorizontal" id="logoHorizontal" value="<?= htmlspecialchars($serieEdit['logoHorizontal'] ?? '') ?>" /></div><div class="input-group"><label class="label" for="new_series_position">Posición (1-<?= count($jsonArray['categorias'][$catIndex]['series']) ?>):</label><input type="number" name="new_series_position" id="new_series_position" min="1" max="<?= count($jsonArray['categorias'][$catIndex]['series']) ?>" value="<?= $serieIndex + 1 ?>" required></div>
            <h3>Temporadas / Capítulos</h3><div id="edit-seasons-container"></div><button type="button" class="btn-add" onclick="addSeason('edit-seasons-container')">+ Añadir Temporada</button><br><br><button type="submit">Guardar Cambios</button></form>
            <script>(async function(){ const existingSeasons = <?= json_encode($serieEdit['temporadas'] ?? [], JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES) ?>; const existingTmdbId = <?= $editTmdbId ?>; const existingTotal = <?= $editTotalSeasons ?>; await initEditForm(existingSeasons, existingTmdbId, existingTotal); })();</script>
        </div>
        <?php endif; ?>
        <?php if ($addCategoryData):$catIndex=$addCategoryData['catIndex'];$serieIndex=$addCategoryData['serieIndex'];$serieInfo=$addCategoryData['serie'];$serieName=$serieInfo['nombre']??'Sin nombre';?>
        <div class="block">
            <h2>Copiar Serie a Otra Categoría: <strong><?= htmlspecialchars($serieName) ?></strong></h2>
            <form method="post" action=""><input type="hidden" name="action" value="do_add_to_category" /><input type="hidden" name="cat_index" value="<?= $catIndex ?>" /><input type="hidden" name="serie_index" value="<?= $serieIndex ?>" /><div class="input-group"><label class="label" for="categoria_nueva">Categoría destino:</label><select name="categoria_nueva" id="categoria_nueva"><?php foreach($jsonArray['categorias']as $cat):?><option value="<?= htmlspecialchars($cat['nombre']) ?>"><?= htmlspecialchars($cat['nombre']) ?></option><?php endforeach; ?></select></div><button type="submit">Copiar Serie</button></form>
        </div>
        <?php endif; ?>
        <?php if(isset($editCategoryData)&&$editCategoryData):?>
        <div class="block">
            <h2>Editar Posición de Categoría: <?= htmlspecialchars($editCategoryData['categoria']['nombre']) ?></h2>
            <form method="post" action=""><input type="hidden" name="action" value="save_edit_category"><input type="hidden" name="cat_index" value="<?= $editCategoryData['catIndex'] ?>"><div class="input-group"><label class="label" for="new_position">Nueva Posición (1-<?= count($jsonArray['categorias']) ?>):</label><input type="number" name="new_position" id="new_position" min="1" max="<?= count($jsonArray['categorias']) ?>" required></div><button type="submit">Guardar Posición</button></form>
        </div>
        <?php endif; ?>
        <div class="block category-list">
            <h2>3) Listado Actual</h2>
            <form method="get" action=""><input type="hidden" name="action" value="local_search" /><div class="input-group"><label class="label" for="searchLocal">Buscar serie existente:</label><input type="text" name="q" id="searchLocal" placeholder="Nombre de la serie" /></div><button type="submit">Buscar en JSON</button></form>
            <?php if(!empty($localSearchResults)):?><div class="local-search-results"><h3>Resultados:</h3><ul><?php foreach($localSearchResults as $res):?><li><strong><?= htmlspecialchars($res['nombre']) ?></strong> (Cat: <?= htmlspecialchars($res['cat_nombre']) ?>) <a class="mini-button" href="?action=edit_series&cat_index=<?= $res['cat_index'] ?>&serie_index=<?= $res['serie_index'] ?>">[Editar]</a><a class="mini-button" href="?action=add_to_other_category&cat_index=<?= $res['cat_index'] ?>&serie_index=<?= $res['serie_index'] ?>">[Copiar]</a><a class="mini-button" style="background:#dc3545;" href="?action=delete_series&cat_index=<?= $res['cat_index'] ?>&serie_index=<?= $res['serie_index'] ?>" onclick="return confirm('¿Eliminar esta serie?');">[X]</a></li><?php endforeach;?></ul></div><?php endif; ?>
            <?php if(!empty($jsonArray['categorias'])):?><?php foreach($jsonArray['categorias']as $catIndex=>$cat):?><h3>- <?= htmlspecialchars($cat['nombre']) ?> <a class="mini-button" href="?action=edit_category&cat_index=<?= $catIndex ?>">[Posición]</a> <a class="mini-button" href="?action=rename_category&cat_index=<?= $catIndex ?>">[Nombre]</a></h3><?php if(!empty($cat['series'])&&is_array($cat['series'])):?><ul><?php foreach($cat['series']as $serieIndex=>$serie):?><li><strong><?= htmlspecialchars($serie['nombre']) ?></strong><a class="mini-button" href="?action=edit_series&cat_index=<?= $catIndex ?>&serie_index=<?= $serieIndex ?>">[Editar]</a><a class="mini-button" href="?action=add_to_other_category&cat_index=<?= $catIndex ?>&serie_index=<?= $serieIndex ?>">[Copiar]</a><a class="mini-button" style="background:#dc3545;" href="?action=delete_series&cat_index=<?= $catIndex ?>&serie_index=<?= $serieIndex ?>" onclick="return confirm('¿Eliminar esta serie?');">[X]</a></li><?php endforeach;?></ul><?php else:?><p>(No hay series en esta categoría)</p><?php endif;?><?php endforeach;?><?php else:?><p>Aún no hay categorías ni series.</p><?php endif;?>
        </div>
        <div class="danger-zone">
            <h2>Opciones Avanzadas</h2><a href="?action=edit_raw_json" class="mini-button" style="background: #ffc107; color: black; padding: 8px 12px; font-size: 1em;">Editar JSON Manualmente</a><p style="font-size: 0.9em; margin-top: 5px;">Abre un editor para modificar todo el `series.json`.</p><hr style="margin: 15px 0;">
            <?php if(!file_exists($encryptionFlagFile)):?><form method="post" action="" onsubmit="return confirm('¿SEGURO?\nEncriptará TODAS las URLs de TODOS los episodios.\nEsta operación no se puede deshacer y el botón desaparecerá.');"><input type="hidden" name="action" value="encrypt_all"><button type="submit">Encriptar Todas las URLs (Uso Único)</button></form><p style="font-size: 0.9em; margin-top: 5px;">Usa esto una sola vez para asegurar todas las URLs existentes.</p><?php else:?><p>✅ La encriptación masiva de URLs ya fue realizada.</p><?php endif;?>
        </div>
    <?php endif; ?>
</div>
</body>
</html>