<?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)
     * @return int|false Organizer post ID or false on failure
     */
    public static function create_or_update_organizer_from_post( $post_data = null ) {
        if ( is_null( $post_data ) ) {
            $post_data = $_POST;
        }

        // Only create if user selected 'create' for organizer
        if ( empty( $post_data['organizer'] ) || $post_data['organizer'] !== 'create' ) {
            return ! empty( $post_data['_EventOrganizerID'] ) ? $post_data['_EventOrganizerID'] : false;
        }

        // Extract and sanitize organizer fields
        $organizer_args = [];
        $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;
    }
}
