<?php

/**
 * Plugin Name: brainX Form Connector
 * Description: Plugin zum Verbinden des brainX CRM mit Ninja Forms und Formidable
 * Version: 1.0.2
 * Author: Brainformatik GmbH
 * Author URI: https://www.brainformatik.com
 * Text Domain: brainx-form-connector
 * License: GPLv2 or later
 * License URI: https://www.gnu.org/licenses/gpl-2.0.html
 * Requires at least: 6.0
 * Tested up to: 6.9
 * Requires PHP: 7.4
 */
// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit;
}

// Plugin-Version definieren
define('BRAINX_API_CONNECTOR_VERSION', '1.0.0');

if (!defined('BRAINX_CRM_PLUGIN_URL')) {
    define('BRAINX_CRM_PLUGIN_URL', plugin_dir_url(__FILE__));
}

if (!defined('BRAINX_CRM_PLUGIN_DIR')) {
    define('BRAINX_CRM_PLUGIN_DIR', plugin_dir_path(__FILE__));
}


include BRAINX_CRM_PLUGIN_DIR . 'admin/brainx-form-connector-admin.php';
include BRAINX_CRM_PLUGIN_DIR . 'front/brainx-form-connector-front.php';

register_activation_hook(__FILE__, 'brainx_create_api_responses_table');

if (!function_exists('brainx_load_admin_custom_styles')) {

    function brainx_load_admin_custom_styles() {
        wp_enqueue_style('brainxAdmin-style', plugin_dir_url(__FILE__) . 'assets/admin-style.css');
    }

}
add_action('admin_enqueue_scripts', 'brainx_load_admin_custom_styles');

/**
 * Create the brainx_api_responses table on plugin activation.
 */
if (!function_exists('brainx_create_api_responses_table')) {

    function brainx_create_api_responses_table() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'brainx_api_responses';
        $charset_collate = $wpdb->get_charset_collate();
        $sql = "CREATE TABLE $table_name (
        id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        form_id INT(11) NOT NULL,
        entry_id INT(11) NOT NULL,
        form_type VARCHAR(50) NOT NULL,
        status VARCHAR(20) NOT NULL,
        response_got LONGTEXT NOT NULL,
        message LONGTEXT NOT NULL,
        date VARCHAR(50) NOT NULL,
        PRIMARY KEY (id)
    ) $charset_collate;";

        $table_name_logs = $wpdb->prefix . 'brainx_api_form_updates_logs';
        $sql_logs = "CREATE TABLE $table_name_logs (
        id BIGINT(20) UNSIGNED NOT NULL AUTO_INCREMENT,
        user_id INT(11) NOT NULL,
        form_id INT(11) NOT NULL,
        form_type VARCHAR(50) NOT NULL,
        event VARCHAR(255) NOT NULL,
        datetime DATETIME NOT NULL,
        PRIMARY KEY (id)
    ) $charset_collate;";

        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
        dbDelta($sql_logs);
    }

}

if (!function_exists('brainx_get_assigned_company_ids')) {

    function brainx_get_assigned_company_ids() {
        $brainx_res = array();
        $brainx_accessToken = brainxGetApiToken();
        $brainx_settings = get_option('_brainx_api_creds_settings');
        $brainx_server_url = rtrim(isset($brainx_settings['server_url']) ? $brainx_settings['server_url'] : '', '/');

        $brainx_url = $brainx_server_url . "/api/users/companies";

        $brainx_response = wp_remote_get($brainx_url, array(
            'headers' => array(
                'Authorization' => "Bearer $brainx_accessToken",
                'Content-Type' => 'application/json',
            )
        ));

        if (is_wp_error($brainx_response)) {
            return $brainx_res;
        }

        $data = json_decode(wp_remote_retrieve_body($brainx_response), true);
        if (isset($data['data'])) {
            $brainx_res = $data['data'];
        }
        return $brainx_res;
    }

}

