<?php
/**
 * Plugin Name: Contact Form 7 for Ascora
 * Plugin URI:  https://www.ascora.com.au/
 * Description: Send an API call based contact form 7 submission.
 * Version:     1.0.0
 * Author:      Ascora
 * Prefix: cf7a
 */
 
if( !class_exists('Contact_Form_7_Ascora') ){
	class Contact_Form_7_Ascora{
		public function __construct(){
			
			add_action( 'wpcf7_mail_sent', array( $this, 'cf7a_before_send_mail' ), 20, 1 );
			
		}
		
		public function cf7a_before_send_mail( $contact_form ){
			if ( !isset( $contact_form->posted_data ) && class_exists( 'WPCF7_Submission' ) ) {
			
				$submission = WPCF7_Submission::get_instance();
				if ( $submission ) {
					
					$formdata = $submission->get_posted_data();
				
			
        			$url = "https://api.ascora.com.au/Enquiry";
        			$token = 'YOUR_TOKEN_HERE';
        			$headers = array();
        			$headers['Auth'] = $token;
        			$headers['Content-type'] = 'application/json';
        			
        			$body = array();
        			$body['companyName'] = "";
        			$body['firstName'] = $formdata['First'];
        			$body['lastName'] = $formdata['Last'];
        			$body['email'] = $formdata['Email'];
        			$body['phone'] = $formdata['Telephone'];
        			$body['mobile'] = "";
        			$body['addressLine1'] = "";
        			$body['addressLine2'] = "";
        			$body['addressSuburb'] = "";
        			$body['addressState'] = "";
        			$body['addressPostcode'] = $formdata['Postcode'];
        			$body['addressCountry'] = "";
        			$body['enquiryDescription'] = $formdata['Message'];
        			
        			$reponse = wp_remote_post( 
        				$url,
        				array(
        					'headers' => $headers,
        					'body' => json_encode( $body ),
        					'timeout' => 120
        				)
        			); 
				}
			}
		}
		
	}
 
}
 
new Contact_Form_7_Ascora();