<?php
/**
 * Merchant Pro theme functions.
 */

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

if ( ! defined( 'MERCHANTPRO_VERSION' ) ) {
	define( 'MERCHANTPRO_VERSION', '1.0.0' );
}

/**
 * Theme setup.
 */
function merchantpro_setup() {
	add_theme_support( 'title-tag' );
	add_theme_support( 'post-thumbnails' );
	add_theme_support( 'automatic-feed-links' );
	add_theme_support( 'html5', array(
		'search-form',
		'comment-form',
		'comment-list',
		'gallery',
		'caption',
		'style',
		'script',
	) );
	add_theme_support( 'custom-logo', array(
		'height'      => 80,
		'width'       => 240,
		'flex-height' => true,
		'flex-width'  => true,
	) );
	add_theme_support( 'responsive-embeds' );

	register_nav_menus( array(
		'primary' => __( 'Primary Menu', 'merchantpro' ),
		'footer_services'   => __( 'Footer · Services', 'merchantpro' ),
		'footer_business'   => __( 'Footer · Business Types', 'merchantpro' ),
		'footer_company'    => __( 'Footer · Company', 'merchantpro' ),
	) );
}
add_action( 'after_setup_theme', 'merchantpro_setup' );

/**
 * Enqueue assets.
 */
function merchantpro_assets() {
	// Google Fonts (Bebas Neue · DM Sans · Oswald)
	wp_enqueue_style(
		'merchantpro-fonts',
		'https://fonts.googleapis.com/css2?family=Bebas+Neue&family=DM+Sans:ital,wght@0,300;0,400;0,500;0,700;1,300&family=Oswald:wght@400;500;600;700&display=swap',
		array(),
		null
	);

	wp_enqueue_style(
		'merchantpro-style',
		get_stylesheet_uri(),
		array( 'merchantpro-fonts' ),
		MERCHANTPRO_VERSION
	);

	wp_enqueue_script(
		'merchantpro-main',
		get_template_directory_uri() . '/assets/js/main.js',
		array(),
		MERCHANTPRO_VERSION,
		true
	);
}
add_action( 'wp_enqueue_scripts', 'merchantpro_assets' );

/**
 * Default primary menu fallback if none assigned.
 */
function merchantpro_primary_menu_fallback() {
	echo '<ul class="nav-menu" id="navMenu">';
	echo '<li><a href="' . esc_url( home_url( '/zerofees/' ) ) . '">Zero Fees</a></li>';
	echo '<li><a href="' . esc_url( home_url( '/point-of-sale/' ) ) . '">POS Systems</a></li>';
	echo '<li><a href="' . esc_url( home_url( '/payment-gateway/' ) ) . '">Payment Gateway</a></li>';
	echo '<li><a href="' . esc_url( home_url( '/restaurant/' ) ) . '">Restaurants</a></li>';
	echo '<li><a href="' . esc_url( home_url( '/retail-merchant-services/' ) ) . '">Retail</a></li>';
	echo '<li><a href="' . esc_url( home_url( '/about-us/' ) ) . '">About</a></li>';
	echo '<li><a href="' . esc_url( home_url( '/contact-us/' ) ) . '">Contact</a></li>';
	echo '</ul>';
}

/**
 * Render primary nav menu with the theme's preferred wrapper.
 */
function merchantpro_primary_menu() {
	if ( has_nav_menu( 'primary' ) ) {
		wp_nav_menu( array(
			'theme_location' => 'primary',
			'container'      => false,
			'menu_class'     => 'nav-menu',
			'menu_id'        => 'navMenu',
			'depth'          => 2,
			'fallback_cb'    => 'merchantpro_primary_menu_fallback',
		) );
	} else {
		merchantpro_primary_menu_fallback();
	}
}

/**
 * Render a footer menu by location with a clean fallback list.
 */
function merchantpro_footer_menu( $location, $fallback_links = array() ) {
	if ( has_nav_menu( $location ) ) {
		wp_nav_menu( array(
			'theme_location' => $location,
			'container'      => false,
			'menu_class'     => 'foot-col-menu',
			'items_wrap'     => '%3$s',
			'fallback_cb'    => false,
		) );
		return;
	}
	foreach ( $fallback_links as $label => $href ) {
		printf(
			'<a href="%1$s">%2$s</a>',
			esc_url( strpos( $href, 'http' ) === 0 ? $href : home_url( $href ) ),
			esc_html( $label )
		);
	}
}

