<?php
/**
 * Videos API Endpoint
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');

require_once __DIR__ . '/../config/database.php';

try {
    $pdo = getDBConnection();
    
    $stmt = $pdo->query("
        SELECT id, title, description, video_url, video_type, thumbnail_url, 
               autoplay, `loop`, muted, show_controls, display_order
        FROM videos 
        WHERE status = 'active'
        ORDER BY display_order ASC, created_at DESC
        LIMIT 1
    ");
    
    $video = $stmt->fetch();
    
    if ($video) {
        // Process thumbnail URL
        $thumbnailUrl = $video['thumbnail_url'];
        if ($thumbnailUrl && strpos($thumbnailUrl, 'uploads/') !== false) {
            $thumbnailUrl = '/backend/uploads/videos/' . basename($thumbnailUrl);
        }
        
        // Process video URL - if it's a direct upload, prepend the upload path
        $videoUrl = $video['video_url'];
        if ($video['video_type'] === 'direct' && !filter_var($videoUrl, FILTER_VALIDATE_URL)) {
            // It's an uploaded file, not a URL
            $videoUrl = '/backend/uploads/videos/' . $videoUrl;
        }
        
        echo json_encode([
            'success' => true,
            'video' => [
                'id' => (int)$video['id'],
                'title' => $video['title'],
                'description' => $video['description'],
                'video_url' => $videoUrl,
                'video_type' => $video['video_type'],
                'thumbnail_url' => $thumbnailUrl,
                'autoplay' => (bool)$video['autoplay'],
                'loop' => (bool)$video['loop'],
                'muted' => (bool)$video['muted'],
                'show_controls' => (bool)$video['show_controls'],
                'display_order' => (int)$video['display_order']
            ]
        ]);
    } else {
        echo json_encode([
            'success' => true,
            'video' => null
        ]);
    }
    
} catch (Exception $e) {
    error_log("Videos API error: " . $e->getMessage());
    http_response_code(500);
    echo json_encode([
        'success' => false,
        'video' => null
    ]);
}

