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

if (!class_exists('INTEGRAZO_WZ_Zoho_Desk_Util')) {
    class INTEGRAZO_WZ_Zoho_Desk_Util
    {
        public function send_to_crm($final_data, $integration, $account_details)
        {
            try {
                $desk = new INTEGRAZO_WZ_Zoho_Desk($account_details);
                $util = new INTEGRAZO_WZ_Util();

                $main_record_fields = [];

                // Normalize values
                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 ($data_type === 'Date') {
                        $field_value = $util->formatDate($field_value, 'Y-m-d');
                    } elseif ($data_type === 'DateTime') {
                        $field_value = $util->formatDate($field_value, 'Y-m-d\TH:i:s.000\Z');
                    } elseif ($data_type === 'Multiselect') {
                        try {
                            if (is_array($field_value)) {
                                // If it's already an array, trim and join with commas
                                $field_value = implode(',', array_map('trim', $field_value));
                            } else {
                                // If it's a string, split by common separators and rejoin with commas
                                $items = preg_split('/[,|;:]+/', (string)$field_value);
                                $items = array_map('trim', $items);
                                $items = array_filter($items, fn($v) => $v !== '');
                                $field_value = implode(',', $items);
                            }
                        } catch (\Throwable $e) {
                            // If anything fails, set empty string
                            $field_value = '';
                        }
                    } elseif (is_array($field_value)) {
                        $field_value = implode(', ', $field_value);
                    }

                    $main_record_fields[$field_key] = $field_value;
                }

                // Decode integration settings
                $integration_config = json_decode($integration['integration_data'] ?? '[]', true);
                $department_id = $integration_config['integrazo_wz_department_id'] ?? '';

                if (empty($department_id)) {
                    return INTEGRAZO_WZ_Product_Util::create_error_response(
                        'DEPARTMENT_ID_MISSING',
                        'Zoho Desk department is not selected.'
                    );
                }

                // Create ticket
                $response = $desk->add_desk_ticket_with_contact($department_id, $main_record_fields, true);
                // If SDK already returned a structured error, bubble it up
                return $response;
            } catch (Throwable $e) {
                return INTEGRAZO_WZ_Product_Util::create_error_response(
                    'EXCEPTION_THROWN',
                    $e->getMessage(),
                    null
                );
            }
        }
    }
}
