'fasoon_form1_summary_title',
'summary_price_class' => 'fasoon_form1_summary_price',
'summary_partners_class' => 'fasoon_form1_summary_partners',
'summary_partner_tpl_class' => 'fasoon_form1_summary_partner_tpl',
'summary_total_class' => 'fasoon_form1_summary_total',
'plugins_url' => null,
'ajax_url' => null,
];
protected $_template_vars = [
'step1' => [
'form_id' => 'fasoon_form1',
'partner_class' => 'fasoon_form1_partners',
'entry_type_id' => 'entry_type',
'backing_type_id' => 'backing_type',
],
'step2' => [
'form_id' => 'fasoon_form2',
'phone_id' => 'phone',
'email_id' => 'email',
'street_id' => 'street',
'zip_id' => 'zip',
'city_id' => 'city',
'plugins_url' => null,
],
'step3' => [
'form_id' => 'fasoon_form3',
'company_zip_id' => 'company_zip',
'company_city_id' => 'company_city',
'company_canton_id' => 'company_canton',
'plugins_url' => null,
],
'step4' => [
'form_id' => 'fasoon_form4',
'save_action' => 'fqp_step4_save_ajax',
'persons_class' => 'indivuduals',
'add_person_class' => 'add_person',
'add_company_class' => 'add_company',
'new_person_form_class' => 'new_person_form',
'new_company_form_class' => 'new_company_form',
'nationality_id' => null,
'nationality_switzerland_val' => self::NATIONALITY_SWITZERLAND_VAL,
'hometown_id' => null,
'person_zip_id' => 'zip',
'company_zip_id' => 'company_zip',
'company_person_zip_id' => 'comp_zip',
'load_contact_data_id' => 'load_contact_data',
],
'step5' => [
'form_id' => 'fasoon_form5',
],
'step6' => [
'form_id' => 'fasoon_form6',
'payment_method_el_name' => 'payment_method',
'loyalty_card_id_el_name' => 'loyalty_card_id',
'loyalty_card_value_el_name' => 'loyalty_card_value',
'_loyalty_card_id_el_name' => '_loyalty_card_id',
'loyalty_card_apply_el_name' => 'loyalty_card_apply',
'loyalty_card_remove_el_name' => 'loyalty_card_remove',
'summary_product_tpl_class' => 'fasoon_form6_summary_partner_tpl',
'loyalty_card_required_msg' => 'Card ID is required'
],
];
public function __construct() {
add_shortcode( 'fasoon_quote_price', [ $this, 'exec' ] );
// init action
add_filter( 'admin_post_nopriv_fqp_init', [ $this, 'exec_init' ] );
add_filter( 'admin_post_fqp_init', [ $this, 'exec_init' ] );
add_filter( 'admin_post_nopriv_fqp_step1_save', [ $this, 'exec_step1_save' ] );
add_filter( 'admin_post_fqp_step1_save', [ $this, 'exec_step1_save' ] );
add_filter( 'admin_post_nopriv_fqp_step2_save', [ $this, 'exec_step2_save' ] );
add_filter( 'admin_post_fqp_step2_save', [ $this, 'exec_step2_save' ] );
add_filter( 'admin_post_nopriv_fqp_step3_save', [ $this, 'exec_step3_save' ] );
add_filter( 'admin_post_fqp_step3_save', [ $this, 'exec_step3_save' ] );
add_filter( 'admin_post_nopriv_fqp_step4_save', [ $this, 'exec_step4_save' ] );
add_filter( 'admin_post_fqp_step4_save', [ $this, 'exec_step4_save' ] );
if ( wp_doing_ajax() ) {
add_filter( "wp_ajax_nopriv_{$this->_template_vars['step4']['save_action']}", [ $this, 'exec_step4_save_ajax' ] );
add_filter( "wp_ajax_{$this->_template_vars['step4']['save_action']}", [ $this, 'exec_step4_save_ajax' ] );
}
add_filter( 'admin_post_nopriv_fqp_step5_save', [ $this, 'exec_step5_save' ] );
add_filter( 'admin_post_fqp_step5_save', [ $this, 'exec_step5_save' ] );
add_filter( 'admin_post_nopriv_fqp_step6_save', [ $this, 'exec_step6_save' ] );
add_filter( 'admin_post_fqp_step6_save', [ $this, 'exec_step6_save' ] );
add_filter( 'admin_post_nopriv_fqp_send', [ $this, 'exec_send' ] );
add_filter( 'admin_post_fqp_send', [ $this, 'exec_send' ] );
add_filter( 'admin_post_nopriv_fqp_stripe_success', [ $this, 'exec_stripe_success' ] );
add_filter( 'admin_post_fqp_stripe_success', [ $this, 'exec_stripe_success' ] );
add_filter( 'admin_post_nopriv_fqp_stripe_cancel', [ $this, 'exec_stripe_cancel' ] );
add_filter( 'admin_post_fqp_stripe_cancel', [ $this, 'exec_stripe_cancel' ] );
add_filter( 'admin_post_nopriv_fqp_stripe_webhook', [ $this, 'exec_stripe_webhook' ] );
add_filter( 'admin_post_fqp_stripe_webhook', [ $this, 'exec_stripe_webhook' ] );
add_filter( 'admin_post_nopriv_fqp_cron_job', [ $this, 'exec_cron_job' ] );
add_filter( 'admin_post_fqp_cron_job', [ $this, 'exec_cron_job' ] );
if ( wp_doing_ajax() ) {
add_filter( 'wp_ajax_nopriv_apply_loyalty_card', [ $this, 'exec_step6_apply_loyalty_card' ] );
add_filter( 'wp_ajax_apply_loyalty_card', [ $this, 'exec_step6_apply_loyalty_card' ] );
}
}
protected function _get_method( $action ) {
return 'exec_' . strtolower($action);
}
protected function _get_template_vars( $action ) {
$vars = $this->_template_vars_common;
if ( array_key_exists( $action, $this->_template_vars ) ) {
$vars = array_merge($vars, $this->_template_vars[$action]);
$vars['plugins_url'] = plugins_url( '', FQP_PLUGIN_BASE_NAME );
$vars['ajax_url'] = self::get_form_ajax_action();
$vars['gtm_data'] = $this->_get_gtm_data();
$vars['step'] = preg_replace( '/\D+/', '', $action );
switch ( $action ) {
case 'step6':
$vars['loyalty_card_required_msg'] = fqp__( $vars['loyalty_card_required_msg'] );
break;
}
}
return $vars;
}
protected function _get_gtm_data()
{
$data = [];
$forms_data = $this->_get_all_data();
if ( ! empty( $forms_data['step1']['entry_type'] ) ) {
$entry_types = DB::get_entry_types();
$data['legal_form'] = $entry_types[$forms_data['step1']['entry_type']]['gtm_title'];
}
if ( ! empty( $forms_data['step1']['backing_type'] ) ) {
$backing_types = DB::get_backing_types();
$data['backing_type'] = $backing_types[$forms_data['step1']['backing_type']]['gtm_title'];
}
$data['items'] = [];
if ( ! empty( $forms_data['step1']['partners'] ) ) {
$partners_list = DB::get_partners(true);
$partners = [];
foreach ( $forms_data['step1']['partners'] as $partner_ID ) {
if ( array_key_exists( $partner_ID, $partners_list ) ) {
$partners[$partner_ID] = $partners_list[$partner_ID];
$partners[$partner_ID]['partner_ID'] = $partner_ID;
}
}
$partners = $this->_preparePartnersDiscounts($partners);
foreach ( $partners as $partner ) {
$data['items'][] = [
'item_name' => $partner['acf']['api_name'] ?: $partner['post_title'],
'currency' => 'CHF',
'item_category' => 'Partner',
'discount' => $partner['discount'],
];
}
}
$data['GCLID'] = @$_COOKIE['GCLID'] ?: '';
$data['region'] = $forms_data['step3']['company_canton'];
if ( ( $referrer = FQP\FQP::get_referrer() ) ) {
foreach ( FQP\FQP::get_referrer_fields_map() as $param => $key ) {
$data[$param] = $referrer[$key];
}
}
return $data;
}
protected function _get_template_options() {
$options = parent::_get_template_options();
$options['page_url'] = self::get_page_url();
$options['step'] = $this->_action;
$options['data'] = $this->_session( $this->_action ) ?: [];
$options['all_data'] = $this->_get_all_data();
$options['prices'] = Settings::get_prices();
$options['tpl_vars'] = $this->_get_template_vars( $this->_action );
$options['form_errors'] = $this->_session( 'form_errors' );
$this->_session( 'form_errors', null );
return $options;
}
protected function _get_all_data() {
$data = [];
foreach ( array_keys( $this->_template_vars ) as $step ) {
$data[$step] = $this->_session( $step ) ?: [];
}
return $data;
}
protected function _get_post_data() {
$data = [];
$request_method = strtolower( $_SERVER['REQUEST_METHOD'] );
if ( 'post' == $request_method ) {
$data = $_POST;
} elseif ( 'get' == $request_method ) {
$data = $_GET;
} else {
wp_die( 'Wrong Request Method', __METHOD__ );
}
$data = wp_unslash( $data );
$this->sanitize_spaces( $data );
return $data;
}
public function exec() {
$action = @$_REQUEST['action'];
if ( $action ) {
if ( 0 === strpos( $action, 'fqp_' ) ) {
$this->_action = substr( $action, 4 );
} else {
$this->_action = null;
}
} else {
$this->_action = $this->_default_action;
}
if ( null === $this->_action ) {
return '';
}
$method = $this->_get_method( $this->_action );
if ( !method_exists( __CLASS__, $method ) ) {
wp_die( 'Something went wrong!', __METHOD__ );
}
if ( ! wp_doing_ajax() ) {
wp_enqueue_style( 'fasoon-jquery-ui', plugins_url( '/css/jquery-ui.css', FQP_PLUGIN_BASE_NAME ) );
wp_enqueue_style( 'fasoon-jquery-ui-structure', plugins_url( '/css/jquery-ui.structure.css', FQP_PLUGIN_BASE_NAME ) );
wp_enqueue_style( 'fasoon-jquery-ui-theme', plugins_url( '/css/jquery-ui.theme.css', FQP_PLUGIN_BASE_NAME ) );
//wp_enqueue_style( 'fasoon-jquery-ui-theme', '//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css' );
wp_enqueue_script( 'fasoon_quote_tooltip', plugins_url( '/js/fasoon-quote-tooltip.js', FQP_PLUGIN_BASE_NAME ), [ 'jquery-ui-tooltip' ] );
wp_enqueue_script( 'fasoon_quote_form_background', plugins_url( '/js/fasoon-quote-form-background.js', FQP_PLUGIN_BASE_NAME ), [ 'jquery' ] );
wp_enqueue_script( 'fasoon_quote_form_placeholder', plugins_url( '/js/fasoon-quote-form-placeholder.js', FQP_PLUGIN_BASE_NAME ), [ 'jquery' ] );
add_action( 'wp_footer', function() { echo '
'; } );
}
return $this->{$method}();
}
public function exec_init() {
$data = $this->_get_post_data();
if ( !empty( $data ) ) {
FQP\Form\Step1::sanitize_data( $data );
$this->_session( 'step1', $data );
}
$this->_redirect_to( 'step1' );
}
/**
* @param string|FQP\FormAbstract $form
*/
protected function _set_form_entry_type( $form ) {
$step1 = $this->_session( 'step1' );
if ( empty( $step1 ) || empty( $step1['entry_type'] ) ) {
$this->_redirect_to( 'step1' );
}
$form::set_entry_type( $step1['entry_type'] );
if ( ! empty( $step1['backing_type'] ) ) {
$form::set_backing_type( $step1['backing_type'] );
}
}
protected function _enqueue_atl_summary_script( array $script_options ) {
$script_options['container_id'] = 'fasoon_form1';
wp_enqueue_script( 'fasoon-alt-summary-box', plugins_url( '/js/alt-summary-box.js', FQP_PLUGIN_BASE_NAME ), [ 'jquery' ], '1.0.1' );
wp_localize_script( 'fasoon-alt-summary-box', 'fasoon_alt_summary_box_vars', $script_options );
}
public function exec_step1() {
//wp_enqueue_style( 'tooltipster', plugins_url( '/css/tooltipster/tooltipster.bundle.css', FQP_PLUGIN_BASE_NAME ) );
//wp_enqueue_script( 'tooltipster', plugins_url( '/js/tooltipster/tooltipster.bundle.js', FQP_PLUGIN_BASE_NAME ), [ 'jquery' ] );
wp_enqueue_script( 'fasoon_quote_step1', plugins_url( '/js/fasoon-quote-step1.js', FQP_PLUGIN_BASE_NAME ), [ 'jquery', 'underscore' ] );
$script_options = json_encode($this->_get_template_vars( $this->_action ));
wp_add_inline_script( 'fasoon_quote_step1', "jQuery(document).ready(function() { new fasoon.QuotePriceStep1({$script_options}); })" );
$this->_template = 'quote-step1.php';
return parent::exec();
}
public function exec_step1_save() {
$data = $this->_get_post_data();
if ( true === ( $errors = FQP\Form\Step1::sanitize_data( $data ) ) ) {
$this->_session( 'step1', $data );
$this->_session( 'form_errors', null );
$this->_redirect_to( 'step2' );
} else {
$this->_session( 'form_errors', $errors );
$this->_redirect_to( 'step1' );
}
}
public function step1_save_partners( &$data ) {
if ( array_key_exists( 'partners', $data ) ) {
$partners = $data['partners'];
unset( $data['partners'] );
$all_data = $this->_get_all_data();
$canton = null;
if ( array_key_exists( 'step3', $all_data ) && ! empty( $all_data['step3']['company_zip'] ) ) {
$canton = DB::get_canton_by_zip( $all_data['step3']['company_zip'] );
if ( $canton ) {
$canton = $canton['ID'];
}
}
FQP\Form\Step1::sanitize_partners( $partners, $canton );
$step1_data = $this->_session( 'step1' );
$step1_data['partners'] = $partners;
$this->_session( 'step1', $step1_data );
}
}
public function exec_step2() {
$this->_set_form_entry_type( 'FQP\Form\Step2' );
wp_enqueue_style('intl-tel-input', plugins_url('/css/intlTelInput.css', FQP_PLUGIN_BASE_NAME));
wp_enqueue_script('intl-tel-input', plugins_url('/js/intl-tel-input/intlTelInput.js', FQP_PLUGIN_BASE_NAME), ['jquery']);
wp_enqueue_script( 'auto_numeric', plugins_url( '/js/autoNumeric/autoNumeric-min.js', FQP_PLUGIN_BASE_NAME ), [ 'jquery' ] );
wp_enqueue_script( 'fasoon_quote_step2', plugins_url( '/js/fasoon-quote-step2.js', FQP_PLUGIN_BASE_NAME ), [ 'jquery' ] );
$script_options = $this->_get_template_vars( $this->_action );
$script_options_json = json_encode( $script_options );
wp_add_inline_script( 'fasoon_quote_step2', "jQuery(document).ready(function() { new fasoon.QuotePriceStep2({$script_options_json}); })" );
$this->_enqueue_atl_summary_script( $script_options );
$this->_template = 'quote-step2.php';
return parent::exec();
}
public function exec_step2_save() {
$this->_set_form_entry_type( 'FQP\Form\Step2' );
$data = $this->_get_post_data();
$this->step1_save_partners( $data );
$this->_session( 'step2', $data );
if ( true === ( $errors = FQP\Form\Step2::sanitize_data( $data ) ) ) {
$this->_session( 'form_errors', null );
$this->_redirect_to( 'step3' );
} else {
$this->_session( 'form_errors', $errors );
$this->_redirect_to( 'step2' );
}
}
public function exec_step3() {
$this->_set_form_entry_type( 'FQP\Form\Step3' );
wp_enqueue_script( 'auto_numeric', plugins_url( '/js/autoNumeric/autoNumeric-min.js', FQP_PLUGIN_BASE_NAME ), [ 'jquery' ] );
wp_enqueue_script( 'fasoon_quote_step3', plugins_url( '/js/fasoon-quote-step3.js', FQP_PLUGIN_BASE_NAME ), [ 'jquery', 'jquery-ui-autocomplete' ] );
$script_options = $this->_get_template_vars( $this->_action );
$script_options['zip_codes'] = FQP\DB::get_zip_codes( null, true );
$script_options_json = json_encode( $script_options );
wp_add_inline_script( 'fasoon_quote_step3', "jQuery(document).ready(function() { new fasoon.QuotePriceStep3({$script_options_json}); })" );
$this->_enqueue_atl_summary_script( $script_options );
$this->_template = 'quote-step3.php';
return parent::exec();
}
public function exec_step3_save() {
$this->_set_form_entry_type( 'FQP\Form\Step3' );
$data = $this->_get_post_data();
$this->step1_save_partners( $data );
$this->_session( 'step3', $data );
if ( true === ( $errors = FQP\Form\Step3::sanitize_data( $data ) ) ) {
$this->_session( 'form_errors', null );
$this->_redirect_to( 'step4' );
} else {
$this->_session( 'form_errors', $errors );
$this->_redirect_to( 'step3' );
}
}
public function exec_step4() {
$this->_set_form_entry_type( 'FQP\Form\Step4' );
wp_enqueue_script( 'auto_numeric', plugins_url( '/js/autoNumeric/autoNumeric-min.js', FQP_PLUGIN_BASE_NAME ), [ 'jquery' ] );
wp_enqueue_script(
'fasoon_quote_step4',
plugins_url( '/js/fasoon-quote-step4.js', FQP_PLUGIN_BASE_NAME ),
[ 'jquery', 'jquery-serialize-object' ]
);
if ( 'de' == FQP\FQP::get_curr_lang() ) {
wp_enqueue_script(
'fasoon_quote_datepicker_de',
plugins_url( '/js/jquery-ui/datepicker-de.js', FQP_PLUGIN_BASE_NAME ),
[ 'jquery-ui-datepicker' ]
);
}
wp_enqueue_script(
'fasoon_quote_datepicker',
plugins_url( '/js/fasoon-quote-datepicker.js', FQP_PLUGIN_BASE_NAME ),
[ 'jquery-ui-datepicker' ]
);
$script_options = $this->_get_template_vars( $this->_action );
$script_options['nationality_id'] = FQP\Form\Step4::get_html_id( 'nationality' );
$script_options['hometown_id'] = FQP\Form\Step4::get_html_id( 'hometown' );
$script_options['persons_data'] = $this->_session( 'step4' );
$contact_data = (array) $this->_session( 'step2' );
$fields = array_keys( FQP\Form\Step4::get_fields( 'person' ) );
foreach ( array_keys( $contact_data ) as $key ) {
if ( ! in_array( $key, $fields ) ) {
unset( $contact_data[$key] );
}
}
$script_options['contact_data'] = $contact_data;
$script_options['contact_data_confirmation'] = fqp__( 'Do you really wont override entered data?' );
$script_options_json = json_encode( $script_options );
wp_add_inline_script(
'fasoon_quote_step4',
"jQuery(document).ready(function() { new fasoon.QuotePriceStep4({$script_options_json}); })"
);
$this->_enqueue_atl_summary_script( $script_options );
$this->_template = 'quote-step4.php';
return parent::exec();
}
public function exec_step4_save() {
$this->_set_form_entry_type( 'FQP\Form\Step4' );
$post_data = $this->_get_post_data();
$this->step1_save_partners( $post_data );
$data = $this->_session( 'step4' );
if ( ! empty( $data ) ) {
$data = array_filter($data);
}
if ( empty( $data ) ) {
/*$data = [
'_completed' => true, // треба для того щоб визначити чи юзер вже пройшов цей крок
];
$this->_session( 'step4', $data );
$this->_redirect_to( 'step5' );*/
$this->_session( 'form_errors', [ fqp__( 'Please add at least one person' ) ] );
$this->_redirect_to( 'step4' );
} else {
$this->_session( 'form_errors', null );
$this->_redirect_to( 'step5' );
}
}
public function exec_step4_save_ajax() {
$this->_set_form_entry_type( 'FQP\Form\Step4' );
$data = $this->_get_post_data();
$result = [];
if ( ! wp_verify_nonce( $data['_wpnonce'], "{$this->_template_vars['step4']['save_action']}_{$data['person_type']}" ) ) {
$result['is_success'] = false;
$result['wrong_nonce'] = true;
die( json_encode( $result ) );
}
$sub_action = @$data['sub_action'] ?: 'save';
switch ( $sub_action ) {
case 'save':
$result = $this->_step4_save_person( $data );
break;
case 'delete':
$result = $this->_step4_delete_person( $data );
break;
default:
$result['is_success'] = false;
$result['error'] = 'Unknown subaction!';
}
$this->_display_json( $result );
}
protected function _clear_person_data( &$data ) {
unset(
$data['_wpnonce'],
$data['_wp_http_referer'],
$data['id'],
$data['action'],
$data['sub_action']
);
}
protected function _step4_save_person( $data ) {
if ( true !== ( $errors = FQP\Form\Step4::sanitize_data( $data ) ) ) {
$result['is_success'] = false;
array_walk( $errors, function ( &$val ) {
$val = fqp_esc_html__( $val );
} );
$result['error'] = implode( '
', $errors );
return $result;
}
$session_data = $this->_session( 'step4' );
$type_data = ( ! empty( $session_data[$data['person_type']] ) ) ? $session_data[$data['person_type']] : [];
$id = @$data['id'];
$this->_clear_person_data( $data );
if ($id) {
if ( array_key_exists( $id, $type_data ) ) {
$type_data[$id] = $data;
}
} else {
$id = md5( json_encode( $data ) . microtime( true ) );
$type_data[$id] = $data;
}
$session_data[$data['person_type']] = $type_data;
$this->_session( 'step4', $session_data );
$entry_type = $this->_session( 'step1' )['entry_type'];
$result['is_success'] = true;
$result['persons_html'] = static::step4_render_list( $session_data, $entry_type );
$result['persons_data'] = $session_data;
$result['person'] = $type_data[$id];
$result['action'] = 'save';
return $result;
}
protected function _step4_delete_person( $data ) {
$id = $data['id'];
$type = $data['person_type'];
$session_data = $this->_session( 'step4' );
$type_data = ( ! empty( $session_data[$type] ) ) ? $session_data[$type] : [];
$this->_clear_person_data( $data );
$person = $type_data[$id];
if ( ! empty( $type_data[$id] ) && $type_data[$id] == $data ) {
unset( $type_data[$id] );
}
$session_data[$type] = $type_data;
$this->_session( 'step4', $session_data );
$entry_type = $this->_session( 'step1' )['entry_type'];
$result['is_success'] = true;
$result['persons_html'] = static::step4_render_list( $session_data, $entry_type );
$result['persons_data'] = $session_data;
$result['person'] = $person;
$result['action'] = 'delete';
return $result;
}
public static function step4_render_list( $data, $entry_type ) {
if ( empty( $data ) || ! $entry_type ) {
return '';
}
FQP\Form\Step4::filter_data( $data );
ob_start();
include FQP_PLUGIN_DIR_PATH . 'templates/quote-step4-persons-list.php';
$output = ob_get_contents();
ob_end_clean();
return $output;
}
public function exec_step5() {
$this->_set_form_entry_type( 'FQP\Form\Step5' );
if ( ! in_array( FQP\Form\Step5::get_entry_type(), [ FQP\FQP::ENTRY_TYPE_AG, FQP\FQP::ENTRY_TYPE_LTD ] ) ) {
$this->_redirect_to( 'step6' );
}
wp_enqueue_script( 'auto_numeric', plugins_url( '/js/autoNumeric/autoNumeric-min.js', FQP_PLUGIN_BASE_NAME ), [ 'jquery' ] );
wp_enqueue_script( 'fasoon_quote_step5', plugins_url( '/js/fasoon-quote-step5.js', FQP_PLUGIN_BASE_NAME ), [ 'jquery' ] );
$script_options = $this->_get_template_vars( $this->_action );
$script_options['shares_number_id'] = FQP\Form\Step5::get_html_id( '_shares_number' );
$script_options['equity_capital_id'] = FQP\Form\Step5::get_html_id( 'equity_capital' );
$script_options['share_price_id'] = FQP\Form\Step5::get_html_id( 'share_price' );
if ( FQP\FQP::ENTRY_TYPE_LTD == FQP\Form\Step5::get_entry_type() ) {
$script_options['share_text'] = [
'singular' => fqp__( 'EN Stammanteile' ),
'plural' => fqp__( 'EN Stammanteile' ),
];
} else {
$script_options['share_text'] = [
'singular' => fqp__( 'EN Aktie' ),
'plural' => fqp__( 'EN Aktien' ),
];
}
$script_options_json = json_encode( $script_options );
wp_add_inline_script( 'fasoon_quote_step5', "jQuery(document).ready(function() { new fasoon.QuotePriceStep5({$script_options_json}); })" );
$this->_enqueue_atl_summary_script( $script_options );
$this->_template = 'quote-step5.php';
return parent::exec();
}
public function exec_step5_save() {
$this->_set_form_entry_type( 'FQP\Form\Step5' );
$data = $this->_get_post_data();
$this->step1_save_partners( $data );
$this->_session( 'step5', $data );
$persons = $this->_session( 'step4' );
if ( true === ( $errors = FQP\Form\Step5::sanitize_data( $data, $persons ) ) ) {
$this->_session( 'step5', $data );
$this->_session( 'form_errors', null );
$this->_redirect_to( 'step6' );
} else {
$this->_session( 'form_errors', $errors );
$this->_redirect_to( 'step5' );
}
}
public function exec_step6() {
$this->_set_form_entry_type( 'FQP\Form\Step2' );
$this->_set_form_entry_type( 'FQP\Form\Step3' );
$this->_set_form_entry_type( 'FQP\Form\Step4' );
$this->_set_form_entry_type( 'FQP\Form\Step5' );
$this->_set_form_entry_type( 'FQP\Form\Step6' );
wp_enqueue_script( 'jquery-mask', plugins_url( '/js/jquery.mask.js', FQP_PLUGIN_BASE_NAME ), [ 'jquery' ], '1.14.16' );
wp_enqueue_script( 'fasoon_quote_step6', plugins_url( '/js/fasoon-quote-step6.js', FQP_PLUGIN_BASE_NAME ), [ 'jquery' ] );
$script_options = $this->_get_template_vars( $this->_action );
$script_options['order_total'] = FQP\Form\Step6::get_order_total( $this->_get_all_data() );
$script_options_json = json_encode( $script_options );
wp_add_inline_script( 'fasoon_quote_step6', "var QuotePriceStep6 = null; jQuery(document).ready(function() { QuotePriceStep6 = new fasoon.QuotePriceStep6({$script_options_json}); })" );
FQP\Product::enqueue_scripts($script_options);
$this->_template = 'quote-step6.php';
return parent::exec();
}
public function exec_step6_save() {
$this->_set_form_entry_type( 'FQP\Form\Step6' );
$data = $this->_get_post_data();
$this->_session( 'step6', $data );
$all_data = $this->_get_all_data();
if ( true === ( $errors = FQP\Form\Step6::sanitize_data( $data, $all_data ) ) ) {
$this->_session( 'step6', $data );
$this->_session( 'form_errors', null );
$this->_redirect_to( self::get_form_action() . '&action=fqp_send' );
} else {
$this->_session( 'form_errors', $errors );
$this->_redirect_to( 'step6' );
}
}
public function exec_step6_apply_loyalty_card()
{
try {
$post_data = $this->_get_post_data();
$card = InnocardLoyalty\Card::get( $post_data['loyalty_card_id'] );
$result = [
'is_success' => true,
'loyalty_card_id' => $card['AppPAN'],
'loyalty_card_value' => $card['Balance'],
];
} catch (InnocardLoyalty\InnocadLoyaltyException $e) {
$result = [
'is_success' => false,
'error' => $e->getMessage(),
];
}
$this->_display_json( $result );
}
public function exec_send() {
/** @var \wpdb $wpdb */
global $wpdb;
$this->_set_form_entry_type( 'FQP\Form\Step2' );
$this->_set_form_entry_type( 'FQP\Form\Step3' );
$this->_set_form_entry_type( 'FQP\Form\Step4' );
$this->_set_form_entry_type( 'FQP\Form\Step5' );
$this->_set_form_entry_type( 'FQP\Form\Step6' );
// validate & collect data
$all_data = [];
foreach ( array_keys( $this->_template_vars ) as $step ) {
$data = (array) $this->_session( $step );
/** @var FQP\FormAbstract $class */
$class = 'FQP\\Form\\' . ucfirst( $step );
if ( 'step4' == $step ) {
unset( $data['_completed'] );
foreach ( $data as $persons ) {
foreach ( $persons as $person ) {
/** @var FQP\Form\Step4 $class */
if ( true !== ( $errors = $class::sanitize_data( $person ) ) ) {
$this->app_log( print_r( $errors, true ), true );
$this->_session( 'form_errors', $errors );
$this->_redirect_to( $step );
}
}
}
$class::filter_data( $data );
} elseif ( 'step5' == $step ) {
/** @var FQP\Form\Step5 $class */
if ( true !== ( $errors = $class::sanitize_data( $data, $all_data['step4'] ) ) ) {
$this->app_log( print_r( $errors, true ), true );
$this->_session( 'form_errors', $errors );
$this->_redirect_to( $step );
}
$class::filter_data( $data, $all_data['step4'] );
} else {
if ( true !== ( $errors = $class::sanitize_data( $data ) ) ) {
$this->app_log( print_r( $errors, true ), true );
$this->_session( 'form_errors', $errors );
$this->_redirect_to( $step );
}
$class::filter_data( $data );
}
$all_data[$step] = $data;
} // validate & collect data - end
if ( ! ( $submission_ID = $this->_save_submission( $all_data ) ) ) {
$errors = [ 'Can\'t save quote submission' ];
$this->app_log( print_r( $errors, true ), true );
$this->_session( 'form_errors', $errors );
$this->_redirect_to( 'step1' );
}
$submission = DB::get_submission( $submission_ID );
if ( ! $this->_send_notifications( $submission )) {
$errors = [ 'Can\'t send admin notification' ];
$this->app_log( print_r( $errors, true ), true );
/*$this->_session( 'form_errors', $errors );
$this->_redirect_to( 'step1' );*/
}
$this->app_log( "Created submission ID {$submission_ID}" );
$this->zoho_export( $submission );
$this->_clear_session();
$order_total = FQP\Form\Step6::get_order_total( $all_data );
$amount = 0;
$amount = bcadd( $amount, $order_total['total'], 2 );
$amount = bcadd( $amount, $order_total['tax'], 2 );
$amount = bcadd( $amount, $order_total['products_total'], 2 );
$amount = bcadd( $amount, $order_total['products_tax'], 2 );
$amount = bcadd( $amount, $order_total['payment_fee'], 2 );
$amount = bcadd( $amount, $order_total['payment_fee_tax'], 2 );
if ( $order_total['loyalty_card_discount'] ) {
$loyalty_card_transaction = $this->_process_loyalty_card_transaction(
$submission['loyalty_card_id'],
$order_total['loyalty_card_discount']
);
if ( false !== $loyalty_card_transaction ) {
$amount = bcsub( $amount, $order_total['loyalty_card_discount'], 2 );
}
}
if (
! empty( $all_data['step6']['payment_method'] )
&& 'stripe' == $all_data['step6']['payment_method']
&& $amount > 0
&& ( $api_key = get_option( 'fqp_stripe_secret_key' ) )
) {
$entry_types = \FQP\DB::get_entry_types();
$backing_types = \FQP\DB::get_backing_types();
$et_id = @$all_data['step1']['entry_type'];
$bt_id = @$all_data['step1']['backing_type'];
$name = fqp__( $entry_types[$et_id]['title'] );
if ( 'y' == $entry_types[$et_id]['hasBacking'] ) {
$name .= ' ' . fqp__( 'with' ) . ' ' . fqp__( $backing_types[ $bt_id ]['title'] );
}
$name .= ' (Submission ID ' . $submission_ID . ')';
try {
\Stripe\Stripe::setApiKey( $api_key );
$session = \Stripe\Checkout\Session::create([
'payment_method_types' => ['card'],
'line_items' => [[
'name' => $name,
'amount' => bcmul( $amount, 100, 0),
'currency' => 'chf',
'quantity' => 1,
]],
'success_url' => self::get_form_action() . '&action=fqp_stripe_success&session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => self::get_form_action() . '&action=fqp_stripe_cancel',
]);
$result = $wpdb->update(
DB::get_table_name( 'submission' ),
[ 'stripe_checkout_session_id' => $session->id, 'payment_status' => 'pending' ],
[ 'ID' => $submission_ID ]
);
if ( ! $result ) {
$this->stripe_log( $wpdb->last_error, true );
$this->_redirect_to_cancel_page();
}
} catch (Exception $e) {
$this->stripe_log( $e->getMessage(), true );
$this->_redirect_to_cancel_page();
}
$this->_process_stripe_payment( $session );
}
$url = Settings::get_thanks_url();
if ( ! $url ) {
$url = get_site_url();
}
$this->_redirect_to( $url );
}
/**
* @param $card_id
* @param $amount
* @return array|false
*/
protected function _process_loyalty_card_transaction($card_id, $amount)
{
try {
$terminal = InnocardLoyalty\Terminal::get( InnocardLoyalty\Terminal::TYPE_MERCHANT );
$transaction = InnocardLoyalty\Transaction::put($terminal['TrmID'], $card_id, $amount);
$this->app_log( 'InnocardLoyalty\Transaction: ' . json_encode( $transaction ) );
} catch ( InnocardLoyalty\InnocadLoyaltyException $e ) {
$this->app_log( 'InnocardLoyalty\Transaction Error: ' . $e->getMessage(), true );
return false;
}
return $transaction;
}
protected function _process_stripe_payment( \Stripe\Checkout\Session $session )
{
?>
Redirecting...
document.location.href="' . fqp_esc_attr__( $url ) . '"';
} else {
wp_redirect( $url );
}
exit;
}
/**
* @return bool|array
*/
protected function _session() {
$args = func_get_args();
switch ( count( $args )) {
case 1:
return @$_SESSION[$this->_session_name][$args[0]];
break;
case 2:
$_SESSION[$this->_session_name][$args[0]] = $args[1];
return true;
break;
}
wp_die('Function params is wrong.', __METHOD__);
return false;
}
protected function _clear_session() {
$_SESSION[$this->_session_name] = [];
}
protected function _save_submission( array $data ) {
/** @var \wpdb $wpdb */
global $wpdb;
$entry_types = DB::get_entry_types();
$backing_types = DB::get_backing_types();
$prices = Settings::get_prices();
$curr_lang = FQP\FQP::get_curr_lang();
$lang_list = FQP\FQP::get_lang_list();
$partners = [];
if ( ! empty( $data['step1']['partners'] ) && is_array( $data['step1']['partners'] ) ) {
$partners_list = DB::get_partners( true );
foreach ( $partners_list as $partner ) {
if ( in_array( $partner['ID'], $data['step1']['partners'] ) ) {
$partners[] = [
'submission_ID' => null,
'partner_ID' => $partner['ID'],
'title' => $partner['post_title'],
'api_name' => @$partner['acf']['api_name'],
'discount' => 0,
];
}
}
$banks_list = FQP\Bank::get();
foreach ($banks_list as $bank) {
if ( in_array( $bank->ID, $data['step1']['partners'] ) ) {
$partners[] = [
'submission_ID' => null,
'partner_ID' => $bank->ID,
'title' => $bank->post_title,
'discount' => 0,
'api_name' => @$bank->acf['api_name'],
'_discounts' => FQP\Bank::fetch_discounts( $bank ),
];
}
}
}
$products = [];
if ( ! empty( $data['step6']['products'] ) && is_array( $data['step6']['products'] ) ) {
$products_list = FQP\Product::get_query( $data['step1']['entry_type'], @$data['step1']['backing_type'] );
if ( $products_list && $products_list->have_posts() ) {
foreach ( $products_list->posts as $prod ) {
if ( in_array( $prod->ID, $data['step6']['products'] ) ) {
$price = get_field( 'price', $prod );
$products[] = [
'submission_ID' => null,
'product_ID' => $prod->ID,
'title' => $prod->post_title,
'price' => $price,
'tax' => self::claclulateTax( $price, FQP\FQP::VAT ),
];
}
}
}
}
$_data = $data['step1'] + $data['step2'] + $data['step3'];
unset( $_data['partners'] );
$_data['entry_type_ID'] = $_data['entry_type'];
$_data['entry_type'] = $entry_types[$_data['entry_type_ID']]['title'];
$_data['backing_type_ID'] = $_data['backing_type'] ?: null;
if (null !== $_data['backing_type_ID']) {
$_data['backing_type'] = $backing_types[$_data['backing_type_ID']]['title'];
$_data['price'] = $prices['price'][$_data['entry_type_ID']][$_data['backing_type_ID']][$curr_lang];
} else {
$_data['price'] = $prices['price'][$_data['entry_type_ID']][$curr_lang];
}
if ( ! empty( $data['step5'] ) ) {
$_data += $data['step5'];
unset( $_data['person_shares'] );
}
$_data += $data['step6'];
unset( $_data[ 'products'] );
$_data['email_subscription'] = ( 'y' == $_data['email_subscription'] ) ? 'y' : 'n';
$_data['agree'] = ( 'y' == $_data['agree'] ) ? 'y' : 'n';
$payment_method = null;
if ( $_data['payment_method'] ) {
$payment_method = $_data['payment_method'];
$_data['payment_method'] = ucfirst( $_data['payment_method'] );
}
$_total = FQP\Form\Step6::get_order_total($data, $payment_method);
$_data['tax'] = $_total['tax'];
$_data['payment_fee'] = $_total['payment_fee'];
$_data['payment_fee_tax'] = $_total['payment_fee_tax'];
unset( $_data['zc_gad'], $_data['company_canton'] );
$_data['language'] = $lang_list[$curr_lang]['native_name'];
$_data['referrer'] = serialize(FQP\FQP::get_referrer());
if ( $_data['loyalty_card_id'] ) {
$_data['loyalty_card_id'] = $data['step6']['loyalty_card_id'];
try {
$card = InnocardLoyalty\Card::get( $_data['loyalty_card_id'] );
$_data['loyalty_card_value'] = $card['Balance'];
} catch (InnocardLoyalty\InnocadLoyaltyException $e) {
if ( WP_DEBUG ) {
wp_die( $e->getMessage() );
}
}
}
$this->clear_empty( $_data );
$result = $wpdb->insert( DB::get_table_name( 'submission' ), $_data );
if ( ! $result ) {
$this->db_log( $wpdb->last_error, true );
if ( WP_DEBUG ) {
wp_die( $wpdb->last_error );
}
return $result;
}
$submission_ID = $wpdb->insert_id;
if ( $partners ) {
$partners = $this->_preparePartnersDiscounts( $partners );
foreach ( $partners as $partner ) {
$partner['submission_ID'] = $submission_ID;
$this->clear_empty( $partner );
$result = $wpdb->insert( DB::get_table_name( 'submission_partner' ), $partner );
if ( ! $result ) {
$this->db_log( $wpdb->last_error, true );
}
}
}
if ( $products ) {
foreach ( $products as $product ) {
$product['submission_ID'] = $submission_ID;
$this->clear_empty( $product );
$result = $wpdb->insert( DB::get_table_name( 'submission_product' ), $product );
if ( ! $result ) {
$this->db_log( $wpdb->last_error, true );
}
}
}
$country_nationality = DB::get_nationality();
$dictionary = [
'nationality' => $country_nationality,
'company_country' => $country_nationality,
'vr_function_in_company' => DB::get_vr_function_in_company(),
'function_in_company' => DB::get_function_in_company(),
'signature_authorization' => DB::get_signature_authorization(),
];
foreach ( $data['step4'] as $type => $persons ) {
foreach ( $persons as $person_id => $person ) {
$person['submission_ID'] = $submission_ID;
$person['type'] = $type;
$person['birth_date'] = $this->prepere_date($person['birth_date']);
if ( ! empty( $data['step5']['person_shares'] ) ) {
$person['shares_number'] = @$data['step5']['person_shares'][$person_id];
}
$dict_fields = [ 'nationality', 'vr_function_in_company', 'function_in_company', 'signature_authorization', 'company_country' ];
foreach ( $dict_fields as $field ) {
if ( array_key_exists( $field, $person ) ) {
$person["{$field}_ID"] = $person[$field];
$person[$field] = fqp_array_get(@$dictionary[$field], @$person["{$field}_ID"], '');
}
}
$this->clear_empty( $person );
$result = $wpdb->insert( DB::get_table_name( 'submission_person' ), $person );
if ( ! $result ) {
$this->db_log( $wpdb->last_error, true );
}
}
}
return $submission_ID;
}
/**
* @param array $partners
* @return array
*/
protected function _preparePartnersDiscounts($partners)
{
$prices = Settings::get_prices();
$all_data = self::_get_all_data();
$entry_type_ID = $all_data['step1']['entry_type'];
$backing_type_ID = $all_data['step1']['backing_type'];
$curr_lang = FQP\FQP::get_curr_lang();
if (null !== $backing_type_ID) {
$price = $prices['price'][$entry_type_ID][$backing_type_ID][$curr_lang];
} else {
$price = $prices['price'][$entry_type_ID][$curr_lang];
};
$total = $price;
foreach ( $partners as &$partner ) {
if ( array_key_exists( '_discounts', $partner ) ) {
$_discounts = $partner['_discounts'];
unset( $partner['_discounts'] );
} else {
$_discounts = @$prices['partner_discount'][$partner['partner_ID']];
}
if (null !== $backing_type_ID) {
$partner_discount = @$_discounts[$entry_type_ID][$backing_type_ID];
} else {
$partner_discount = @$_discounts[$entry_type_ID];
}
$discount = bcdiv( bcmul( $price, $partner_discount ), 100, 2 );
if ( 1 == bccomp( $discount, $total, 2 ) ) {
$discount = $total;
}
$total = bcsub( $total, $discount, 2 );
if ( -1 == bccomp( $total, '0', 2 ) ) {
$total = '0';
}
$partner['discount'] = $discount;
}
return $partners;
}
public static function claclulateTax($sum, $vat)
{
$tax = bcdiv( bcmul( $sum, $vat, 3 ), 100, 3 );
$tax = bcmul( $tax, 100, 1 );
$tax = ceil( floatval( $tax ) );
$tax = bcdiv( $tax, 100, 2 );
return $tax;
}
protected function _send_notifications ( $submission ) {
if ( empty( $submission ) ) {
return false;
}
$options = get_option( Settings::OPTION_EMAILS );
$emails = $options['emails'];
$subject = $options['subject'];
$partners = $submission['partners'];
if ( $partners ) {
$submission['partners'] = '';
foreach ( $partners as $partner ) {
$title = fqp_esc_html__( $partner['title'] );
$discount = fqp_esc_html__( fqp_money( $partner['discount'] ) );
$submission['partners'] .= "{$title} (-CHF {$discount}), ";
}
$submission['partners'] = trim( $submission['partners'], ', ' );
} else {
$submission['partners'] = '-';
}
$submission['email_subscription'] = ( 'y' == $submission['email_subscription'] ) ? 'Yes' : 'No';
$submission['terms_and_conditions_agree'] = ( 'y' == $submission['agree'] ) ? 'Yes' : 'No';
$body = nl2br( $options['body'] );
foreach ( $submission as $key => $val) {
if ( is_scalar( $val ) ) {
$val = esc_html( $val );
$body = str_replace( "{{$key}}", $val, $body );
}
}
add_filter( 'wp_mail_content_type', function () { return 'text/html'; } );
return wp_mail( $emails, $subject, $body );
}
protected function _display_json( $data ) {
die( json_encode( $data ) );
}
protected function prepere_date( $date ) {
/* dd.mm.yyyy */
$date = explode( '.', $date );
return sprintf( "%04d-%02d-%02d", $date[2], $date[1], $date[0] );
}
protected function clear_empty( array &$data ) {
foreach ( $data as $key => $val ) {
if ( null === $val || '' === $val ) {
unset( $data[$key] );
}
}
}
public function exec_cron_job() {
die( '' );
/*try {
\FQP\ZOHO::initZCRMRestClient();
$zcrmLeads = \ZCRMModule::getInstance( FQP\ZOHO::MODULE_LEADS );
//vdie( $zcrmLeads->getRecords() );
$email = 'david.zbinden@gmail.com';
$email = $this->escape_zoho_value($email);
$bulkResponse = $zcrmLeads->searchRecordsByCriteria("(Email:equals:{$email})");
vdie($bulkResponse);
} catch (Exception $e) {
vdie($e);
}*/
//$data = FQP\DB::get_submission( 178 ); // Gmbh
//$data = FQP\DB::get_submission( 192 ); // AG
//$data = FQP\DB::get_submission( 2716 ); // AG
//$data = FQP\DB::get_submission( 4288 ); // Products test
//$data = FQP\DB::get_submission( 4874 ); // referrer test
//$data = FQP\DB::get_submission( 4880 );
//static::zoho_export( $data );
//ignore_user_abort();
//for ($i = 7340; $i <= 7363; $i++) {
// $submission = FQP\DB::get_submission($i);
// if (!empty($submission) /*&& empty($submission['zoho_account_id'])*/) {
// //static::zoho_export($submission);
// if ( $submission['zoho_deal_id'] && 'Stripe' == $submission['payment_method'] && 'paid' == $submission['payment_status'] ) {
// static::zoho_log( "Update Deal ID {$submission['zoho_deal_id']}" );
// try {
// FQP\ZOHO::initZCRMRestClient();
//
// try {
// $zcrmDeals = ZCRMModule::getInstance( FQP\ZOHO::MODULE_DEALS );
// /** @var APIResponse $response */
// $response = $zcrmDeals->getRecord( $submission['zoho_deal_id'] );
// } catch (ZCRMException $e) {
// if (APIConstants::RESPONSECODE_NO_CONTENT != $e->getCode()) {
// throw $e;
// }
// }
//
// if ( null !== $response ) {
// /** @var ZCRMRecord $record */
// $record = $response->getData();
// $record->setFieldValue( 'paid_cc', true );
// //$record->setFieldValue( 'Deal_Name', 'CC PAID' );
// /** @var BulkAPIResponse $response */
// $response = $zcrmDeals->updateRecords( [ $record ] );
// $response = $response->getResponseJSON();
// if ('success' != @$response['data']['0']['status']) {
// static::zoho_log( [ json_encode($response), PHP_EOL ], true );
// }
// }
// } catch (Exception $e) {
// static::zoho_log( [ $e->getMessage(), PHP_EOL ], true );
// }
// }
//
// echo "{$submission['zoho_deal_id']} done
";
// flush();
// }
//}
}
protected function escape_zoho_value( $value ) {
return str_replace(
['(', ')', '|'],
['\(', '\)', '\|'],
$value
);
}
protected function zoho_export( $data ) {
if ( ! $data ) {
static::zoho_log( [ 'Data is empty!', PHP_EOL ], true );
return;
}
global $wpdb;
static::zoho_log( "Export Submission ID {$data['ID']}" );
try {
FQP\ZOHO::initZCRMRestClient();
/*if ('78.111.219.54' == $_SERVER['REMOTE_ADDR']) {
try {
$zcrmDeals = ZCRMModule::getInstance(FQP\ZOHO::MODULE_DEALS);
//vdie($zcrmDeals->getRecord('98392000000528042'));
vdie($zcrmDeals->getRecord('2522347000000283001'));
} catch (ZCRMException $e) {
vdie($e);
}
}*/
// перевіряємо чи є екаунт
try {
$account_id = null;
$zcrmAccounts = ZCRMModule::getInstance(FQP\ZOHO::MODULE_ACCOUNTS);
/** @var BulkAPIResponse $bulkResponse */
$company_name = $this->escape_zoho_value($data['company_name']);
$bulkResponse = $zcrmAccounts->searchRecordsByCriteria("(Account_Name:equals:{$company_name})");
$records = $bulkResponse->getData();
/** @var ZCRMRecord $record */
foreach ($records as $record) {
$account_id = $record->getEntityId();
break;
}
} catch (ZCRMException $e) {
if (APIConstants::RESPONSECODE_NO_CONTENT != $e->getCode()) {
throw $e;
}
}
// якщо не знайшли екаунт, то треба створити його
if (!$account_id) {
$account = ZCRMRecord::getInstance(FQP\ZOHO::MODULE_ACCOUNTS, null);
FQP\ZOHO\Accounts::setModuleData($account, $data);
$records = [ $account ];
/** @var BulkAPIResponse $response */
$response = $zcrmAccounts->createRecords($records);
$response = $response->getResponseJSON();
if ('success' != @$response['data']['0']['status']) {
static::zoho_log( [ json_encode($response), PHP_EOL ], true );
return;
}
$account_id = @$response['data']['0']['details']['id'];
if (!$account_id) {
static::zoho_log( [ 'Can\'t Find Zoho Account ID: ' . print_r( $account, true ), PHP_EOL ], true );
return;
} else {
static::zoho_log( "Created Zoho Account ID: {$account_id}" );
}
} else {
static::zoho_log( "Use Zoho Account ID: {$account_id}" );
}
$wpdb->update(
DB::get_table_name('submission'),
[ 'zoho_account_id' => $account_id ],
[ 'ID' => $data['ID']]
);
// вибираємо екаунт по ID
/** @var APIResponse $account */
$account = $zcrmAccounts->getRecord($account_id);
$account = $account->getResponseJSON();
$account_name = @$account['data']['0']['Account_Name'];
if ( ! $account_name ) {
static::zoho_log( [ 'Can\'t Find Zoho Account Name: ' . print_r( $account, true ), PHP_EOL ], true );
return;
}
$data['company_name'] = $account_name;
// перевіряємо чи є контакт
try {
$contact_id = null;
$zcrmContacts = ZCRMModule::getInstance(FQP\ZOHO::MODULE_CONTACTS);
/** @var BulkAPIResponse $bulkResponse */
$email = $this->escape_zoho_value($data['email']);
$bulkResponse = $zcrmContacts->searchRecordsByCriteria("(Email:equals:{$email})");
$records = $bulkResponse->getData();
/** @var ZCRMRecord $record */
foreach ($records as $record) {
$contact_id = $record->getEntityId();
break;
}
} catch (ZCRMException $e) {
if (APIConstants::RESPONSECODE_NO_CONTENT != $e->getCode()) {
throw $e;
}
}
// якщо не знайшли контакт, то треба створити його
if ( ! $contact_id ) {
$contact = ZCRMRecord::getInstance(FQP\ZOHO::MODULE_CONTACTS, null);
FQP\ZOHO\Contacts::setModuleData($contact, $data);
$records = [ $contact ];
/** @var BulkAPIResponse $response */
$response = $zcrmContacts->createRecords($records);
$response = $response->getResponseJSON();
if ('success' != @$response['data']['0']['status']) {
static::zoho_log( [ json_encode($response), PHP_EOL ], true );
return;
}
$contact_id = @$response['data']['0']['details']['id'];
if (!$contact_id) {
static::zoho_log( [ 'Can\'t Find Zoho Contact ID: ' . print_r( $response, true ), PHP_EOL ], true );
return;
}
static::zoho_log( "Created Zoho Contact ID: {$contact_id}" );
} else {
static::zoho_log( "Use Zoho Contact ID: {$contact_id}" );
}
$wpdb->update(
DB::get_table_name('submission'),
[ 'zoho_contact_id' => $contact_id ],
[ 'ID' => $data['ID']]
);
// створюємо новий діл
$data['zoho_account_id'] = $account_id;
$data['zoho_contact_id'] = $contact_id;
$zcrmDeals = ZCRMModule::getInstance(FQP\ZOHO::MODULE_DEALS);
$deal = ZCRMRecord::getInstance(FQP\ZOHO::MODULE_DEALS, null);
FQP\ZOHO\Deals::setModuleData($deal, $data);
$records = [ $deal ];
/** @var BulkAPIResponse $response */
$response = $zcrmDeals->createRecords($records);
$response = $response->getResponseJSON();
if ('success' != @$response['data']['0']['status']) {
static::zoho_log( [ json_encode($response), PHP_EOL ], true );
return;
}
$deal_id = @$response['data']['0']['details']['id'];
if (!$deal_id) {
static::zoho_log( [ 'Can\'t Find Zoho Contact ID: ' . print_r( $response, true ), PHP_EOL ], true );
return;
}
static::zoho_log( "Created Zoho Deal ID: {$deal_id}" );
$wpdb->update(
DB::get_table_name('submission'),
[ 'zoho_deal_id' => $deal_id ],
[ 'ID' => $data['ID']]
);
FQP\FQP::clear_referrer();
} catch (Exception $e) {
static::zoho_log( [ $e->getMessage(), PHP_EOL ], true );
}
static::zoho_log( PHP_EOL );
}
public function exec_stripe_success()
{
$url = Settings::get_thanks_url();
if ( ! $url ) {
$url = get_site_url();
}
$this->_redirect_to( $url );
}
public function exec_stripe_cancel()
{
$this->_redirect_to_cancel_page();
}
protected function _redirect_to_cancel_page() {
$url = Settings::get_cancel_url();
if ( ! $url ) {
$url = get_site_url();
}
$this->_redirect_to( $url );
}
public function exec_stripe_webhook()
{
/** @var \wpdb $wpdb */
global $wpdb;
$this->stripe_log( 'Webhook attempt' );
\Stripe\Stripe::setApiKey( get_option( 'fqp_stripe_secret_key' ) );
$endpoint_secret = get_option( 'fqp_stripe_webhooks_secret' );
$payload = @file_get_contents('php://input');
$sig_header = $_SERVER['HTTP_STRIPE_SIGNATURE'];
$event = null;
try {
$event = \Stripe\Webhook::constructEvent( $payload, $sig_header, $endpoint_secret );
} catch(\UnexpectedValueException $e) {
http_response_code(400);
$this->stripe_log( 'Webhook: ' . $e->getMessage() );
exit();
} catch(\Stripe\Exception\SignatureVerificationException $e) {
http_response_code(400);
$this->stripe_log( 'Webhook: ' . $e->getMessage() );
exit();
}
if ($event->type == 'checkout.session.completed') {
/** @var \Stripe\Checkout\Session $session */
$session = $event->data->object;
$sql = 'SELECT `ID`, `zoho_deal_id` FROM `' . DB::get_table_name( 'submission' ) . '` WHERE `stripe_checkout_session_id` = "' . $wpdb->_escape( $session->id ) . '"';
$submission = $wpdb->get_row( $sql );
if ( ! $submission ) {
http_response_code(400);
$this->stripe_log( 'Webhook: FQP submission isn\'t found' );
exit();
}
// update submission payment status
$wpdb->update(
DB::get_table_name( 'submission' ),
[ 'payment_status' => 'paid' ],
[ 'ID' => $submission->ID ]
);
// update zoho deal
if ( $submission->zoho_deal_id ) {
static::zoho_log( "Update Deal ID {$submission->zoho_deal_id}" );
try {
FQP\ZOHO::initZCRMRestClient();
try {
$zcrmDeals = ZCRMModule::getInstance( FQP\ZOHO::MODULE_DEALS );
/** @var APIResponse $response */
$response = $zcrmDeals->getRecord( $submission->zoho_deal_id );
} catch (ZCRMException $e) {
if (APIConstants::RESPONSECODE_NO_CONTENT != $e->getCode()) {
throw $e;
}
}
if ( null !== $response ) {
/** @var ZCRMRecord $record */
$record = $response->getData();
$record->setFieldValue( 'paid_cc', true );
//$record->setFieldValue( 'Deal_Name', 'CC PAID' );
/** @var BulkAPIResponse $response */
$response = $zcrmDeals->updateRecords( [ $record ] );
$response = $response->getResponseJSON();
if ('success' != @$response['data']['0']['status']) {
static::zoho_log( [ json_encode($response), PHP_EOL ], true );
}
}
} catch (Exception $e) {
static::zoho_log( [ $e->getMessage(), PHP_EOL ], true );
}
} else {
static::zoho_log( 'Deal ID is empty (FQP submission ID: ' . $submission->ID . ')' );
}
} else {
$this->stripe_log( 'Webhook: event type is wrong (' . $event->type . ')' );
}
$this->stripe_log( 'Webhook success (FQP submission ID: ' . $submission->ID . ')' );
http_response_code(200);
}
protected function stripe_log( $message, $is_error = false ) {
$this->_log( $message, $is_error, 'stripe.log' );
}
protected function zoho_log( $message, $is_error = false ) {
$this->_log( $message, $is_error, 'zoho.log' );
}
protected function db_log( $message, $is_error = false ) {
$this->_log( $message, $is_error, 'db.log' );
}
protected function app_log( $message, $is_error = false ) {
$this->_log( $message, $is_error, 'application-submissions.log' );
}
protected function _log( $message, $is_error, $log_file ) {
$file = WP_CONTENT_DIR . '/' . $log_file;
$fh = fopen( $file, 'a' );
if ( $fh ) {
if ( ! is_array( $message ) ) {
$message = [ $message ];
}
foreach ( $message as $string ) {
if ( $string === PHP_EOL ) {
$string = '--------------------------------------------------------------------------------'
. PHP_EOL
. PHP_EOL;
} else {
$string = date('Y-m-d H:i:s - ') . ( ( $is_error ) ? 'ERROR - ' : '') . $string . PHP_EOL;
}
fwrite( $fh, $string );
}
}
fclose( $fh );
}
}