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

if (!class_exists('INTEGRAZO_WZ_Zoho_Books_Util')) {
    class INTEGRAZO_WZ_Zoho_Books_Util
    {
        /**
         * Send data to Zoho Inventory according to the mapped event.
         *
         * @param array $final_data     Flattened field map output: [ api_key => ['product_data_type' => '...', 'value' => mixed], ... ]
         * @param array $integration    Integration row with 'integration_data' JSON
         * @param array $account_details Account auth/config for INTEGRAZO_WZ_Zoho_Books
         * @return array                API response or standardized error
         */
        public function send_to_crm($final_data, $integration, $account_details)
        {
            try {
                // Instances
                if (class_exists('INTEGRAZO_WZ_Zoho_Books_Pro')) {
                    $product_instance = new INTEGRAZO_WZ_Zoho_Books_Pro($account_details);
                } else {
                    $product_instance = new INTEGRAZO_WZ_Zoho_Books($account_details);
                }
                $util     = new INTEGRAZO_WZ_Util();

                $main_record_fields = [];

                // Normalize values by data type
                if (is_array($final_data)) {
                    foreach ($final_data as $field_key => $field_info) {
                        if (!is_array($field_info) || !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');
                        }

                        $main_record_fields[$field_key] = $field_value;
                    }
                }

                // Decode integration settings
                $integration_config = json_decode($integration['integration_data'] ?? '[]', true);
                if (!is_array($integration_config)) {
                    $integration_config = [];
                }

                $event_name = $integration_config['integrazo_wz_product_event']  ?? '';
                $org_id     = $integration_config['integrazo_wz_product_orgid'] ?? '';

                if (empty($org_id)) {
                    return INTEGRAZO_WZ_Product_Util::create_error_response(
                        'MISSING_ORG_ID',
                        'Organization ID is required but missing in the integration settings.',
                        null
                    );
                }
                // Route to the correct Inventory API
                switch ($event_name) {
                    case 'create_contact':
                        $response = $product_instance->create_contact($org_id, $main_record_fields, true);
                        break;
                    case 'integrazo_wz_cm_update_contact':
                        $response = $product_instance->upsert_contact($org_id, $main_record_fields, true);
                        break;
                    case 'integrazo_wz_cm_create_item':

                        $response = $product_instance->create_item($org_id, $main_record_fields, true);
                        break;
                    case 'integrazo_wz_cm_update_item':
                        $response = $product_instance->upsert_item($org_id, $main_record_fields, true);
                        break;
                    case 'integrazo_wz_cm_create_inventory_adjustment':
                        $response = $product_instance->create_item_adjustment($org_id, $main_record_fields, true);
                        break;
                    case 'integrazo_wz_cm_create_sales_order':
                        $response = $product_instance->create_sales_order_basic($org_id, $main_record_fields, true);
                        break;
                    case 'integrazo_wz_cm_create_invoice':
                        $response = $product_instance->create_invoice_basic($org_id, $main_record_fields, true);
                        break;
                    default:
                        return INTEGRAZO_WZ_Product_Util::create_error_response(
                            'UNSUPPORTED_EVENT',
                            'The selected event is not supported or not configured.',
                            ['event' => $event_name]
                        );
                }
                // Bubble up SDK errors if present, otherwise return the API body
                return $response;
            } catch (\Throwable $e) {
                return INTEGRAZO_WZ_Product_Util::create_error_response(
                    'EXCEPTION_THROWN',
                    $e->getMessage(),
                    null
                );
            }
        }
    }
}
