<?php

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

add_action( 'admin_post_nopriv_sev_tort_lead', 'sev_tort_handle_lead_form' );
add_action( 'admin_post_sev_tort_lead', 'sev_tort_handle_lead_form' );

function sev_tort_handle_lead_form() {
	if ( empty( $_POST['sev_tort_nonce'] ) || ! wp_verify_nonce( sanitize_text_field( wp_unslash( $_POST['sev_tort_nonce'] ) ), 'sev_tort_lead' ) ) {
		sev_tort_redirect_form_status( 'error' );
	}

	if ( empty( $_POST['personal_data_agree'] ) ) {
		sev_tort_redirect_form_status( 'consent' );
	}

	if ( ! empty( $_POST['lead_company'] ) ) {
		sev_tort_redirect_form_status( 'success' );
	}

	$name    = isset( $_POST['lead_name'] ) ? sanitize_text_field( wp_unslash( $_POST['lead_name'] ) ) : '';
	$phone   = isset( $_POST['lead_phone'] ) ? sanitize_text_field( wp_unslash( $_POST['lead_phone'] ) ) : '';
	$email   = isset( $_POST['lead_email'] ) ? sanitize_email( wp_unslash( $_POST['lead_email'] ) ) : '';
	$message = isset( $_POST['lead_message'] ) ? sanitize_textarea_field( wp_unslash( $_POST['lead_message'] ) ) : '';
	$page    = isset( $_POST['lead_page'] ) ? sanitize_text_field( wp_unslash( $_POST['lead_page'] ) ) : '';
	$source  = isset( $_POST['lead_source'] ) ? sanitize_text_field( wp_unslash( $_POST['lead_source'] ) ) : '';

	if ( '' === $phone || ! preg_match( '/^\+7 \([0-9]{3}\) [0-9]{3}-[0-9]{2}-[0-9]{2}$/', $phone ) ) {
		sev_tort_redirect_form_status( 'error' );
	}

	if ( '' !== $email && ! is_email( $email ) ) {
		sev_tort_redirect_form_status( 'error' );
	}

	$text = "Новая заявка с сайта sevastopol-tort.ru\n";
	$text .= "Страница: " . ( $page ? $page : 'не указана' ) . "\n";
	$text .= "Источник: " . ( $source ? $source : 'не указан' ) . "\n";
	$text .= "Имя: " . ( $name ? $name : 'не указано' ) . "\n";
	$text .= "Телефон: " . $phone . "\n";
	$text .= "Почта: " . ( $email ? $email : 'не указана' ) . "\n";
	$text .= "Комментарий: " . ( $message ? $message : 'не указан' );

	$sent = sev_tort_send_telegram_message( $text );

	sev_tort_redirect_form_status( $sent ? 'success' : 'queued' );
}

function sev_tort_send_telegram_message( $text ) {
	if ( ! defined( 'SEV_TORT_TELEGRAM_BOT_TOKEN' ) || ! defined( 'SEV_TORT_TELEGRAM_CHAT_ID' ) ) {
		return false;
	}

	$response = wp_remote_post(
		'https://api.telegram.org/bot' . SEV_TORT_TELEGRAM_BOT_TOKEN . '/sendMessage',
		array(
			'timeout' => 10,
			'body'    => array(
				'chat_id' => SEV_TORT_TELEGRAM_CHAT_ID,
				'text'    => $text,
			),
		)
	);

	return ! is_wp_error( $response ) && 200 === wp_remote_retrieve_response_code( $response );
}

function sev_tort_redirect_form_status( $status ) {
	$referer = wp_get_referer();
	$url     = $referer ? $referer : home_url( '/' );

	wp_safe_redirect( add_query_arg( 'form_status', $status, $url ) );
	exit;
}
