<?php

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}
if (!class_exists('INTEGRAZO_WZ_NinjaForms_Helper')) {
    class INTEGRAZO_WZ_NinjaForms_Helper
    {
        /**
         * Get all Ninja Forms with ID and title.
         *
         * @return array|string
         */
        public static function get_all_forms()
        {
            $validation = self::validate_ninjaforms_plugin();
            if (is_string($validation)) {
                return $validation;
            }

            $forms = Ninja_Forms()->form()->get_forms();

            if (empty($forms)) {
                return 'No Ninja Forms found. Please create at least one form to continue.';
            }

            $data = [];
            foreach ($forms as $form) {
                $data[] = [
                    'id'    => (int) $form->get_id(),
                    'title' => $form->get_setting('title'),
                ];
            }

            return $data;
        }

        /**
         * Get all supported fields for a specific Ninja Form.
         *
         * @param int $form_id
         * @return array|string
         */
        public static function get_form_fields($form_id)
        {
            $validation = self::validate_form_plugin_and_id($form_id);
            if (is_string($validation)) {
                return $validation;
            }

            $form = Ninja_Forms()->form($form_id);

            $fields_collection = $form->get_fields();

            $fields = [];
            foreach ($fields_collection as $field) {
                $type = $field->get_setting('type');

                if (in_array($type, ['html', 'submit', 'hr', 'repeater', 'recaptcha', ''], true)) {
                    continue; // Skip display-only, submit button, and divider fields
                }

                $field_id = $field->get_id();
                $label = $field->get_setting('label');

                $fields[] = [
                    'name'       => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($field_id, $label),
                    'type'       => $type,
                    'label'      => $label,
                    'identifier' => INTEGRAZO_WZ_Identifier_Util::build_field_identifier($field_id, $label),
                ];
            }

            if (empty($fields)) {
                return 'This Ninja Form does not contain any fields. Please edit the form and add at least one input field.';
            }
            return $fields;
        }

        /**
         * Validate that the Ninja Forms plugin is active.
         *
         * @return true|string
         */
        private static function validate_ninjaforms_plugin()
        {
            if (!function_exists('Ninja_Forms')) {
                return 'Ninja Forms plugin is not installed or activated. Please install and activate Ninja Forms to continue.';
            }
            return true;
        }

        /**
         * Validate the form plugin and form ID.
         *
         * @param int $form_id
         * @return true|string
         */
        private static function validate_form_plugin_and_id($form_id)
        {

            $form = Ninja_Forms()->form($form_id);

            if (!$form || empty($form->get_fields())) {
                return 'The mapped Ninja Form was not found. It may have been deleted or is unavailable. Please select another form to continue.';
            }

            return true;
        }
        public static function capture_submission($form_data)
        {
            try {
                // Get form ID
                $form_id = $form_data['form_id'];

                // Get submitted fields
                $fields = $form_data['fields'];
                $cleaned_data = [];

                // Loop through all fields
                foreach ($fields as $field) {

                    $field_type = $field['settings']['type'] ?? '';
                    if (in_array($field_type, ['html', 'submit', 'hr', 'repeater', 'recaptcha', ''], true)) {
                        continue; // Skip display-only, submit button, and divider fields
                    }

                    $field_id = $field['settings']['id'] ?? '';
                    $field_label = $field['settings']['label'] ?? '';
                    $identifier = INTEGRAZO_WZ_Identifier_Util::build_field_identifier($field_id, $field_label);

                    $value = $field['value'];

                    if ($field_type === 'date') {
                        if (is_array($value)) {
                            $date_raw = $value['date'];
                            if (!empty($date_raw)) {
                                $hour = (int)($value['hour'] ?? 0);
                                $minute = (int)($value['minute'] ?? 0);
                                $ampm = strtolower($value['ampm'] ?? '');

                                // Adjust hour based on AM/PM
                                if ($ampm === 'pm' && $hour < 12) {
                                    $hour += 12;
                                } elseif ($ampm === 'am' && $hour === 12) {
                                    $hour = 0;
                                }

                                $timestamp = strtotime($date_raw);
                                if ($timestamp) {
                                    $date_part = gmdate('Y-m-d', $timestamp);
                                    $value = sprintf('%s %02d:%02d:00', $date_part, $hour, $minute);
                                }
                            } else {
                                $value = null;
                            }
                        }
                    } else if ($field_type === 'file') {
                        // if (is_array($value)) {
                        //     foreach ($field['value'] as $fileIndex => $fileName) {
                        //         $entry[$field['id']] = array_column($field['value'], null);
                        //     }
                        // } else {
                        //     $entry[$field['id']] = $field['value'];
                        // }
                    }
                    $cleaned_data[$identifier] = $value;
                }


                // Process the data further
                INTEGRAZO_WZ_Form_Hooks::process_submission($form_id, $cleaned_data, "ninja_forms");
            } catch (Throwable $e) {
            }
        }
    }
}

// ✅ Safe hook, only if class exists
if (class_exists('INTEGRAZO_WZ_NinjaForms_Helper')) {
    add_action('ninja_forms_after_submission', ['INTEGRAZO_WZ_NinjaForms_Helper', 'capture_submission'], 10, 1);
}
