<?php
// Exit if accessed directly.
if (!defined('ABSPATH')) {
    exit; // Prevent direct access to the file.
}

// Check if the class already exists to avoid redeclaration.
if (!class_exists('integrazo_fwcrm_form_API')) {
    class integrazo_fwcrm_form_API
    {
        private $api_key;
        private $instance_url;
        private $module_action = array("contacts" => "contact", "sales_accounts" => "sales_account");
        private $unique_identifier = array("contacts" => "emails", "sales_accounts" => "name");
        private $file_target = array("contacts" => "Contact", "sales_accounts" => "SalesAccount");

        public function __construct($instance_url = null, $api_key = null)
        {
            $this->instance_url = $instance_url ? rtrim($instance_url, '/') : null; // Set to null if not provided
            $this->api_key = $api_key; // Set to null if not provided
        }
        // Method to retrieve module_action for a specific module
        public function getModuleAction($module_name)
        {
            return $this->module_action[$module_name] ?? null;
        }
        private function create_error_response($error_code)
        {
            return [
                'data' => [
                    [
                        'status' => 'error',
                        'code' => $error_code,
                    ],
                ],
            ];
        }
        // Helper function to get headers
        private function get_headers()
        {
            return [
                'Authorization' => 'Token token=' . $this->api_key,
                'Content-Type' => 'application/json',
            ];
        }
        // Function to get fields of a specific module
        public function check_authentication($module_name)
        {
            try {
                $url = $this->instance_url . "/crm/sales/api/settings/" . urlencode($module_name) . "/fields";

                $response = wp_remote_get($url, [
                    'headers' => $this->get_headers(),
                    'timeout' => 60,
                ]);

                if (is_wp_error($response)) {
                    return ['error' => 'Connection failed: Unable to connect to the Freshworks CRM server. Please try again.'];
                }

                $status_code = wp_remote_retrieve_response_code($response);
                $body = json_decode(wp_remote_retrieve_body($response), true);

                return $body;
            } catch (Throwable $e) {
                return ['error' => 'Connection failed: Unable to connect to the Freshworks CRM server. Please try again.'];
            }
        }
        // Function to get fields of a specific module
        public function get_module_fields($module_name)
        {
            try {
                $url = $this->instance_url . "/crm/sales/api/settings/" . urlencode($module_name) . "/fields";

                $response = wp_remote_get($url, [
                    'headers' => $this->get_headers(),
                    'timeout' => 60,
                ]);

                if (is_wp_error($response)) {
                    return $this->create_error_response('NETWORK_ISSUE');
                }

                $status_code = wp_remote_retrieve_response_code($response);
                $body = json_decode(wp_remote_retrieve_body($response), true);

                return $body;
            } catch (Throwable $e) {
                return $this->create_error_response('INVALID_DATA');
            }
        }


        // Function to add a record to a specific module
        public function add_module_record($module_name, $record_data)
        {
            try {
                // $url = $this->instance_url . "/crm/suite/api/v1/" . urlencode($module_name);
                $url = $this->instance_url . "/crm/sales/api/" . urlencode($module_name);
                $temp = wp_json_encode([$this->module_action[$module_name] => $record_data]);
                $response = wp_remote_post($url, [
                    'headers' => $this->get_headers(),
                    'body' => $temp,
                    'timeout' => 60,
                ]);

                if (is_wp_error($response)) {
                    return $this->create_error_response('NETWORK_ISSUE');
                }

                $status_code = wp_remote_retrieve_response_code($response);
                $body = json_decode(wp_remote_retrieve_body($response), true);
                // Ensure the body is valid and has required keys
                return $body;
            } catch (Throwable $e) {
                return $this->create_error_response('INVALID_DATA');
            }
        }

        public function upsert_module_record($module_name, $record_data)
        {
            try {
                // Construct the API URL
                $url = $this->instance_url . "/crm/sales/api/" . urlencode($module_name) . '/upsert';
                // Prepare the body with unique_identifier and module data
                $body_data = [
                    'unique_identifier' => [
                        $this->unique_identifier[$module_name] => $record_data[$this->unique_identifier[$module_name]]
                    ],
                    $this->module_action[$module_name] => $record_data
                ];
                $body = wp_json_encode($body_data);

                // Send the POST request
                $response = wp_remote_post($url, [
                    'headers' => $this->get_headers(),
                    'body' => $body,
                    'timeout' => 60,
                ]);

                if (is_wp_error($response)) {
                    return $this->create_error_response('NETWORK_ISSUE');
                }

                $status_code = wp_remote_retrieve_response_code($response);
                $body = json_decode(wp_remote_retrieve_body($response), true);
                return $body;
            } catch (Throwable $e) {
                return $this->create_error_response('INVALID_DATA');
            }
        }

        // Function to get account details by ID
        public function get_account_id($s_tag)
        {
            try {
                // Construct the URL with query parameters
                $url = $this->instance_url . "/crm/sales/api/search?" . http_build_query(array(
                    'q'        => sanitize_text_field($s_tag),
                    'include'  => 'sales_account',
                    'per_page' => 25,
                ));

                // Send the GET request
                $response = wp_remote_get($url, [
                    'headers' => $this->get_headers(),
                    'timeout' => 60,
                ]);

                // Handle errors
                if (is_wp_error($response)) {
                    return null;
                }

                // Retrieve the status code and body
                $status_code = wp_remote_retrieve_response_code($response);
                $body = json_decode(wp_remote_retrieve_body($response), true);

                // Validate and iterate over the data
                if (is_array($body)) {
                    foreach ($body as $record) {
                        if (isset($record['name']) && strtolower(trim($record['name'])) === strtolower(trim($s_tag))) {
                            return sanitize_text_field($record['id']);
                        }
                    }
                }

                // Return an error if no match is found or data is invalid
                return null;
            } catch (Throwable $e) {
                return null;
            }
        }
        public function attach_file_to_fw($file_path, $record_id, $module_name)
        {

            try {
                $target_module = $this->file_target[$module_name];
                global $wp_filesystem;

                if (!function_exists('WP_Filesystem')) {
                    require_once(ABSPATH . 'wp-admin/includes/file.php');
                }
                WP_Filesystem();

                $url = $this->instance_url . '/crm/sales/api/documents';

                $file_content = $wp_filesystem->get_contents($file_path);
                $boundary = wp_generate_password(24);

                // Create multipart body
                $body = '';
                $body .= "--$boundary\r\n";
                $body .= 'Content-Disposition: form-data; name="file"; filename="' . basename($file_path) . '"' . "\r\n";
                $body .= 'Content-Type: ' . mime_content_type($file_path) . "\r\n\r\n";
                $body .= $file_content . "\r\n";
                $body .= "--$boundary\r\n";
                $body .= 'Content-Disposition: form-data; name="file_name"' . "\r\n\r\n";
                $body .= basename($file_path) . "\r\n";
                $body .= "--$boundary\r\n";
                $body .= 'Content-Disposition: form-data; name="is_shared"' . "\r\n\r\n";
                $body .= "true\r\n";
                $body .= "--$boundary\r\n";
                $body .= 'Content-Disposition: form-data; name="targetable_id"' . "\r\n\r\n";
                $body .= sanitize_text_field($record_id) . "\r\n";
                $body .= "--$boundary\r\n";
                $body .= 'Content-Disposition: form-data; name="targetable_type"' . "\r\n\r\n";
                $body .= $target_module . "\r\n"; // Ensure correct value
                $body .= "--$boundary--\r\n";

                $headers = [
                    'Authorization' => 'Token token=' . $this->api_key,
                    'Content-Type'  => 'multipart/form-data; boundary=' . $boundary,
                ];

                $response = wp_remote_post($url, [
                    'headers' => $headers,
                    'body'    => $body,
                    'timeout' => 60,
                ]);

                if (is_wp_error($response)) {
                    return null;
                }

                $status_code = wp_remote_retrieve_response_code($response);
                $response_body = json_decode(wp_remote_retrieve_body($response), true);

                return $response_body;
            } catch (Throwable $e) {
                return null;
            }
        }
    }
    $integrazo_fwcrm_form_api_Instance = new integrazo_fwcrm_form_API();
}
