<?php
/**
 * Video information API for Main VPS (Web Version)
 * This version calls the CLI service instead of using shell_exec
 * Place this file in the web root of each main VPS as /api/info.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);
}

// Main execution
try {
    $action = $_GET['action'] ?? '';
    $file = $_GET['file'] ?? '';
    
    if ($action !== 'info') {
        sendError('Invalid action');
    }
    
    if (empty($file)) {
        sendError('File parameter is required');
    }
    
    if (!validatePath($file)) {
        sendError('Invalid file path or security violation');
    }
    
    $fullPath = $BASE_PATH . $file;
    
    if (!file_exists($fullPath)) {
        sendError('File not found: ' . $file, 404);
    }
    
    // Get basic file info
    $fileInfo = [
        'name' => basename($fullPath),
        'size' => filesize($fullPath),
        'sizeFormatted' => formatBytes(filesize($fullPath)),
        'modified' => date('Y-m-d H:i:s', filemtime($fullPath)),
        'extension' => strtolower(pathinfo($fullPath, PATHINFO_EXTENSION))
    ];
    
    // Get video metadata using cached ffprobe
    $videoInfo = getVideoInfoFromCache($fullPath, $file);
    if ($videoInfo) {
        $fileInfo = array_merge($fileInfo, $videoInfo);
    }
    
    sendJsonResponse([
        'success' => true,
        'file' => $fileInfo
    ]);
    
} catch (Exception $e) {
    sendError($e->getMessage());
}

?>