<?php
/**
 * Submission storage for the WordPress.org free build.
 *
 * @package CF7MasterPro\Database
 */

namespace CF7MasterPro\Database;

defined( 'ABSPATH' ) || exit;

/**
 * Save Contact Form 7 submissions.
 */
class Submission {

	/**
	 * Register hooks.
	 */
	public function register() {
		add_action( 'wpcf7_mail_sent', array( $this, 'save_submission' ) );
	}

	/**
	 * Save a submission.
	 *
	 * @param object $cf7 Contact Form 7 instance.
	 */
	public function save_submission( $cf7 ) {
		global $wpdb;
		$submission = \WPCF7_Submission::get_instance();
		if ( ! $submission ) {
			return;
		}
		$data    = $submission->get_posted_data();
		$payload = wp_json_encode( $data );

		$wpdb->insert( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Inserting a form submission into the plugin's own table.
			$wpdb->prefix . CF7MP_DB_PREFIX . 'submissions',
			array(
				'form_id'      => $cf7->id(),
				'form_data'    => $payload,
				'ip_address'   => $this->get_ip(),
				'user_agent'   => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '',
				'referer'      => isset( $_SERVER['HTTP_REFERER'] ) ? esc_url_raw( wp_unslash( $_SERVER['HTTP_REFERER'] ) ) : '',
				'utm_source'   => isset( $data['utm_source'] ) ? sanitize_text_field( $data['utm_source'] ) : '',
				'utm_medium'   => isset( $data['utm_medium'] ) ? sanitize_text_field( $data['utm_medium'] ) : '',
				'utm_campaign' => isset( $data['utm_campaign'] ) ? sanitize_text_field( $data['utm_campaign'] ) : '',
				'status'       => 'new',
				'created_at'   => current_time( 'mysql' ),
			),
			array( '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s' )
		);
		do_action( 'cf7mp_after_save_submission', (int) $wpdb->insert_id, $cf7 );
	}

	/**
	 * Get request IP address.
	 *
	 * @return string
	 */
	private function get_ip() {
		$ip = '';
		if ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
			$forwarded = explode( ',', sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) );
			$ip        = trim( $forwarded[0] );
		} elseif ( ! empty( $_SERVER['REMOTE_ADDR'] ) ) {
			$ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) );
		}
		return $ip;
	}
}
