<?php

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

/**
 * Organizer Handler for Events Calendar (Pro)
 *
 * Handles organizer creation and updates using The Events Calendar ORM API.
 *
 * @since 4.1.8
 */
class Organizer_Handler {
    /**
     * Create or update an organizer from post data
     *
     * @param array $post_data (optional, defaults to $_POST)
     * @param int   $event_id  (optional) The event post ID being edited
     * @return int|false Organizer post ID or false on failure
     */
    public static function create_or_update_organizer_from_post( $post_data = null, $event_id = 0 ) {
        if ( is_null( $post_data ) ) {
            $post_data = $_POST;
        }

        // Get event ID from post data if not provided
        if ( empty( $event_id ) && ! empty( $post_data['post_id'] ) ) {
            $event_id = intval( $post_data['post_id'] );
        }

        // Check if user selected 'find' mode - return the selected organizer ID
        if ( empty( $post_data['organizer'] ) || 'create' !== $post_data['organizer'] ) {
            return ! empty( $post_data['_EventOrganizerID'] ) ? intval( $post_data['_EventOrganizerID'] ) : false;
        }

        // User selected 'create' mode - always create a new organizer
        // Extract and sanitize organizer fields
        $organizer_args = [];
        $organizer_args['status'] = 'publish'; // Always publish organizers regardless of event status
        $organizer_args['organizer'] = isset( $post_data['organizer_name'] ) ? sanitize_text_field( $post_data['organizer_name'] ) : '';
        $organizer_args['phone'] = isset( $post_data['organizer_phone'] ) ? sanitize_text_field( $post_data['organizer_phone'] ) : '';
        $organizer_args['website'] = isset( $post_data['organizer_website'] ) ? esc_url_raw( $post_data['organizer_website'] ) : '';
        $organizer_args['email'] = isset( $post_data['organizer_email'] ) ? sanitize_email( $post_data['organizer_email'] ) : '';

        // Required: organizer name
        if ( empty( $organizer_args['organizer'] ) ) {
            return false;
        }

        // Create the organizer using TEC ORM
        if ( function_exists( 'tribe_organizers' ) ) {
            $organizer = tribe_organizers()->set_args( $organizer_args )->create();
            if ( $organizer instanceof \WP_Post ) {
                return $organizer->ID;
            }
        }
        return false;
    }
}