if (!function_exists('brainxGetApiToken')) {

    function brainxGetApiToken() {
        $brainx_accessToken = '';
        $brainx_settings = get_option('_brainx_api_creds_settings');

        if (!empty($brainx_settings)) {
            $brainx_server_url = isset($brainx_settings['server_url']) ? $brainx_settings['server_url'] : '';
            $brainx_server_username = isset($brainx_settings['server_username']) ? $brainx_settings['server_username'] : '';
            $brainx_server_pass = isset($brainx_settings['server_password']) ? $brainx_settings['server_password'] : '';
            $brainx_two_factor = isset($brainx_settings['brainx_two_factor']) ? $brainx_settings['brainx_two_factor'] : '';
            $brainxapp_pass = isset($brainx_settings['brainxapp_pass']) ? $brainx_settings['brainxapp_pass'] : '';
            if (empty($brainx_server_url)) {
                return '';
            }
            if (substr($brainx_server_url, -1) === '/') {
                $brainx_server_url = rtrim($brainx_server_url, '/');
            }
            $brainx_server_url = $brainx_server_url . '/api/auth';
            // Prepare the request body
            if ($brainx_two_factor == 'on') {
                $body = wp_json_encode([
                    'user' => $brainx_server_username,
                    'password' => '',
                    'apiPassword' => $brainxapp_pass,
                ]);
            } else {
                $body = wp_json_encode([
                    "user" => $brainx_server_username,
                    "password" => $brainx_server_pass,
                ]);
            }

            // Send the request using wp_remote_post
            $brainx_response = wp_remote_post($brainx_server_url, [
                'method' => 'POST',
                'body' => $body,
                'headers' => [
                    'Content-Type' => 'application/json',
                ],
                'timeout' => 10,
            ]);
            // Check if the response has an error
            if (is_wp_error($brainx_response)) {
                return $brainx_accessToken;
            }

            // Decode the response
            $brainx_response_body = wp_remote_retrieve_body($brainx_response);
            $brainx_response_data = json_decode($brainx_response_body, true);
            // Debugging the response
            // Check for the access token in the response
            if (isset($brainx_response_data['data']['accessToken'])) {
                $brainx_accessToken = $brainx_response_data['data']['accessToken'];
            }
        }

        return $brainx_accessToken;
    }

}
if (!function_exists('BrainxGetFields')) {

    function BrainxGetFields($brainx_accessToken, $brainx_entityId) {
        $brainx_fields = array();
        $brainx_settings = get_option('_brainx_api_creds_settings');
        $brainx_server_url = rtrim(isset($brainx_settings['server_url']) ? $brainx_settings['server_url'] : '', '/');
        if (empty($brainx_entityId) || $brainx_entityId === 0) {
            $brainx_entityId = isset($brainx_settings['entity_id']) ? $brainx_settings['entity_id'] : '';
        }
        $brainx_url = $brainx_server_url . "/api/metadata/entities/$brainx_entityId";

        $brainx_response = wp_remote_get($brainx_url, array(
            'headers' => array(
                'Authorization' => "Bearer $brainx_accessToken",
                'Content-Type' => 'application/json',
            )
        ));

        if (is_wp_error($brainx_response)) {
            return $brainx_fields;
        }

        $data = json_decode(wp_remote_retrieve_body($brainx_response), true);
        if (!empty($data) && isset($data['data'])) {
            $brainx_fields = isset($data['data']['fields']) ? $data['data']['fields'] : '';
        }

        return $brainx_fields;
    }

}
if (!function_exists('brainx_get_ninja_form_option_by_id')) {

    function brainx_get_ninja_form_option_by_id($brainx_id) {
        global $wpdb;

        $brainx_results = $wpdb->get_var(
                $wpdb->prepare(
                        "SELECT value FROM {$wpdb->prefix}nf3_field_meta WHERE parent_id = %d AND meta_key = %s",
                        $brainx_id,
                        'options'
                )
        );

        return $brainx_results;
    }

}

add_action('wp_ajax_brainx_api_connection_check', 'brainx_api_connection_check');

if (!function_exists('brainx_api_connection_check')) {

    function brainx_api_connection_check() {
        // Check nonce for security
        if (!isset($_POST['nonce']) || !check_ajax_referer('brainx-ninja-nonce', 'nonce', false)) {
            echo wp_json_encode(array('status' => 0, 'message' => __('Die Nonce-Überprüfung ist fehlgeschlagen', 'brainx-form-connector')));
            die();
        }

        // Sanitize input data
        $brainx_server_url = '';
        if (isset($_POST['server_url'])) {
            $brainx_server_url = sanitize_text_field(wp_unslash($_POST['server_url']));
            $brainx_server_url = trim($brainx_server_url);
            $brainx_server_url = esc_url_raw($brainx_server_url);
        }
        $brainx_server_username = isset($_POST['server_username']) ? sanitize_text_field(wp_unslash($_POST['server_username'])) : '';
        $brainx_server_pass = isset($_POST['server_password']) ? sanitize_text_field(wp_unslash($_POST['server_password'])) : '';
        $brainxapp_pass = isset($_POST['brainxapp_pass']) ? sanitize_text_field(wp_unslash($_POST['brainxapp_pass'])) : '';

        // Validate required fields
        // Ensure server URL does not end with a slash
        $brainx_server_url = rtrim($brainx_server_url, '/') . '/api/auth';

        // Prepare the request body
        if (!empty($brainxapp_pass)) {
            $body = wp_json_encode([
                'user' => $brainx_server_username,
                'password' => '',
                'apiPassword' => $brainxapp_pass,
            ]);
        } else {
            $body = wp_json_encode([
                'user' => $brainx_server_username,
                'password' => $brainx_server_pass
            ]);
        }
        // Send the request using wp_remote_post
        $brainx_response = wp_remote_post($brainx_server_url, [
            'method' => 'POST',
            'body' => $body,
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'timeout' => 10,
        ]);

        // Check for errors in the response
        if (is_wp_error($brainx_response)) {
            echo wp_json_encode(array('status' => 0, 'message' => $brainx_response->get_error_message()));
            die();
        }

        $brainx_response_code = wp_remote_retrieve_response_code($brainx_response);
        $brainx_response_body = wp_remote_retrieve_body($brainx_response);

        // Return the response with the appropriate HTTP code
        if ($brainx_response_code === 200) {
            echo wp_json_encode(array('status' => 1, 'message' => 'Success'));
            die();
        } else {
            echo wp_json_encode(array('status' => 0, 'message' => __('Fehler: 2FA-Passwort prüfen', 'brainx-form-connector')));
        }
        die();
    }

}

add_filter('wp_kses_allowed_html', function ($tags, $context) {
    if (!is_admin()) {
        return $tags;
    }
    $action = isset($_POST['action']) ? $_POST['action'] : '';
    if ($context === 'post' && $action == 'brainx_load_field_mapping') {
        $tags['select'] = [
            'name' => true,
            'id' => true,
            'class' => true,
            'multiple' => true,
            'required' => true,
        ];
        $tags['option'] = [
            'value' => true,
            'selected' => true,
        ];
    }
    return $tags;
}, 10, 2);
