<?php
/**
 * Video listing API for Main VPS
 * Place this file in the web root of each main VPS as /api/list.php
 */

// Include shared configuration
require_once __DIR__ . '/config.php';

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

// Handle preflight requests
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

/**
 * Get file size in bytes
 */
function getFileSize($filepath) {
    if (file_exists($filepath)) {
        return filesize($filepath);
    }
    return 0;
}

/**
 * Check if file has embedded subtitles (simplified version)
 */
function hasSubtitles($filepath) {
    // Simple check based on file extension and common patterns
    // This is a fallback when ffprobe is not available
    $videoExtensions = ['.mkv', '.mp4', '.avi'];
    $extension = strtolower(pathinfo($filepath, PATHINFO_EXTENSION));
    
    // MKV files commonly have subtitles
    if ($extension === 'mkv') {
        return true; // Assume MKV files might have subtitles
    }
    
    // Check for external subtitle files
    $baseName = pathinfo($filepath, PATHINFO_FILENAME);
    $directory = dirname($filepath);
    $subtitleExtensions = ['.srt', '.vtt', '.ass', '.ssa', '.sub'];
    
    foreach ($subtitleExtensions as $subExt) {
        if (file_exists($directory . '/' . $baseName . $subExt)) {
            return true;
        }
    }
    
    return false; // Conservative approach when can't detect
}

/**
 * Get basic video information (without ffprobe)
 */
function getVideoInfo($filepath) {
    if (!file_exists($filepath)) {
        return null;
    }
    
    return [
        'duration' => null, // Cannot determine without ffprobe
        'resolution' => null, // Cannot determine without ffprobe  
        'hasSubtitles' => hasSubtitles($filepath)
    ];
}

/**
 * List video files in directory
 */
function listVideoFiles($directory) {
    $allowedExtensions = ['.mp4', '.mkv', '.avi', '.mov', '.wmv', '.flv', '.webm'];
    $files = [];
    $directories = [];
    
    if (!is_dir($directory)) {
        return ['videos' => [], 'directories' => []];
    }
    
    $iterator = new DirectoryIterator($directory);
    
    foreach ($iterator as $fileInfo) {
        if ($fileInfo->isDot()) {
            continue;
        }
        
        if ($fileInfo->isDir()) {
            $directories[] = [
                'name' => $fileInfo->getFilename(),
                'path' => str_replace($GLOBALS['BASE_PATH'], '', $fileInfo->getPathname()) . '/',
                'type' => 'directory'
            ];
            continue;
        }
        
        $filename = $fileInfo->getFilename();
        $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
        
        if (in_array('.' . $extension, $allowedExtensions)) {
            $filepath = $fileInfo->getPathname();
            
            $fileData = [
                'name' => $filename,
                'size' => getFileSize($filepath),
                'path' => str_replace($GLOBALS['BASE_PATH'], '', $filepath),
                'type' => 'video',
                'extension' => $extension,
                'modified' => date('Y-m-d H:i:s', $fileInfo->getMTime())
            ];
            
            // Get video info using cached ffprobe if available
            if (function_exists('shell_exec')) {
                $videoInfo = getVideoInfoFromCache($filepath, str_replace($GLOBALS['BASE_PATH'], '', $filepath));
                if ($videoInfo) {
                    $fileData = array_merge($fileData, $videoInfo);
                }
            }
            
            $files[] = $fileData;
        }
    }
    
    // Sort files and directories by name
    usort($files, function($a, $b) {
        return strcasecmp($a['name'], $b['name']);
    });
    
    usort($directories, function($a, $b) {
        return strcasecmp($a['name'], $b['name']);
    });
    
    return [
        'videos' => $files,
        'directories' => $directories
    ];
}

// Main execution
try {
    $action = $_GET['action'] ?? '';
    $path = $_GET['path'] ?? '';
    $page = isset($_GET['page']) ? max(1, intval($_GET['page'])) : 1; // Page number (1-indexed)
    $pageSize = isset($_GET['pageSize']) ? min(intval($_GET['pageSize']), $MAX_PAGE_SIZE) : $DEFAULT_PAGE_SIZE;
    
    if ($action !== 'list') {
        throw new Exception('Invalid action');
    }
    
    if (empty($path)) {
        throw new Exception('Path parameter is required');
    }
    
    if (!validatePath($path)) {
        throw new Exception('Invalid path format or security violation');
    }
    
    $fullPath = $BASE_PATH . $path;
    
    if (!is_dir($fullPath)) {
        throw new Exception('Directory not found: ' . $path);
    }
    
    $files = listVideoFiles($fullPath);
    
    // Get total counts
    $totalVideos = count($files['videos']);
    $totalDirectories = count($files['directories']);
    
    // Calculate pagination for videos
    $totalPages = max(1, ceil($totalVideos / $pageSize));
    $page = min($page, $totalPages); // Ensure page doesn't exceed total pages
    $offset = ($page - 1) * $pageSize;
    
    // Slice videos array for current page
    $paginatedVideos = array_slice($files['videos'], $offset, $pageSize);
    
    // Always show directories on first page only (not paginated)
    $paginatedDirectories = ($page === 1) ? $files['directories'] : [];
    
    $response = [
        'success' => true,
        'path' => $path,
        'videos' => $paginatedVideos,
        'directories' => $paginatedDirectories,
        'pagination' => [
            'currentPage' => $page,
            'pageSize' => $pageSize,
            'totalVideos' => $totalVideos,
            'totalDirectories' => $totalDirectories,
            'totalPages' => $totalPages,
            'hasNextPage' => $page < $totalPages,
            'hasPreviousPage' => $page > 1,
            'startIndex' => $offset + 1,
            'endIndex' => min($offset + $pageSize, $totalVideos)
        ]
    ];
    
    echo json_encode($response);
    
} catch (Exception $e) {
    http_response_code(400);
    echo json_encode([
        'error' => $e->getMessage(),
        'success' => false
    ]);
}
?>