<?php
/**
 * FluentCRM Service
 *
 * Handles FluentCRM integration for Booktics orders
 */

namespace Booktics\Module\FluentCrm;

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

use Booktics\Contracts\Hookable_Service_Contract;

class FluentCRM_Service implements Hookable_Service_Contract {
	/**
	 * Register hooks
	 */
	public function register() {
		add_action( 'booktics_order_created', array( $this, 'add_contact_to_fluentcrm' ) );
	}

	/**
	 * Add contact to FluentCRM
	 *
	 * @param object $order_model The order model
	 */
	public function add_contact_to_fluentcrm( $order_model ) {
		// Check if FluentCRM is active
		if ( ! defined( 'FLUENTCRM' ) || ! function_exists( 'FluentCrmApi' ) ) {
			return;
		}

		// Get customer details
		$customer = get_user_by( 'id', $order_model->customer_id );
		if ( ! $customer ) {
			return;
		}

        $customer_data = array(
            'email' => $customer->user_email,
            'first_name' => $customer->first_name,
            'last_name' => $customer->last_name ?: '',
            'status' => 'subscribed',
        );

		try {
			// Check if FluentCRM Pro is active (has webhooks)
			$is_pro_active = is_plugin_active('fluent-crm-pro/fluentcampaign-pro.php');
            $fluentcrm_webhook_exists = !empty( booktics_get_option( 'fluentcrm_webhook_url') );
			
            if ( $is_pro_active && $fluentcrm_webhook_exists ) {
				// Use webhook if Pro is active
				$webhook_url = booktics_get_option( 'fluentcrm_webhook_url');

				if ( ! empty( $webhook_url ) ) {
                    $this->send_webhook(
						$webhook_url,
						$customer_data,
					);

                    // Returns if fluentCRM pro exists and is working properly
					return;
				}
			}

			// Fallback to direct API for free version, gets used when fluentCRM pro is not active or webhook is not set.
			$contact_api = FluentCrmApi( 'contacts' );
			$contact_api->createOrUpdate( $customer_data );
		} catch ( \Throwable $e ) {
			// Ensures silent failure in case of any error
			if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
				error_log( 'FluentCRM Error: ' . $e->getMessage() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
			}
		}
	}

	private function send_webhook( $url, $data ) {
		$response = wp_remote_post(
			$url,
			array(
				'body'    => wp_json_encode( $data ),
				'headers' => array(
					'Content-Type' => 'application/json',
				),
				'timeout' => 15,
			)
		);

		if ( is_wp_error( $response ) ) {
			if ( defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
				error_log( 'FluentCRM Webhook Error: ' . $response->get_error_message() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
			}
		}
	}
}
