<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use WPEventGenius\Admin\Actions\RegistrationRecord;
use WPEventGenius\Common\Event\EventPost;

// Initialize registration_data with default values
$registration_data = !empty($registration_data) ? $registration_data : array(
    'id' => 0,
    'event_id' => 0,
    'quantity' => 1,
    'status' => 'confirmed'
);

if ( empty( $event_id ) ) {
	$event_id = $registration_data['event_id'];
}

$event_post = new EventPost( $event_id );
$form = $event_post->get_form();
$guest_mode = ( $form && method_exists( $form, 'get_guest_registration_type' ) ) ? $form->get_guest_registration_type() : 'none';
$show_registration_type_dropdown = $guest_mode !== 'simple_count';
$show_simple_count_quantities   = $guest_mode === 'simple_count';
$active_registration_types = array();
$current_event_registration_type_id = isset( $registration_data['event_registration_type_id'] ) ? (int) $registration_data['event_registration_type_id'] : 0;
$type_quantities = array(); // type_id => quantity for simple_count

$main_registration_id = isset( $registration_data['id'] ) ? (int) $registration_data['id'] : 0;
$parent_registration  = isset( $registration_data['parent'] ) ? (int) $registration_data['parent'] : 0;
$main_registration_id = $parent_registration > 0 ? $parent_registration : $main_registration_id;

if ( $event_id > 0 ) {
	$database = new \WPEventGenius\Common\Database();
	$all_types = $database->get_event_registration_types( $event_id );
	$active_registration_types = array_filter( $all_types, function ( $t ) {
		return ! empty( $t['status'] ) && $t['status'] === 'active';
	} );

	$payment_items_for_main = array();
	if ( $main_registration_id > 0 ) {
		$raw_items = $database->get_payment_items_by_registration_id( $main_registration_id, false );
		if ( ! empty( $raw_items ) && is_array( $raw_items ) ) {
			$payment_items_for_main = $raw_items;
		}
	}

	if ( $show_simple_count_quantities && ! empty( $active_registration_types ) ) {
		if ( ! empty( $payment_items_for_main ) ) {
			foreach ( $payment_items_for_main as $item ) {
				$type_id = isset( $item['event_registration_type_id'] ) ? (int) $item['event_registration_type_id'] : 0;
				$qty     = isset( $item['quantity'] ) ? max( 0, (int) $item['quantity'] ) : 0;
				if ( $type_id > 0 ) {
					$type_quantities[ $type_id ] = isset( $type_quantities[ $type_id ] ) ? $type_quantities[ $type_id ] + $qty : $qty;
				}
			}
		}
		if ( empty( $type_quantities ) ) {
			$qty = ! empty( $registration_data['quantity'] ) ? max( 0, (int) $registration_data['quantity'] ) : 1;
			$type_id = $current_event_registration_type_id > 0 ? $current_event_registration_type_id : (int) array_values( $active_registration_types )[0]['id'];
			$type_quantities[ $type_id ] = $qty;
		}
	}
}

if ( isset( $registration_record ) && $registration_record instanceof RegistrationRecord ) {
	$preferred_type_id = $registration_record->get_preferred_event_registration_type_id_for_edit_form();
	if ( $preferred_type_id > 0 ) {
		$current_event_registration_type_id = $preferred_type_id;
	}
}

// Dropdown options: active types plus the purchased type when it is inactive (otherwise <option> never matches and the browser shows the wrong value).
$registration_type_options = $active_registration_types;
if ( $event_id > 0 && $current_event_registration_type_id > 0 ) {
	if ( ! isset( $database ) ) {
		$database = new \WPEventGenius\Common\Database();
	}
	$option_ids = array();
	foreach ( $registration_type_options as $t ) {
		if ( isset( $t['id'] ) ) {
			$option_ids[] = (int) $t['id'];
		}
	}
	if ( ! in_array( $current_event_registration_type_id, $option_ids, true ) ) {
		$inactive_or_missing = $database->get_event_registration_type( $current_event_registration_type_id );
		if ( ! empty( $inactive_or_missing['id'] ) ) {
			$registration_type_options[] = $inactive_or_missing;
		}
	}
}

// Admin can change registration type when: multiple types, or single type but this registration's type doesn't match the event's single type.
$active_type_count = count( $active_registration_types );
$single_event_type_id = ( 1 === $active_type_count ) ? (int) array_values( $active_registration_types )[0]['id'] : 0;
$registration_mismatches_single_type = ( $single_event_type_id > 0 && $current_event_registration_type_id !== $single_event_type_id );
$can_change_registration_type = ( $active_type_count > 1 ) || $registration_mismatches_single_type;

