<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}
/**
 * Handle Sifency Admin Form Submissions
 */
function sifency_handle_admin_forms() {
	if ( 'POST' !== $_SERVER['REQUEST_METHOD'] ) {
		return;
	}
	if ( isset( $_POST['sifency_feature_request_submit'] ) ) {

		if ( ! isset( $_POST['sifency_feature_nonce'] ) || ! wp_verify_nonce( $_POST['sifency_feature_nonce'], 'sifency_feature_request' ) ) {
			add_settings_error( 'sifency_messages', 'sifency_error', __( 'Security verification failed.', 'sifency-addons' ), 'error' );
			return;
		}

		$email   = sanitize_email( $_POST['feature_email'] );
		$request = sanitize_textarea_field( $_POST['feature_request'] );

		if ( ! is_email( $email ) ) {
			add_settings_error( 'sifency_messages', 'sifency_error', __( 'Invalid email address.', 'sifency-addons' ), 'error' );
		} else {
			$to      = 'hello.sifency@gmail.com';
			$subject = __( 'New Feature Request - Sifency Addons', 'sifency-addons' );
			$body    = '<strong>User Email:</strong> ' . $email . '<br/><br/>';
			$body   .= '<strong>Request:</strong><br/>' . nl2br( $request );

			$headers = array( 'Content-Type: text/html; charset=UTF-8', "Reply-To: $email" );

			$sent = wp_mail( $to, $subject, $body, $headers );

			if ( $sent ) {
				add_settings_error( 'sifency_messages', 'sifency_success', __( 'Feature request sent successfully!', 'sifency-addons' ), 'success' );
			} else {
				add_settings_error( 'sifency_messages', 'sifency_error', __( 'Failed to send email. Please try again.', 'sifency-addons' ), 'error' );
			}
		}
	}

	if ( isset( $_POST['sifency_subscribe_submit'] ) ) {

		if ( ! isset( $_POST['sifency_subscribe_nonce'] ) || ! wp_verify_nonce( $_POST['sifency_subscribe_nonce'], 'sifency_subscribe' ) ) {
			add_settings_error( 'sifency_messages', 'sifency_error', __( 'Security verification failed.', 'sifency-addons' ), 'error' );
			return;
		}

		$email = sanitize_email( $_POST['email'] );

		if ( is_email( $email ) ) {

			// ====================================================
			// MAILCHIMP CONFIGURATION
			// ====================================================
			$api_key = 'YOUR_MAILCHIMP_API_KEY_HERE'; // e.g., 123456789-us6
			$list_id = 'YOUR_MAILCHIMP_AUDIENCE_ID';  // e.g., a1b2c3d4
			// ====================================================

			if ( strpos( $api_key, '-' ) === false ) {
				 add_settings_error( 'sifency_messages', 'sifency_error', __( 'Mailchimp API Key is missing or invalid in code.', 'sifency-addons' ), 'error' );
				 return;
			}
			$data_center = substr( $api_key, strpos( $api_key, '-' ) + 1 );

			$url = "https://{$data_center}.api.mailchimp.com/3.0/lists/{$list_id}/members";

			$body = json_encode(
				array(
					'email_address' => $email,
					'status'        => 'subscribed',
				)
			);

			$response = wp_remote_post(
				$url,
				array(
					'body'        => $body,
					'headers'     => array(
						'Authorization' => 'Basic ' . base64_encode( 'user:' . $api_key ),
						'Content-Type'  => 'application/json; charset=utf-8',
					),
					'method'      => 'POST',
					'data_format' => 'body',
				)
			);

			if ( is_wp_error( $response ) ) {
				add_settings_error( 'sifency_messages', 'sifency_error', __( 'Connection error.', 'sifency-addons' ), 'error' );
			} else {
				$response_code = wp_remote_retrieve_response_code( $response );
				$response_body = json_decode( wp_remote_retrieve_body( $response ), true );

				if ( $response_code == 200 || $response_code == 201 ) {
					add_settings_error( 'sifency_messages', 'sifency_success', __( 'You have successfully subscribed!', 'sifency-addons' ), 'success' );
				} elseif ( $response_code == 400 && strpos( $response_body['title'], 'Member Exists' ) !== false ) {
					add_settings_error( 'sifency_messages', 'sifency_warning', __( 'You are already subscribed to this list.', 'sifency-addons' ), 'warning' );
				} else {
					add_settings_error( 'sifency_messages', 'sifency_error', __( 'Mailchimp Error: ', 'sifency-addons' ) . $response_body['detail'], 'error' );
				}
			}
		} else {
			add_settings_error( 'sifency_messages', 'sifency_error', __( 'Please provide a valid email.', 'sifency-addons' ), 'error' );
		}
	}
}
add_action( 'admin_init', 'sifency_handle_admin_forms' );

/**
 * Helper to show messages in the HTML
 */
function sifency_show_admin_notices() {
	settings_errors( 'sifency_messages' );
}

