<?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_WZ_Zoho_CRM_Util')) {
    class INTEGRAZO_WZ_Zoho_CRM_Util
    {
        public function send_to_crm($final_data, $integration, $account_details)
        {
            try {
                if (class_exists('INTEGRAZO_WZ_Zoho_CRM_Pro')) {
                    $instance = new INTEGRAZO_WZ_Zoho_CRM_Pro($account_details);
                } else {
                    $instance = new INTEGRAZO_WZ_Zoho_CRM($account_details);
                }
                $session = integrazo_wz_session();
                // Initialize arrays to categorize input data
                $attachments = [];
                $additional_data = [];
                $uploaded_files = [];
                $profile_images = [];
                $main_record_fields = [];

                // Create util instance once
                $util = new INTEGRAZO_WZ_Util();

                // Categorize each CRM field based on its data type and key name
                foreach ($final_data as $field_key => $field_info) {
                    if (!isset($field_info['product_data_type'])) {
                        continue;
                    }

                    $data_type   = $field_info['product_data_type'];
                    $field_value = $field_info['value'];

                    if (strpos($field_key, 'integrazo_wz_additional_attachment') !== false) {
                        $attachments[] = $field_value;
                    } elseif (strpos($field_key, 'integrazo_wz_additional_') !== false) {
                        $additional_data[$field_key] = $field_value;
                    } elseif ($data_type === 'fileupload') {
                        // Remove custom field prefix if present
                        $normalized_key = $util->normalizeFieldKey($field_key);
                        $uploaded_files[$normalized_key] = $field_value;
                    } elseif ($data_type === 'profileimage') {
                        $profile_images[$field_key] = $field_value;
                    } else {
                        if ($data_type === 'boolean') {
                            $field_value = $util->is_acceptance_true($field_value);
                        } elseif ($data_type === 'multiselectpicklist') {
                            $field_value = $util->normalizeMultiSelect($field_value);
                        } elseif ($data_type === 'date') {
                            $field_value = $util->formatDate($field_value);
                        } elseif ($data_type === 'datetime') {
                            $field_value = $util->formatDateTime($field_value);
                        } else {
                            if (is_array($field_value)) {
                                $field_value = implode(', ', $field_value);
                            }
                        }

                        // Remove custom field prefix if present
                        $normalized_key = $util->normalizeFieldKey($field_key);
                        $main_record_fields[$normalized_key] = $field_value;
                    }
                }

                // Decode integration settings
                $integration_config = json_decode($integration['integration_data'], true);
                $module_id = $integration_config['integrazo_wz_module'];
                // Remove custom module prefix if present
                $module_id = $util->normalizeModuleId($module_id);

                $record_action = $integration['record_action'];

                // Insert or update main record
                if ($record_action === "add_or_update" && method_exists($instance, 'upsert_module_record') && $session) {
                    $response = $instance->upsert_module_record($module_id, $main_record_fields, [], true);
                } else {
                    $response = $instance->add_module_record($module_id, $main_record_fields, true);
                }

                // Process additional actions if record ID is returned
                $record_id = $response['data'][0]['details']['id'] ?? null;

                if (!isset($response['data'])) {
                    return $response;
                }

                // Add note if available
                if (!empty($additional_data['integrazo_wz_additional_note']) && method_exists($instance, 'add_note_to_record') && $session) {
                    $instance->add_note_to_record($module_id, $record_id, $additional_data['integrazo_wz_additional_note'], true);
                }

                // Add tags if available
                if (!empty($additional_data['integrazo_wz_additional_tag'])  && method_exists($instance, 'add_record_tag') && $session) {
                    $instance->add_record_tag($module_id, $record_id, $additional_data['integrazo_wz_additional_tag'], true);
                }

                // Upload attachments
                if (!empty($attachments) && method_exists($instance, 'upload_attachment') && $session) {
                    foreach ($attachments as $attachment_group) {
                        if (is_array($attachment_group)) {
                            foreach ($attachment_group as $attachment) {
                                $instance->upload_attachment($module_id, $record_id, $attachment, true);
                            }
                        }
                    }
                }

                // Upload profile images
                if (!empty($profile_images) && method_exists($instance, 'upload_record_image') && $session) {
                    foreach ($profile_images as $image_key => $image_files) {
                        if (is_array($image_files)) {
                            foreach ($image_files as $image_file) {
                                $instance->upload_record_image($module_id, $record_id, $image_file, true);
                            }
                        }
                    }
                }

                // Upload and map additional files
                if (!empty($uploaded_files)  && method_exists($instance, 'upload_and_map_file') && $session) {
                    foreach ($uploaded_files as $f_key => $file_group) {
                        if (is_array($file_group)) {
                            foreach ($file_group as $file) {
                                $instance->upload_and_map_file($module_id, $record_id, $f_key, $file, true);
                            }
                        }
                    }
                }

                $code = $response["data"][0]["code"] ?? 'INVALID_RESPONSE';
                $message = $response["data"][0]["message"] ?? '-';
                return INTEGRAZO_WZ_Product_Util::create_error_response($code, $message, $response);
            } catch (Throwable $e) {
                return INTEGRAZO_WZ_Product_Util::create_error_response('EXCEPTION_THROWN', $e->getMessage(), null);
            }
        }
    }
}
