<?php
// descargar-video.php

if (isset($_GET['url']) && !empty($_GET['url'])) {
    $videoUrl = $_GET['url'];
    $videoTitle = isset($_GET['title']) ? $_GET['title'] : 'video-descargado';

    if (!filter_var($videoUrl, FILTER_VALIDATE_URL) || strpos($videoUrl, 'picsum.photos') === false) {
        http_response_code(400);
        die('Error: URL de video no válida o no permitida.');
    }

    $videoData = @file_get_contents($videoUrl);

    if ($videoData === false) {
        http_response_code(404);
        die('Error: No se pudo encontrar el video.');
    }

    $filename = preg_replace('/[^a-zA-Z0-9-_\.]/', '', $videoTitle) . '.mp4';

    header('Content-Description: File Transfer');
    header('Content-Type: video/mp4');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . strlen($videoData));
    
    echo $videoData;
    exit;

} else {
    http_response_code(400);
    echo 'Error: No se especificó la URL del video a descargar.';
}