<?php
/**
 * Dynamic video catalog from /var/www/html/dance_Content/
 *
 * Deploy to: /var/www/html/server-media/api/videos.php
 *
 * Success: {"success":true,"videos":[...]}
 * Failure: {"success":false,"error":"..."}
 */
ini_set('display_errors', '0');
error_reporting(0);

header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Accept, Content-Type');
header('Cache-Control: no-store, no-cache, must-revalidate');

if (isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(204);
    exit;
}

function videos_api_fail($message) {
    echo json_encode(array(
        'success' => false,
        'error' => (string) $message,
    ));
    exit;
}

function videos_api_ok($videos) {
    echo json_encode(array(
        'success' => true,
        'videos' => $videos,
    ));
    exit;
}

$root = '/var/www/html/dance_Content';
$webBase = '/dance_Content';
$ignoredNames = array(
    '.git' => true,
    '.DS_Store' => true,
    'node_modules' => true,
    'api' => true,
    'deploy-tv' => true,
    'jd-addressable' => true,
    'videos' => true,
);

if (!is_dir($root) || !is_readable($root)) {
    videos_api_fail('dance_Content directory missing or unreadable');
}

$entries = @scandir($root);
if ($entries === false) {
    videos_api_fail('Failed to scan dance_Content directory');
}

$videos = array();
$seenIds = array();

foreach ($entries as $folder) {
    if ($folder === '.' || $folder === '..') {
        continue;
    }

    // Ignore hidden entries and reserved names
    if (isset($folder[0]) && $folder[0] === '.') {
        continue;
    }
    if (isset($ignoredNames[$folder])) {
        continue;
    }

    $dirPath = $root . DIRECTORY_SEPARATOR . $folder;

    // Only immediate child directories (ignore files at root)
    if (!is_dir($dirPath)) {
        continue;
    }

    $mp4 = $dirPath . DIRECTORY_SEPARATOR . $folder . '.mp4';
    $png = $dirPath . DIRECTORY_SEPARATOR . $folder . '.png';

    if (!is_file($mp4) || !is_file($png)) {
        continue;
    }

    if (!preg_match('/(\d+)$/', $folder, $m)) {
        continue;
    }

    $id = intval($m[1], 10);
    if ($id <= 0) {
        continue;
    }

    // Skip duplicate ids (first win)
    if (isset($seenIds[$id])) {
        continue;
    }
    $seenIds[$id] = true;

    $videos[] = array(
        'id' => $id,
        'name' => $folder,
        'folder' => $folder,
        'videoUrl' => $webBase . '/' . $folder . '/' . $folder . '.mp4',
        'imageUrl' => $webBase . '/' . $folder . '/' . $folder . '.png',
    );
}

usort($videos, function ($a, $b) {
    return $a['id'] - $b['id'];
});

videos_api_ok($videos);