if ( ! empty( $registration_data ) ) {
	$registration_id = $registration_data['id'];
} else {
	$registration_id = 0;
}
$quantity = ! empty( $registration_data['quantity'] ) ? $registration_data['quantity'] : 1;

$status = ! empty( $registration_data['status'] ) ? $registration_data['status'] : 'confirmed';

// Check user capabilities
$can_manage_registrations = current_user_can( 'manage_evge_registrations' );
$can_view_registrations = current_user_can( 'view_evge_registrations' );

// If user can't view registrations, don't show anything
if ( ! $can_view_registrations ) {
    return;
}

// Check if this is the "Add New" modal (no existing registration ID)
$is_add_new_modal = empty( $registration_id );
?>

<?php if ( $is_add_new_modal ) : ?>
<div class="evge-dynamic evge-modal-settings" data-evge-modal-settings="<?php echo esc_attr( wp_json_encode( array( 'width' => 'medium' ) ) ); ?>">
    <div class="evge-modal-heading">
        <h2><?php esc_html_e( 'Add New Registration', 'event-genius' ); ?></h2>
    </div>
    <div class="evge-registration-form-wrap evge-modal-pad evge-modal-body">
        <div class="evge-registration-form-inner">
<?php else : ?>
<div class="evge-registration-form-inner">
<?php endif; ?>

    <?php if ( $can_manage_registrations ) : ?>
        <form id="evge-registration-form" method="post" action="" enctype="multipart/form-data" class="evge-registration-form">
    <?php else : ?>
        <div class="evge-registration-form evge-registration-form-readonly">
    <?php endif; ?>
    
        <input type="hidden" name="evge_registration_id" value="<?php echo esc_attr( $registration_id ); ?>">
        <input type="hidden" name="evge_event_id" value="<?php echo esc_attr( $event_id ); ?>">
        <?php if ( $can_manage_registrations ) : ?>
            <?php wp_nonce_field( 'evge-edit-registration', 'evge-edit-registration-nonce' ); ?>
        <?php endif; ?>
        
        <div class="evge-field-wrapper">
            <div class="evge-field-inner">
                <div class="evge-label-wrapper">
                    <label for="evge_first"><?php esc_html_e( 'Status', 'event-genius' ); ?></label>
                </div>
                <div class="evge-input-wrapper evge-select-input">
                    <?php if ( $can_manage_registrations ) : ?>
                        <select id="evge-status" type="select" name="evge_status">
                            <option value="confirmed" <?php selected( $status, 'confirmed' ); ?>><?php esc_html_e( 'Confirmed', 'event-genius' ); ?></option>
                            <option value="pending" <?php selected( $status, 'pending' ); ?>><?php esc_html_e( 'Pending', 'event-genius' ); ?></option>
                            <option value="canceled" <?php selected( $status, 'canceled' ); ?>><?php esc_html_e( 'Canceled', 'event-genius' ); ?></option>
                        </select>
                    <?php else : ?>
                        <div class="evge-readonly-value">
                            <?php 
                            $status_labels = array(
                                'confirmed' => __( 'Confirmed', 'event-genius' ),
                                'pending' => __( 'Pending', 'event-genius' ),
                                'canceled' => __( 'Canceled', 'event-genius' )
                            );
                            echo esc_html( $status_labels[$status] ?? $status );
                            ?>
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

		<?php if ( $show_registration_type_dropdown && ! empty( $registration_type_options ) && $can_change_registration_type ) : ?>
        <div class="evge-field-wrapper">
            <div class="evge-field-inner">
                <div class="evge-label-wrapper">
                    <label for="evge_event_registration_type_id"><?php esc_html_e( 'Registration type', 'event-genius' ); ?></label>
                </div>
                <div class="evge-input-wrapper evge-select-input">
                    <?php if ( $can_manage_registrations ) : ?>
                        <select id="evge_event_registration_type_id" name="evge_event_registration_type_id" class="evge-select-input">
                            <?php foreach ( $registration_type_options as $type ) : ?>
                                <option value="<?php echo esc_attr( (int) $type['id'] ); ?>" <?php selected( $current_event_registration_type_id, (int) $type['id'] ); ?>><?php echo esc_html( isset( $type['name'] ) ? $type['name'] : '' ); ?></option>
                            <?php endforeach; ?>
                        </select>
                    <?php else : ?>
                        <?php
                        $current_type_name = __( 'General', 'event-genius' );
                        foreach ( $registration_type_options as $type ) {
                            if ( (int) $type['id'] === $current_event_registration_type_id ) {
                                $current_type_name = isset( $type['name'] ) && $type['name'] !== ''
                                    ? $type['name']
                                    : __( 'General', 'event-genius' );
                                break;
                            }
                        }
                        ?>
                        <div class="evge-readonly-value"><?php echo esc_html( $current_type_name ); ?></div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
		<?php endif; ?>

		<?php if ( $show_simple_count_quantities && ! empty( $active_registration_types ) && $can_change_registration_type ) : ?>
        <div class="evge-field-wrapper evge-registration-type-quantities">
            <div class="evge-field-inner">
                <div class="evge-label-wrapper">
                    <label><?php esc_html_e( 'Registration types', 'event-genius' ); ?></label>
                </div>
                <div class="evge-type-quantities-list evge-input-wrapper">
                    <?php foreach ( $active_registration_types as $type ) :
                        $type_id = (int) $type['id'];
                        $qty = isset( $type_quantities[ $type_id ] ) ? max( 0, (int) $type_quantities[ $type_id ] ) : 0;
                        $name = isset( $type['name'] ) ? $type['name'] : '';
                    ?>
                    <div class="evge-field-wrapper evge-type-quantity-row">
                        <div class="evge-type-quantity-row-inner">
                            <div class="evge-label-wrapper">
                                <label for="evge_type_quantity_<?php echo esc_attr( $type_id ); ?>"><?php echo esc_html( $name ); ?></label>
                            </div>
                            <div class="evge-input-wrapper">
                                <?php if ( $can_manage_registrations ) : ?>
                                    <input type="number" id="evge_type_quantity_<?php echo esc_attr( $type_id ); ?>" name="evge_type_quantities[<?php echo esc_attr( $type_id ); ?>]" value="<?php echo esc_attr( $qty ); ?>" min="0" step="1" class="evge-type-quantity-input">
                                <?php else : ?>
                                    <div class="evge-readonly-value"><?php echo esc_html( (string) $qty ); ?></div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
		<?php endif; ?>

        <input type="hidden" name="evge_quantity" value="<?php echo absint( $quantity ); ?>">

        <div class="evge-registration-form-fields">
            <?php $event_post->display_form_fields( $registration_data, array( 'is_admin' => true ) ); ?>
        </div>

        <?php if ( $can_manage_registrations ) : ?>
            <?php if ( ! empty( $registration_data['id'] ) ) : ?>
            <div class="evge-send-confirmation-feedback evge-email-results" aria-live="polite"></div>
            <?php endif; ?>
            <div class="evge-form-button-wrapper">
                <?php if ( empty( $registration_data['id'] ) ) : ?>
                    <button id="evge-registration-save" name="evge_action" value="submit_create" class="evge-admin-button evge-blue-action-button evge-admin-button-large" type="submit"><span><?php esc_html_e( 'Create', 'event-genius' ); ?></span></button>
                <?php else :
                    $base_json_array = array(
                        'registration_id' => $registration_data['id'],
                        'transaction_id' => ! empty( $item['transaction_id'] ) ? $item['transaction_id'] : 0,
                        'action' => 'evge_identifier_tools_modal_content',
                    );
                    $delete_json_array = array_merge( $base_json_array, array( 'selected' => 'delete' ) );
                    ?>
                    <button id="evge-registration-save" name="evge_action" value="submit_edit" class="evge-admin-button evge-blue-action-button evge-admin-button-large" type="submit"><span><?php esc_html_e( 'Save Changes', 'event-genius' ); ?></span></button>
                    <button type="button" class="evge-send-confirmation-email-btn evge-admin-button evge-admin-button-large" data-registration-id="<?php echo esc_attr( (string) $registration_data['id'] ); ?>" data-event-id="<?php echo esc_attr( (string) $event_id ); ?>"><span class="evge-icon-text">
                        <?php
                        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                        echo \WPEventGenius\Common\Utils\Icon::get( 'email' ) . esc_html( __( 'Send Confirmation Email', 'event-genius' ) ); ?></span></button>
                    <a href="#" data-evge-modal-content="ajax" data-evge-ajax="<?php echo esc_attr( wp_json_encode( $delete_json_array ) ); ?>"  data-evge-modal-settings="<?php echo esc_attr( wp_json_encode( array( 'width' => 'narrow' ) ) ); ?>" class="evge-modal-trigger evge-in-modal-action evge-admin-button evge-danger-button evge-admin-button-large"><span class="evge-icon-text">
                        <?php
                        // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
                        echo \WPEventGenius\Common\Utils\Icon::get( 'trash' ) . esc_html( __( 'Delete Registration', 'event-genius' ) ); ?></span></a>
                <?php endif; ?>
            </div>
        <?php endif; ?>

    <?php if ( $can_manage_registrations ) : ?>
        </form>
    <?php else : ?>
        </div>
    <?php endif; ?>

<?php if ( $is_add_new_modal ) : ?>
        </div>

    </div>
</div>
<?php else : ?>
</div>
<?php endif; ?>
