<?php

class EVENTBOOKINGS_Event_Sync
{
    public static function eventbookings_sync_events()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'eb_events';

        try {
            // Step 1: Get configured events
            $configured_events = self::eventbookings_get_configured_events();
            if (!$configured_events) {
                return json_encode(['message' => 'No Events Configured', 'status' => 424]);
            }

            // Step 2: Extract event UUIDs
            $event_uuids = array_column($configured_events, 'uuid');
            if (empty($event_uuids)) {
                return json_encode(['message' => 'No Events Found', 'status' => 424]);
            }

            // Step 3: Fetch latest events from external API
            $event_list_from_eb = self::eventbookings_events_with_caching($event_uuids, 0);
            $events = $event_list_from_eb['events'] ?? [];

            // Step 4: Save or update events in WordPress
            self::eventbookings_save_configured_events($events);
            return json_encode(['message' => 'Successfully Synced', 'status' => 200]);

        } catch (Exception $e) {
            return json_encode(['message' => 'Failed to Sync', 'status' => 500]);
        }
    }

    private static function eventbookings_get_configured_events()
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'eb_events';
        return $wpdb->get_results($wpdb->prepare("SELECT uuid FROM %i", $table_name), ARRAY_A);
    }

    private static function eventbookings_events_with_caching($event_uuids, $caching = 1)
    {
        $api_url = EVENTBOOKINGS_BASE_URL . '/events';  // Replace with actual API URL
        $url = $api_url . "?order_by=created_descending&caching=$caching&filter_by_ids=" . implode(',', $event_uuids) . "&position=1&rows=100";

        $response = wp_remote_get($url);
        if (is_wp_error($response)) {
            return [];
        }
        return json_decode(wp_remote_retrieve_body($response), true);
    }

    private static function eventbookings_save_configured_events($events)
    {
        global $wpdb;
        $table_name = $wpdb->prefix . 'eb_events';

        foreach ($events as $event) {
            $uuid = $event['uuid'] ?? '';
            $org_uuid = $event['org']['uuid'] ?? '';
            $event_data = json_encode($event);
            $is_published = $event['publishing']['state'] === 'published';
            $event_name = $event['display_name'] ?? $event['name'] ?? '';

            // Check if event has ended
            $is_ended = false;
            foreach ($event['extended_status'] ?? [] as $status) {
                if ($status['name'] === 'ended') {
                    $is_ended = $status['value'];
                    break;
                }
            }

            // Insert or update event in DB
            $wpdb->replace(
                $table_name,
                [
                    'uuid' => $uuid,
                    'organisation_uuid' => $org_uuid,
                    'event_data' => $event_data,
                    'is_published' => $is_published,
                    'event_name' => $event_name,
                    'is_ended' => $is_ended
                ],
                ['%s', '%s', '%s', '%d', '%s', '%d']
            );
        }
    }
}
