<?php
header('Content-Type: application/json');

// Security configurations
$allowed_extensions = [
    'video' => ['mp4', 'webm', 'ogg', 'mov', 'avi', 'mkv', 'm4v'],
    'audio' => ['mp3', 'wav', 'aac', 'flac', 'm4a']
];
$blocked_paths = ['.', '..', '.htaccess', '.php'];

function getMediaType($extension) {
    global $allowed_extensions;
    foreach ($allowed_extensions as $type => $exts) {
        if (in_array($extension, $exts)) {
            return $type;
        }
    }
    return null;
}

function getMediaInfo($file) {
    $path = realpath($file);
    if (!$path || !is_file($path)) {
        return null;
    }

    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    $mediaType = getMediaType($ext);
    
    if (!$mediaType) {
        return null;
    }

    $mimeType = $mediaType === 'video' ? "video/$ext" : "audio/$ext";

    return [
        'name' => basename($file),
        'type' => $mimeType,
        'path' => './' . basename($file),
        'thumbnail' => $mediaType === 'video' ? 'https://picsum.photos/seed/' . crc32($file) . '/400/225' : 'https://picsum.photos/seed/' . crc32($file) . '/400/225',
        'size' => filesize($file),
        'dateModified' => date('Y-m-d\TH:i:s', filemtime($file)),
        'bitrate' => '---',
        'resolution' => $mediaType === 'video' ? '1920x1080' : null,
        'codec' => $ext
    ];
}

try {
    $dir = __DIR__;
    $files = scandir($dir);
    $mediaFiles = [];

    foreach ($files as $file) {
        if (in_array($file, $blocked_paths) || !is_file($file)) {
            continue;
        }

        $mediaInfo = getMediaInfo($file);
        if ($mediaInfo) {
            $mediaFiles[] = $mediaInfo;
        }
    }

    echo json_encode([
        'status' => 'success',
        'files' => $mediaFiles
    ]);

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode([
        'status' => 'error',
        'message' => 'Failed to scan directory'
    ]);
}