<?php
// Configuración
$configFile = __DIR__ . '/intro_config.json';
$videoFile = __DIR__ . '/../splash_rgvip/intro.mp4';
$emptyVideoFile = __DIR__ . '/empty_video.mp4';

// Headers CORS importantes para Android
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Range');
header('Cache-Control: no-cache, no-store, must-revalidate');
header('Pragma: no-cache');
header('Expires: 0');

// Manejar preflight OPTIONS request
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Crear JSON por defecto si no existe
if (!file_exists($configFile)) {
    $defaultConfig = ['intro_enabled' => true];
    file_put_contents($configFile, json_encode($defaultConfig, JSON_PRETTY_PRINT));
}

// Leer configuración actual
$config = json_decode(file_get_contents($configFile), true);
$introEnabled = $config['intro_enabled'] ?? true;

// PRIMERO verificar si el intro está ACTIVADO y el archivo existe
if ($introEnabled && file_exists($videoFile)) {
    // Servir el video normal CON MANEJO DE RANGOS para Android
    serveVideoWithRangeSupport($videoFile);
    exit;
}
// LUEGO verificar si el intro está DESACTIVADO
elseif (!$introEnabled) {
    // Si el intro está desactivado, servir video vacío de 1 segundo
    if (!file_exists($emptyVideoFile)) {
        createEmptyVideo($emptyVideoFile);
    }
    
    if (file_exists($emptyVideoFile) && filesize($emptyVideoFile) > 0) {
        serveVideoWithRangeSupport($emptyVideoFile);
    } else {
        // Fallback: video mínimo base64
        header('Content-Type: video/mp4');
        header('Content-Length: 100');
        echo base64_decode('AAAAGGZ0eXBtcDQyAAAAAGlzb21tcDQyAAAbAG1vb3YAAABsbXZoZAAAAAD8AAAEAAAAAQAAAAAAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAGW0cmFuAAAAIGZpbG5tdDQyAAEABGFtcDQyAAAAAQAAAAYAAAAEAAAAAbW9vdgAAAAA=');
    }
    exit;
}
// FINALMENTE si el intro está activado pero el archivo no existe
else {
    if (!file_exists($emptyVideoFile)) {
        createEmptyVideo($emptyVideoFile);
    }
    
    if (file_exists($emptyVideoFile)) {
        serveVideoWithRangeSupport($emptyVideoFile);
    } else {
        http_response_code(404);
        header('Content-Type: application/json');
        echo json_encode(['error' => 'Video no disponible']);
    }
    exit;
}

function serveVideoWithRangeSupport($filePath) {
    $fileSize = filesize($filePath);
    $file = fopen($filePath, 'rb');
    
    // Headers básicos
    header('Content-Type: video/mp4');
    header('Accept-Ranges: bytes');
    header('Content-Length: ' . $fileSize);
    
    // Manejar solicitudes de rango (CRUCIAL para Android)
    if (isset($_SERVER['HTTP_RANGE'])) {
        $range = $_SERVER['HTTP_RANGE'];
        $range = str_replace('bytes=', '', $range);
        list($start, $end) = explode('-', $range);
        
        $start = intval($start);
        $end = $end ? intval($end) : $fileSize - 1;
        
        if ($end >= $fileSize) {
            $end = $fileSize - 1;
        }
        
        $length = $end - $start + 1;
        
        header('HTTP/1.1 206 Partial Content');
        header('Content-Range: bytes ' . $start . '-' . $end . '/' . $fileSize);
        header('Content-Length: ' . $length);
        
        fseek($file, $start);
        
        $buffer = 1024 * 8;
        while (!feof($file) && ($p = ftell($file)) <= $end) {
            if ($p + $buffer > $end) {
                $buffer = $end - $p + 1;
            }
            echo fread($file, $buffer);
            flush();
        }
    } else {
        // Sin rango, enviar todo el archivo
        readfile($filePath);
    }
    
    fclose($file);
}

function createEmptyVideo($outputPath) {
    // Intentar con ffmpeg primero
    if (function_exists('shell_exec')) {
        $command = "ffmpeg -f lavfi -i color=black:size=640x360:rate=1 -t 1 -c:v libx264 -pix_fmt yuv420p " . escapeshellarg($outputPath) . " 2>/dev/null";
        @shell_exec($command);
    }
    
    // Si ffmpeg falla, crear archivo mínimo
    if (!file_exists($outputPath)) {
        $minimalVideo = base64_decode('AAAAGGZ0eXBtcDQyAAAAAGlzb21tcDQyAAAbAG1vb3YAAABsbXZoZAAAAAD8AAAEAAAAAQAAAAAAAAAAAAAAAPAAAAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAAAGW0cmFuAAAAIGZpbG5tdDQyAAEABGFtcDQyAAAAAQAAAAYAAAAEAAAAAbW9vdgAAAAA=');
        file_put_contents($outputPath, $minimalVideo);
    }
}