<?php

namespace WeDevs\Wpuf\Pro\Integrations\Events_Calendar\Handlers;

use WeDevs\Wpuf\Pro\Integrations\Events_Calendar\Compatibility\TEC_Compatibility_Manager;

/**
 * Event Handler for Events Calendar (Pro)
 *
 * Handles all event creation and editing operations, including pro features
 * such as venue and organizer creation.
 *
 * @since 4.1.8
 */
class Event_Handler {
    /**
     * @var TEC_Compatibility_Manager
     */
    protected $compatibility_manager;

    /**
     * Constructor
     *
     * @param TEC_Compatibility_Manager $compatibility_manager
     */
    public function __construct( $compatibility_manager ) {
        $this->compatibility_manager = $compatibility_manager;
    }

    /**
     * Handle event submission with automatic compatibility routing
     *
     * This method orchestrates the full event creation flow, including:
     * - Creating/updating the event post
     * - Creating/updating the venue (if venue data is present)
     * - Creating/updating the organizer (if organizer data is present)
     * - Attaching venue/organizer IDs to the event
     * - Handling any other pro features
     *
     * @param array $postarr
     * @param array $meta_vars
     * @param int   $form_id
     * @param array $form_settings
     * @return int|false
     */
    public function handle_event_submission( $postarr, $meta_vars, $form_id, $form_settings ) {
        // Delegate to compatibility handler for event creation
        $compatibility_handler = $this->compatibility_manager->get_compatibility_handler();
        if ( ! $compatibility_handler ) {
            return wp_insert_post( $postarr );
        }

        return $compatibility_handler->save_event( $postarr, $meta_vars, $form_id, $form_settings );
    }

    /**
     * Get the compatibility manager instance
     *
     * @return TEC_Compatibility_Manager
     */
    public function get_compatibility_manager() {
        return $this->compatibility_manager;
    }
}
