<?php
/**
 * Events controller for handling events.
 *
 * @package Awesomemotive\Rewardswp\Controllers
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Controllers;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

use Awesomemotive\Rewardswp\Interfaces\ControllerInterface;
use function Awesomemotive\Rewardswp\Helpers\get_current_member;
use function Awesomemotive\Rewardswp\Helpers\is_current_user_a_member;
use function Awesomemotive\Rewardswp\Helpers\create_event;

/**
 * Controller for handling all types of events tracking.
 *
 * This controller provides a generic way to track any type of event
 * (share, click, visit, etc.) with proper validation and context.
 *
 * @since 1.1.0
 */
class EventsController implements ControllerInterface {

	/**
	 * AJAX nonce for events tracking requests.
	 *
	 * @since 1.1.0
	 */
	const AJAX_NONCE = 'rewardswp_advocate_form_nonce';

	/**
	 * Constructor.
	 *
	 * @since 1.1.0
	 */
	public function __construct() {
		// No dependencies needed, using helper functions
	}

	/**
	 * Initialize controller hooks.
	 *
	 * @since 1.1.0
	 * @return void
	 */
	public function init(): void {
		// Register AJAX handlers for both logged-in and non-logged-in users
		add_action( 'wp_ajax_rewardswp_track_event', [ $this, 'ajax_track_event' ] );
		add_action( 'wp_ajax_nopriv_rewardswp_track_event', [ $this, 'ajax_track_event' ] );
	}

	/**
	 * AJAX handler for tracking any type of event.
	 *
	 * @since 1.1.0
	 * @return void
	 */
	public function ajax_track_event(): void {
		// Verify nonce.
		check_ajax_referer( self::AJAX_NONCE, 'nonce' );

		// Get event data from request.
		$type         = sanitize_text_field( filter_input( INPUT_POST, 'type' ) );
		$context      = sanitize_text_field( filter_input( INPUT_POST, 'context' ) );
		$referrer_url = sanitize_text_field( filter_input( INPUT_POST, 'referrer_url' ) );

		// Validate required fields.
		if ( empty( $type ) ) {
			wp_send_json_error(
				[
					'message' => esc_html__( 'Event type is required.', 'rewardswp' ),
				],
				400
			);
		}

		// Check if user is a member.
		if ( ! is_current_user_a_member() ) {
			wp_send_json_error(
				[
					'message' => esc_html__( 'Only members can track events.', 'rewardswp' ),
				],
				403
			);
		}

		// Get current member.
		$current_member = get_current_member();
		if ( ! $current_member ) {
			wp_send_json_error(
				[
					'message' => esc_html__( 'Member not found.', 'rewardswp' ),
				],
				404
			);
		}

		try {
			// Create new event using helper function.
			$event_data = [
				'member_id'    => $current_member->id,
				'type'         => $type,
				'referrer_url' => $referrer_url ?: wp_get_referer(),
			];

			// Add context if provided.
			if ( ! empty( $context ) ) {
				$event_data['context'] = $context;
			}

			$event = create_event( $event_data );

			if ( is_wp_error( $event ) ) {
				wp_send_json_error(
					[
						'message' => esc_html__( 'Failed to save event.', 'rewardswp' ),
						'debug'   => defined( 'WP_DEBUG' ) && WP_DEBUG ? $event->get_error_message() : null,
					],
					500
				);
			}

			if ( $event ) {
				wp_send_json_success(
					[
						'event_id' => $event->id,
						'type'     => $event->type,
						'context'  => $event->context,
						'message'  => esc_html__( 'Event tracked successfully.', 'rewardswp' ),
					]
				);
			} else {
				wp_send_json_error(
					[
						'message' => esc_html__( 'Failed to save event.', 'rewardswp' ),
					],
					500
				);
			}
		} catch ( \Exception $e ) {
			wp_send_json_error(
				[
					'message' => esc_html__( 'An error occurred while tracking the event.', 'rewardswp' ),
					'debug'   => defined( 'WP_DEBUG' ) && WP_DEBUG ? $e->getMessage() : null,
				],
				500
			);
		}
	}
}
