<?php
/**
 * Bridge: ElementSell → petan_contacts (objednávky + webinářové leady).
 * Na webech bez petan_contacts neudělá nic.
 */
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * @return string
 */
function elementsell_petan_contacts_lib_path() {
	return trailingslashit( ABSPATH ) . 'petan_contacts/lib.php';
}

/**
 * @return bool
 */
function elementsell_petan_contacts_bridge_ready() {
	static $ready = null;

	if ( $ready !== null ) {
		return $ready;
	}

	$lib = elementsell_petan_contacts_lib_path();
	if ( ! is_readable( $lib ) ) {
		$ready = false;
		return false;
	}

	require_once $lib;

	$ready = function_exists( 'petan_tables_exist' ) && petan_tables_exist();

	return $ready;
}

/**
 * @param int $order_id
 * @return void
 */
function elementsell_petan_contacts_sync_order( $order_id ) {
	$order_id = (int) $order_id;
	if ( $order_id <= 0 || ! function_exists( 'elementsell_get_order' ) ) {
		return;
	}

	if ( ! elementsell_petan_contacts_bridge_ready() || ! function_exists( 'petan_sync_contact_from_elementsell_order' ) ) {
		return;
	}

	$order = elementsell_get_order( $order_id );
	if ( ! $order ) {
		return;
	}

	petan_sync_contact_from_elementsell_order( $order );
}

/**
 * Po registraci z WebinarJam / automation → petan list.
 *
 * @param string $email
 * @param string $role_key
 * @param string $name
 * @return void
 */
function elementsell_petan_contacts_sync_webinar_lead( $email, $role_key, $name = '' ) {
	if ( ! elementsell_petan_contacts_bridge_ready() || ! function_exists( 'petan_sync_webinar_lead' ) ) {
		return;
	}

	petan_sync_webinar_lead( (string) $email, (string) $role_key, (string) $name );
}

add_action( 'elementsell_order_saved', 'elementsell_petan_contacts_sync_order', 30, 1 );
add_action( 'elementsell_order_paid', 'elementsell_petan_contacts_sync_order', 30, 1 );

/**
 * Hook hned po úspěšném zápisu webinářového leadu do automation.
 */
add_action(
	'elementsell_automation_webinar_lead_registered',
	'elementsell_petan_contacts_sync_webinar_lead',
	20,
	3
);
