<?php
/**
 * Public Widget API for Flickr Photo Mosaic
 * No authentication required - public photos only
 */

// CORS headers for WordPress access
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');

// Handle preflight
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    http_response_code(200);
    exit;
}

// Load configuration
$configFile = __DIR__ . '/config.php';
if (!file_exists($configFile)) {
    echo json_encode(['error' => 'Configuration not found']);
    exit;
}
$config = require $configFile;

// Autoload classes
spl_autoload_register(function ($class) {
    $file = __DIR__ . '/classes/' . $class . '.php';
    if (file_exists($file)) {
        require_once $file;
    }
});

// Widget settings file
$widgetSettingsFile = __DIR__ . '/data/widget_settings.json';

/**
 * Get widget settings
 */
function getWidgetSettings($file) {
    if (file_exists($file)) {
        return json_decode(file_get_contents($file), true) ?: [];
    }
    return [
        'enabled' => true,
        'albums' => [],
        'max_photos' => 30,
        'cache_time' => 3600, // 1 hour
    ];
}

/**
 * Create FlickrAPI instance
 */
function createFlickrAPI($config) {
    $flickr = new FlickrAPI(
        $config['flickr']['api_key'],
        $config['flickr']['api_secret'] ?? '',
        $config['flickr_user_id'] ?? ''
    );
    return $flickr;
}

$action = $_GET['action'] ?? '';

try {
    switch ($action) {

        case 'get_photos':
            // Public endpoint - returns photos for widget
            if (empty($config['flickr']['api_key'])) {
                echo json_encode(['error' => 'Flickr not configured']);
                exit;
            }

            $settings = getWidgetSettings($widgetSettingsFile);

            if (!$settings['enabled']) {
                echo json_encode(['error' => 'Widget disabled']);
                exit;
            }

            // Check cache
            $cacheFile = __DIR__ . '/data/widget_cache.json';
            if (file_exists($cacheFile)) {
                $cacheData = json_decode(file_get_contents($cacheFile), true);
                if ($cacheData && isset($cacheData['timestamp'])) {
                    $cacheAge = time() - $cacheData['timestamp'];
                    if ($cacheAge < ($settings['cache_time'] ?? 3600)) {
                        echo json_encode([
                            'success' => true,
                            'photos' => $cacheData['photos'],
                            'cached' => true,
                        ]);
                        exit;
                    }
                }
            }

            $flickr = createFlickrAPI($config);
            $allPhotos = [];
            $maxPhotos = $settings['max_photos'] ?? 30;
            $selectedAlbums = $settings['albums'] ?? [];

            if (empty($selectedAlbums)) {
                // If no albums selected, get recent photos
                $result = $flickr->getPhotos(1, $maxPhotos);
                $allPhotos = $result['photos'] ?? [];
            } else {
                // Get photos from selected albums
                $photosPerAlbum = max(5, ceil($maxPhotos / count($selectedAlbums)));

                foreach ($selectedAlbums as $albumId) {
                    try {
                        $result = $flickr->getPhotosetPhotos($albumId, 1, $photosPerAlbum);
                        if (!empty($result['photos'])) {
                            $allPhotos = array_merge($allPhotos, $result['photos']);
                        }
                    } catch (Exception $e) {
                        // Skip failed album
                        continue;
                    }
                }

                // Shuffle and limit
                shuffle($allPhotos);
                $allPhotos = array_slice($allPhotos, 0, $maxPhotos);
            }

            // Simplify photo data for widget
            $widgetPhotos = array_map(function($photo) {
                $urls = $photo['urls'] ?? [];
                return [
                    'id' => $photo['id'],
                    'title' => $photo['title'] ?? '',
                    'thumb' => $urls['small'] ?? $urls['thumbnail'] ?? $urls['square'] ?? '',
                    'medium' => $urls['medium'] ?? $urls['medium640'] ?? $urls['small'] ?? '',
                    'large' => $urls['large'] ?? $urls['large2048'] ?? $urls['medium'] ?? '',
                    'page_url' => $photo['page_url'] ?? '',
                ];
            }, $allPhotos);

            // Save to cache
            $dataDir = __DIR__ . '/data';
            if (!is_dir($dataDir)) {
                mkdir($dataDir, 0755, true);
            }
            file_put_contents($cacheFile, json_encode([
                'timestamp' => time(),
                'photos' => $widgetPhotos,
            ]));

            echo json_encode([
                'success' => true,
                'photos' => $widgetPhotos,
                'cached' => false,
            ]);
            break;

        case 'get_albums':
            // For admin - list available albums
            session_start();
            $auth = new Auth();
            if (!$auth->isAuthenticated()) {
                http_response_code(401);
                echo json_encode(['error' => 'Not authenticated']);
                exit;
            }

            if (empty($config['flickr']['api_key'])) {
                echo json_encode(['error' => 'Flickr not configured']);
                exit;
            }

            $flickr = createFlickrAPI($config);
            $result = $flickr->getPhotosets(1, 100);

            echo json_encode([
                'success' => true,
                'albums' => $result['albums'],
            ]);
            break;

        case 'get_settings':
            // For admin - get widget settings
            session_start();
            $auth = new Auth();
            if (!$auth->isAuthenticated()) {
                http_response_code(401);
                echo json_encode(['error' => 'Not authenticated']);
                exit;
            }

            $settings = getWidgetSettings($widgetSettingsFile);
            echo json_encode([
                'success' => true,
                'settings' => $settings,
            ]);
            break;

        case 'save_settings':
            // For admin - save widget settings
            session_start();
            $auth = new Auth();
            if (!$auth->isAuthenticated()) {
                http_response_code(401);
                echo json_encode(['error' => 'Not authenticated']);
                exit;
            }

            $input = json_decode(file_get_contents('php://input'), true);

            $settings = [
                'enabled' => $input['enabled'] ?? true,
                'albums' => $input['albums'] ?? [],
                'max_photos' => (int)($input['max_photos'] ?? 30),
                'cache_time' => (int)($input['cache_time'] ?? 3600),
            ];

            $dataDir = __DIR__ . '/data';
            if (!is_dir($dataDir)) {
                mkdir($dataDir, 0755, true);
            }

            // Clear cache when settings change
            $cacheFile = __DIR__ . '/data/widget_cache.json';
            if (file_exists($cacheFile)) {
                unlink($cacheFile);
            }

            if (file_put_contents($widgetSettingsFile, json_encode($settings, JSON_PRETTY_PRINT))) {
                echo json_encode(['success' => true, 'message' => 'Settings saved']);
            } else {
                echo json_encode(['error' => 'Failed to save settings']);
            }
            break;

        default:
            echo json_encode(['error' => 'Unknown action', 'available' => ['get_photos', 'get_albums', 'get_settings', 'save_settings']]);
    }

} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['error' => $e->getMessage()]);
}
