<?php
namespace Booktics\Onboard\Controllers;

use Booktics\Abstracts\Base_Rest_Controller;
use Booktics\Onboard\Onboarding;
use WP_REST_Server;

/**
 * Onboard controller
 *
 * @package Booktics/Onboard
 */
class Onboard_Controller extends Base_Rest_Controller {
    /**
     * Endpoint namespace
     *
     * @var string
     */
    protected $namespace = 'booktics/v1';

    /**
     * Route name
     *
     * @var string
     */
    protected $base = 'onboard';

    /**
     * Register routes
     *
     * @return  void
     */
    public function register_routes(): void {
        register_rest_route(
            $this->namespace, $this->base, array(
				array(
					'methods'             => WP_REST_Server::CREATABLE,
					'callback'            => array( $this, 'setup_profile' ),
					'permission_callback' => array( $this, 'setup_profile_permissions_check' ),
				),
            )
        );
    }

    /**
     * Setup bussinsess profile
     *
     * @param   WP_Rest_Request  $request  Request Object
     *
     * @return  WP_Rest_Response | WP_Error
     */
    public function setup_profile( $request ) {
        $data = json_decode( $request->get_body(), true );

        $result = Onboarding::update( $data );

        if ( is_wp_error( $result ) ) {
            return $this->error( $result->get_error_message() );
        }
        $message = __( 'Successfully updated business profile', 'booktics' );

        $response = $this->prepare_item_for_response( $data, $request );

        // send webhook to fluentcrm
        $this->connect_with_fluentcrm( $request );

        return $this->response( $response, $message );
    }

    /**
     * Check permissions for setup profile
     *
     * @param   WP_Rest_Request  $request
     *
     * @return  WP_Rest_Response | WP_Error
     */
    public function setup_profile_permissions_check( $request ): bool {
        return current_user_can( 'manage_options' );
    }

    /**
     * Prepare item for response
     *
     * @param   array  $item     Response item
     * @param   array  $request  Requested data
     *
     * @return  array            Collection of response data
     */
    public function prepare_item_for_response( $item, $request ): array {
        $data = array(
            'business_email'    => Onboarding::get( 'business_email' ),
            'business_name'     => Onboarding::get( 'business_name' ),
            'business_type'     => Onboarding::get( 'business_type' ),
            'business_timezone' => Onboarding::get( 'business_timezone' ),
            'schedule'          => Onboarding::get( 'schedule' ),
            'onboard_setup'     => Onboarding::get( 'onboard_setup' ),
        );

        return $data;
    }

    /**
     * Connect with FluentCRM webhook
     *
     * @param WP_Rest_Request $request Request object
     * @return bool|WP_Error True on success, WP_Error on failure
     */
    public function connect_with_fluentcrm( $request ) {
        $data = json_decode( $request->get_body(), true );

        // Validate request data
        if ( ! is_array( $data ) ) {
            return $this->error( __( 'Invalid request data.', 'booktics' ) );
        }

        if ( empty( $data['business_email'] ) ) {
            return $this->error( __( 'Business email is required.', 'booktics' ) );
        }

        $email = sanitize_email( $data['business_email'] );
        if ( ! is_email( $email ) ) {
            return $this->error( __( 'Invalid email address.', 'booktics' ) );
        }

        // Permission check: only allow users with 'manage_options'
        if ( ! current_user_can( 'manage_options' ) ) {
            return $this->error( __( 'You do not have permission to update settings.', 'booktics' ) );
        }

        // Verify email status using external API
        $isValidEmail = $this->verify_email_status( $email );

        
        if ( true !== $isValidEmail ) {
            return $this->error( __( 'Email address could not be verified as valid.', 'booktics' ) );
        }

        // Prepare webhook call
        $webhook_url = 'https://arraytics.com/?fluentcrm=1&route=contact&hash=785538fa-05ea-40ea-8762-02993eab4115';
        $body = [ 'email' => $email ];
        $webhook_response = wp_remote_post( $webhook_url, [ 'body' => $body ] );

        if ( is_wp_error( $webhook_response ) ) {
            if ( function_exists( 'error_log' ) && defined( 'WP_DEBUG_LOG' ) && WP_DEBUG_LOG ) {
                error_log( 'FluentCRM webhook error: ' . $webhook_response->get_error_message() ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
            }
            return $this->error( $webhook_response->get_error_message() );
        }

        return true;
    }

    /**
     * Verify email status
     *
     * @param string $email Email address
     * @return bool True if email is valid, false otherwise
     */
    public function verify_email_status(string $email = "")
	{
		$api_key = 'HGyNLSeQVNfcTpkMRfCJrECTjoEIfXPJ'; // Replace with your actual API key
		$url = 'https://emailverifier.reoon.com/api/v1/verify';
		
		$response = wp_remote_get(add_query_arg([
			'email' => $email,
			'key'   => $api_key,
			'mode'  => 'quick',
		], $url));
		
		if (is_wp_error($response)) {
			return 'error';
		}
		
		$body = wp_remote_retrieve_body($response);
		$data = json_decode($body, true);
		
		
		return isset($data['status']) && $data['status'] === "valid";
	}
}
