<?php

if( !class_exists( 'Post_SMTP_Rest_API_Track' ) ):
class Post_SMTP_Rest_API_Track {

    private static $_instance;

    
    /**
     * Get the instance of the class
     * 
     * @version 1.0.0
     * @since 1.0.0
     */
    public static function get_instance() {

        if ( self::$_instance == null ) {

            self::$_instance = new self();

        }
            

        return self::$_instance;

    }


    /**
     * PostSMTP_Rest_API_Track constructor.
     * 
     * @version 1.0.0
     * @since 1.0.0
     */
    public function __construct() {

        add_action( 'rest_api_init', array( $this, 'register_routes' ) );

    }

    /**
     * Register Routes | Action Callback
     * 
     * @version 1.0.0
     * @since 1.0.0
     */
    public function register_routes() {
        
        register_rest_route( 'post-smtp/v1', '/t/(?P<data>.+)', array(
            'methods'               =>  WP_REST_Server::READABLE,
            'callback'              =>  array( $this, 'track_email' ),
            'permission_callback'   =>  '__return_true',
        ) );

    }


    /**
     * Track the email | Action Callback
     * 
     * @version 1.0.0
     * @since 1.0.0
     */
    public function track_email( $request ) {

        $data = $request->get_param( 'data' );

        $mail_event =  Post_SMTP_RAT_Mail_Event::get_instance()->decode_email_hash( $data );

        if( empty( $mail_event['email_id'] ) || empty( $mail_event['event_type'] ) ) {

            return false;

        }

        // Validate event_type against allowed values to prevent XSS injection.
        $allowed_events = array( 'open-email' );
        if ( ! in_array( $mail_event['event_type'], $allowed_events, true ) ) {
            return false;
        }

        $data = array(
            'email_id'      =>  absint( $mail_event['email_id'] ),
            'event_type'    =>  sanitize_text_field( $mail_event['event_type'] ),
            'time'          =>  current_time( 'timestamp' ),
        );

        $db = new Post_SMTP_RAT_DB();
        $response = $db->insert( $data );

        return $response ? true : false;

    }

}

Post_SMTP_Rest_API_Track::get_instance();
endif;