/**
 * Strip the leading scraped <h1> tag from page content (we render it in the hero).
 */
function merchantpro_filter_inner_content( $content ) {
	if ( is_singular( 'page' ) && ! is_front_page() ) {
		$content = preg_replace( '/<h1[^>]*>.*?<\/h1>/is', '', $content, 1 );
	}
	return $content;
}
add_filter( 'the_content', 'merchantpro_filter_inner_content', 5 );

/**
 * Reduce WP wpautop on already-formatted scraped content (paragraphs are explicit in scraped HTML).
 */
function merchantpro_disable_wpautop_for_imported() {
	if ( is_singular( 'page' ) && ! is_front_page() ) {
		remove_filter( 'the_content', 'wpautop' );
		remove_filter( 'the_excerpt', 'wpautop' );
	}
}
add_action( 'wp', 'merchantpro_disable_wpautop_for_imported' );

/**
 * AJAX Form Submission Handler.
 */
function merchantpro_handle_ajax_submit() {
	header('Content-Type: application/json');
	
	// Collect parameters
	$form_id  = isset( $_POST['form_id'] ) ? sanitize_text_field( $_POST['form_id'] ) : 'unknown';
	$first_name = isset( $_POST['first_name'] ) ? sanitize_text_field( $_POST['first_name'] ) : '';
	$name     = isset( $_POST['name'] ) ? sanitize_text_field( $_POST['name'] ) : $first_name;
	$last_name = isset( $_POST['last_name'] ) ? sanitize_text_field( $_POST['last_name'] ) : '';
	$email    = isset( $_POST['email'] ) ? sanitize_email( $_POST['email'] ) : '';
	$phone    = isset( $_POST['phone'] ) ? sanitize_text_field( $_POST['phone'] ) : '';
	$company  = isset( $_POST['company'] ) ? sanitize_text_field( $_POST['company'] ) : '';
	$company_name = isset( $_POST['business_name'] ) ? sanitize_text_field( $_POST['business_name'] ) : $company;
	$message  = isset( $_POST['message'] ) ? sanitize_textarea_field( $_POST['message'] ) : '';
	$source   = isset( $_POST['source'] ) ? sanitize_text_field( $_POST['source'] ) : '';
	$call_time = isset( $_POST['call_time'] ) ? sanitize_text_field( $_POST['call_time'] ) : '';
	$biz_type = isset( $_POST['business_type'] ) ? sanitize_text_field( $_POST['business_type'] ) : '';
	$volume   = isset( $_POST['monthly_volume'] ) ? sanitize_text_field( $_POST['monthly_volume'] ) : '';
	$processor = isset( $_POST['current_processor'] ) ? sanitize_text_field( $_POST['current_processor'] ) : '';

	// Contact form specific fields
	$country  = isset( $_POST['country'] ) ? sanitize_text_field( $_POST['country'] ) : '';
	$firm_location = isset( $_POST['firm-location'] ) ? sanitize_text_field( $_POST['firm-location'] ) : '';
	$optradio = isset( $_POST['optradio'] ) ? sanitize_text_field( $_POST['optradio'] ) : '';

	// Verify CAPTCHA (if form is quoteForm or main-contact-form and email is not the test bypass email)
	$is_test_email = ( strtolower( trim( $email ) ) === 'salih@codeatech.com' );
	if ( ( $form_id === 'quoteForm' || $form_id === 'main-contact-form' ) && ! $is_test_email ) {
		$captcha_response = isset( $_POST['captcha'] ) ? sanitize_text_field( $_POST['captcha'] ) : '';
		$secret_key = '6LcTRkEtAAAAAKonxwTPvNJLO243D2Ot85xT6wyo';
		$verify_url = 'https://www.google.com/recaptcha/api/siteverify';
		
		$response = wp_remote_post( $verify_url, array(
			'body' => array(
				'secret'   => $secret_key,
				'response' => $captcha_response,
				'remoteip' => $_SERVER['REMOTE_ADDR'],
			),
		) );
		
		if ( is_wp_error( $response ) ) {
			echo wp_json_encode( array( 'success' => false, 'message' => 'CAPTCHA verification request failed.' ) );
			wp_die();
		}
		
		$response_body = wp_remote_retrieve_body( $response );
		$result = json_decode( $response_body, true );
		
		if ( empty( $result['success'] ) ) {
			echo wp_json_encode( array( 'success' => false, 'message' => 'Invalid CAPTCHA verification.' ) );
			wp_die();
		}
	}

	// Build email body
	$to = 'salih@codeatech.com';
	$subject = 'New Lead from Merchant Pro Form: ' . esc_html( $form_id );
	
	$body = "You have received a new form submission.\n\n";
	$body .= "Form ID: " . $form_id . "\n";
	if ( $source ) {
		$body .= "Source: " . $source . "\n";
	}
	if ( $optradio ) {
		$account_type = ($optradio === 'new') ? 'New Merchant Account' : 'Existing Merchant Account';
		$body .= "Account Type: " . $account_type . "\n";
	}
	if ( $name ) {
		$body .= "Name: " . $name . ( $last_name ? ' ' . $last_name : '' ) . "\n";
	}
	if ( $email ) {
		$body .= "Email: " . $email . "\n";
	}
	if ( $phone ) {
		$body .= "Phone: " . $phone . "\n";
	}
	if ( $country ) {
		$body .= "Country: " . $country . "\n";
	}
	if ( $firm_location ) {
		$body .= "Firm Location: " . $firm_location . "\n";
	}
	if ( $company_name ) {
		$body .= "Company/Business: " . $company_name . "\n";
	}
	if ( $biz_type ) {
		$body .= "Business Type: " . $biz_type . "\n";
	}
	if ( $volume ) {
		$body .= "Monthly Volume: " . $volume . "\n";
	}
	if ( $processor ) {
		$body .= "Current Processor: " . $processor . "\n";
	}
	if ( $call_time ) {
		$body .= "Best Time to Call: " . $call_time . "\n";
	}
	if ( $message ) {
		$body .= "Message:\n" . $message . "\n";
	}

	$headers = array('Content-Type: text/plain; charset=UTF-8');

	// Send email using wp_mail
	$sent = wp_mail( $to, $subject, $body, $headers );

	// Respond to client
	if ( $sent ) {
		echo wp_json_encode( array( 'success' => true, 'message' => 'Email sent successfully to ' . $to ) );
	} else {
		echo wp_json_encode( array( 'success' => false, 'message' => 'Mail delivery failed.' ) );
	}
	wp_die();
}
add_action( 'wp_ajax_submit_lead_form', 'merchantpro_handle_ajax_submit' );
add_action( 'wp_ajax_nopriv_submit_lead_form', 'merchantpro_handle_ajax_submit' );

/**
 * Filter the Contact Us page content to fix broken reCAPTCHA key and submission click handler.
 */
function merchantpro_filter_contact_page_content( $content ) {
	// Replace invalid site key with working site key
	$content = str_replace(
		'data-sitekey="6LflEZQqAAAAAPdJQQupJ0HgnaZ4xIBZsYoxmko5"',
		'data-sitekey="6LcTRkEtAAAAAJHjpCOh9J5hSvwGVT1PIF0lJou7"',
		$content
	);

	// Replace undefined sendContact() submit click handler with global submitForm()
	$content = str_replace(
		'onclick="sendContact(); return false;"',
		'onclick="submitForm(event, \'main-contact-form\', \'mail-status\'); return false;"',
		$content
	);

	// Replace empty mail-status div with a hidden success alert container
	$content = str_replace(
		'<div id="mail-status"></div>',
		'<div id="mail-status" class="alert alert-success" style="display: none; margin-top: 15px;">Thank you! Your message has been sent successfully. We will contact you soon.</div>',
		$content
	);
	return $content;
}
add_filter( 'the_content', 'merchantpro_filter_contact_page_content', 99 );
