<?php

namespace Tablesome\Workflow_Library\Triggers;

use Tablesome\Includes\Modules\Workflow\Abstract_Trigger;

if (!defined('ABSPATH')) {
    exit;
} // Exit if accessed directly

if (!class_exists('\Tablesome\Workflow_Library\Triggers\Forminator')) {
    class Forminator extends Abstract_Trigger
    {

        public $trigger_source_id = 0;
        public $trigger_source_data = array();

        public $unsupported_formats = array(
            // 'stripe',
            // 'paypal',
            'captcha',
        );

        public $signature_field_types = array(
            'signature',
            'e_signature',
            'esignature',
        );

        public static $instance = null;

        public static function get_instance()
        {
            if (is_null(self::$instance)) {
                self::$instance = new self();
            }
            return self::$instance;
        }

        public function get_config()
        {
            $is_active = class_exists('Forminator') ? true : false;
            return array(
                'integration' => 'forminator',
                'integration_label' => __('Forminator', 'tablesome'),
                'trigger' => 'tablesome_forminator_form_submit',
                'trigger_id' => 4,
                'trigger_label' => __('On Form Submit', 'tablesome'),
                'trigger_type' => 'forms',
                'is_active' => $is_active,
                'is_premium' => "no",
                'hooks' => array(
                    array(
                        'priority' => 10,
                        'accepted_args' => 3,
                        'name' => 'forminator_custom_form_submit_before_set_fields',
                        'callback_name' => 'trigger_callback',
                    ),
                ),
                'supported_actions' => [],
                'unsupported_actions' => [8, 9]
            );
        }

        public function trigger_callback($entry, $form_id, $fields_data)
        {
            $entry_id = $entry->entry_id;

            $form = \Forminator_API::get_form($form_id);

            $submission_data = $this->get_formatted_posted_data($fields_data, $form);
            $submission_data = apply_filters("tablesome_form_submission_data", $submission_data, $form_id);

            $this->trigger_source_id = $form_id;
            $this->trigger_source_data = array(
                'integration' => $this->get_config()['integration'],
                'form_title' => isset($form->settings['formName']) ? $form->settings['formName'] : 'Untitled Table - ' . $form_id,
                'form_id' => $form_id,
                'data' => $submission_data,
            );

            $this->run_triggers($this, $this->trigger_source_data);
        }

        public function conditions($trigger_meta, $trigger_data)
        {
            $integration = isset($trigger_meta['integration']) ? $trigger_meta['integration'] : '';
            $trigger_id = isset($trigger_meta['trigger_id']) ? $trigger_meta['trigger_id'] : '';

            if ($integration != $this->get_config()['integration'] || $trigger_id != $this->get_config()['trigger_id']) {
                return false;
            }

            $trigger_source_id = isset($trigger_meta['form_id']) ? $trigger_meta['form_id'] : 0;
            if (isset($trigger_data['form_id']) && $trigger_data['form_id'] == $trigger_source_id) {
                return true;
            }
            return false;
        }

        public function get_collection()
        {
            $posts = $this->get_posts();
            if (empty($posts)) {
                return [];
            }

            foreach ($posts as $index => $post) {
                $posts[$index]['fields'] = $this->get_post_fields($post['id']);
            }
            return $posts;
        }

        public function get_posts()
        {
            if (!class_exists('Forminator')) {
                return [];
            }

            $forms = \Forminator_API::get_forms(null, 1, -1, '');

            if (is_wp_error($forms) || empty($forms)) {
                return [];
            }
            $posts = [];
            foreach ($forms as $form) {
                $posts[] = array(
                    'id' => $form->id,
                    'label' => $form->settings['formName'] . " (ID: " . $form->id . ")",
                    'integration_type' => 'forminator',
                );
            }
            return $posts;

        }

        public function get_post_fields($id, $args = array())
        {
            if (!class_exists('Forminator')) {
                return [];
            }
            $fields = \Forminator_API::get_form_fields($id);
            if (is_wp_error($fields) || empty($fields)) {
                return [];
            }

            $form_fields = array();

            foreach ($fields as $field_obj) {

                $type = $field_obj->__get('type');
                $id = $field_obj->__get('element_id');
                $label = $field_obj->__get('field_label');
                
                if (in_array($type, $this->unsupported_formats)) {
                    continue;
                }

                $field = array(
                    'id' => $id,
                    'label' => !empty($label) ? $label : $id,
                    'field_type' => $type,
                );

                $options = $field_obj->__get('options');

                if (!empty($options)) {

                    $options = (array_map(function ($option) {
                        $return_data = $option;
                        $return_data['id'] = $return_data['value'];
                        return $return_data;
                    }, $options));

                    $field['options'] = $options;
                }
                $form_fields[] = $field;
            }

            $form_fields = $this->post_processing_fields($form_fields);
            
            return $form_fields;
        }

        public function get_formatted_posted_data($fields_data, $form_obj)
        {
            $data = array();

            // Gettings other paypal fields

            foreach ($fields_data as $field_data) {
                $name = $field_data['name'];
                $additional_data = [];
                $unix_timestamp = ''; // Reset for each field

                if (in_array($name, ['_forminator_user_ip'])) {
                    continue;
                }

                $field = \Forminator_API::get_form_field($form_obj->id, $name, true);

                if (is_wp_error($field)) {
                    continue;
                }

                $type = $field['type'];

                if (in_array($type, $this->unsupported_formats)) {
                    continue;
                }

                if ($type == 'paypal') {
                    $value = isset($field_data['value']) && isset($field_data['value']['status']) ? $field_data['value']['status'] : '';
                    $additional_data = isset($field_data['value']) && isset($field_data['value']) ? $field_data['value'] : [];
                } else {
                    $value = isset($field_data['value']) ? $field_data['value'] : '';
                }

                if ($type == 'date') {
                    $incoming_date_format = $field_data['field_array']['date_format'];
                    // Note: Special Conversion for Forminator Date Field
                    $incoming_date_format = str_replace("dd", "d", $incoming_date_format);
                    $incoming_date_format = str_replace("mm", "m", $incoming_date_format);
                    $incoming_date_format = str_replace("yy", "Y", $incoming_date_format);

                    // Handle multi-part date fields (year/month/day posted as array)
                    if (is_array($value)) {
                        $year = isset($value['year']) ? $value['year'] : '';
                        $month = isset($value['month']) ? str_pad($value['month'], 2, '0', STR_PAD_LEFT) : '';
                        $day = isset($value['day']) ? str_pad($value['day'], 2, '0', STR_PAD_LEFT) : '';
                        
                        if (!empty($year) && !empty($month) && !empty($day)) {
                            // Convert multi-part date array to Y-m-d format (consistent storage format)
                            // This ensures all dates are stored consistently in Tablesome
                            $value = sprintf('%s-%s-%s', $year, $month, $day);
                            $incoming_date_format = 'Y-m-d';
                        } else {
                            // Invalid multi-part date, skip timestamp conversion
                            $value = '';
                        }
                    }

                    if (!empty($value)) {
                        $unix_timestamp = (int) convert_tablesome_date_to_unix_timestamp($value, $incoming_date_format);
                        $unix_timestamp = $unix_timestamp * 1000; // convert to milliseconds
                    }

                } else if ($type == 'postdata') {
                    /** Get the Post ID */
                    $value = isset($value['postdata']) ? $value['postdata'] : 0;
                } else if ($type == 'file') {
                    $attachment_id = isset($value['file']) ? $value['file'] : '';
                    $value = $attachment_id;

                } else if ($type == 'upload') {
                    $file = isset($value['file']) ? $value['file'] : '';

                    // error_log(' Forminator file : ' . print_r($file, true));

                    $value = '';
                    $file_url = '';
                    if (isset($file['success']) && $file['success'] == 1 && isset($file['file_url'])) {
                        $file_url = is_array($file['file_url']) ? implode(',', $file['file_url']) : $file['file_url'];

                        // Set the value to the file URL for proper integration with Notion and other actions
                        $value = $file_url;
                        $file_type = wp_check_filetype($file_url);

                        // error_log(' Forminator url : ' . $file_url);
                        // error_log(' Forminator value : ' . $value);
                    }
                } else if (in_array($type, $this->signature_field_types)) {
                    // Signature fields may arrive as nested arrays (same structure
                    // as uploads), base64 data URIs, or plain URL strings.
                    if (is_array($value)) {
                        if (isset($value['file']['file_url'])) {
                            $value = $value['file']['file_url'];
                        } elseif (isset($value['file']) && is_string($value['file'])) {
                            $value = $value['file'];
                        } elseif (isset($value['url'])) {
                            $value = $value['url'];
                        } elseif (isset($value['file_url'])) {
                            $value = $value['file_url'];
                        } else {
                            $value = '';
                        }
                    }
                    // Convert base64 data URIs to saved files
                    if (is_string($value) && strpos($value, 'data:image') === 0) {
                        $saved_url = $this->save_base64_signature_to_file($value);
                        if ($saved_url) {
                            $value = $saved_url;
                        }
                    }
                } else {
                    if (is_array($value) && !empty($value)) {
                        if ($type == 'time') {
                            $value = sprintf('%02d', $value['hours']) . ':' . sprintf('%02d', $value['minutes']) . ' ' . $value['ampm'];
                        } else if ($type == 'calculation') {
                            $value = isset($value['result']) ? $value['result'] : '';
                        } else if ($type == 'name') {
                            $value = implode(' ', $value);
                        } else {
                            $value = implode(', ', $value);
                        }
                    }
                }

                $data[$name] = array(
                    'type' => $type,
                    'label' => isset($field['field_label']) && !empty($field['field_label']) ? $field['field_label'] : $name,
                    'value' => $value ?? '',
                    'unix_timestamp' => $unix_timestamp, // use this prop when the column format type is date
                    'additional_data' => $additional_data,
                );

                if ($type == 'upload') {
                    $data[$name]['file_type'] = isset($file_type) ? $file_type['type'] : '';
                    $data[$name]['linkText'] = 'View File';
                    $data[$name]['file_url'] = $file_url ?? '';
                    $data[$name]['type'] = 'file';
                    // Ensure the value contains the file URL for Notion URL columns
                    if (!empty($file_url)) {
                        $data[$name]['value'] = $file_url;
                    }
                }

                if (in_array($type, $this->signature_field_types)) {
                    $sig_url = isset($data[$name]['value']) ? $data[$name]['value'] : '';
                    if (!empty($sig_url)) {
                        $data[$name]['file_type'] = 'image/png';
                        $data[$name]['linkText'] = 'View Signature';
                        $data[$name]['file_url'] = $sig_url;
                        $data[$name]['is_signature'] = true;
                    }
                }
            }

            // $old_url = 'http://tablesome-dev.local/wp-content/uploads/forminator/617_7a9de121849d5b46ac6356cb2bc211ef/uploads/uGUH9tJmPivK-Copy.of_.Member.Roster.Tab_.csv';
            // $old_attachment_id = attachment_url_to_postid($old_url);
            // error_log(' Forminator old_attachment_id : ' . $old_attachment_id);

            $data = $this->post_processing($data);
            // error_log(' Forminator formatted data : ' . print_r($data, true));
            return $data;
        }

        protected function save_base64_signature_to_file($base64_data)
        {
            if (!preg_match('/^data:image\/(png|jpeg|jpg|gif);base64,(.+)$/i', $base64_data, $matches)) {
                return false;
            }

            $extension = strtolower($matches[1]);
            if ($extension === 'jpeg') {
                $extension = 'jpg';
            }

            if (!in_array($extension, array('png', 'jpg', 'gif'), true)) {
                return false;
            }

            $decoded_data = base64_decode($matches[2], true);
            if ($decoded_data === false) {
                return false;
            }

            $finfo = new \finfo(FILEINFO_MIME_TYPE);
            $mime_type = $finfo->buffer($decoded_data);
            $allowed_mimes = array('image/png', 'image/jpeg', 'image/gif');
            if (!in_array($mime_type, $allowed_mimes, true)) {
                return false;
            }

            $filename = 'signature_' . time() . '_' . wp_rand(1000, 9999) . '.' . $extension;
            $filename = sanitize_file_name($filename);

            $upload_dir = wp_upload_dir();
            $signature_dir = $upload_dir['basedir'] . '/tablesome-signatures';

            if (!file_exists($signature_dir)) {
                wp_mkdir_p($signature_dir);
                $index_file = $signature_dir . '/index.php';
                if (!file_exists($index_file)) {
                    file_put_contents($index_file, '<?php // Silence is golden');
                }
            }

            $file_path = $signature_dir . '/' . $filename;
            $bytes_written = file_put_contents($file_path, $decoded_data);
            if ($bytes_written === false) {
                return false;
            }

            return $upload_dir['baseurl'] . '/tablesome-signatures/' . $filename;
        }

        public function post_processing_fields($form_fields)
        {

            end($form_fields);
            $last_key = key($form_fields);
            reset($form_fields);
            // error_log(' Forminator form_fields : ' . print_r($form_fields, true));
            // Processing for paypal fields

            $last_key = $last_key + 1;
            foreach ($form_fields as $primary_key => $field) {

                if ($field['field_type'] == 'paypal') {
                    $form_fields[$last_key++] = [
                        'id' => $field['id'] . '_mode',
                        'label' => 'Mode',
                        'field_type' => 'paypal',
                    ];

                    $form_fields[$last_key++] = [
                        'id' => $field['id'] . '_transaction_id',
                        'label' => 'Transaction ID',
                        'field_type' => 'paypal',
                    ];

                    $form_fields[$last_key++] = [
                        'id' => $field['id'] . '_status',
                        'label' => 'Payment Status',
                        'field_type' => 'paypal',
                    ];

                    $form_fields[$last_key++] = [
                        'id' => $field['id'] . '_amount',
                        'label' => 'Payment Amount',
                        'field_type' => 'paypal',
                    ];

                    $form_fields[$last_key++] = [
                        'id' => $field['id'] . '_currency',
                        'label' => 'Payment Currency',
                        'field_type' => 'paypal',
                    ];

                    $form_fields[$last_key++] = [
                        'id' => $field['id'] . '_transaction_link',
                        'label' => 'Transaction Link',
                        'field_type' => 'paypal',
                    ];

                }
            }

            // error_log(' Forminator form_fields eenndd: ' . print_r($form_fields, true));
            return $form_fields;
        }
        public function post_processing($data)
        {

            // Processing for paypal fields
            foreach ($data as $key => $field) {
                if ($field['type'] == 'paypal') {
                    $data[$key]['value'] = $field['value'];

                    // Mode
                    if (isset($field['additional_data']['mode'])) {
                        $data[$key . '_mode'] = array(
                            'type' => 'paypal',
                            'label' => 'Mode',
                            'value' => isset($field['additional_data']['mode']) ? $field['additional_data']['mode'] : '',
                        );
                    }

                    // Transaction ID
                    if (isset($field['additional_data']['transaction_id'])) {
                        $data[$key . '_transaction_id'] = array(
                            'type' => 'paypal',
                            'label' => 'Transaction ID',
                            'value' => isset($field['additional_data']['transaction_id']) ? $field['additional_data']['transaction_id'] : '',
                        );
                    }

                    // Payment Status
                    if (isset($field['additional_data']['status'])) {
                        $data[$key . '_status'] = array(
                            'type' => 'paypal',
                            'label' => 'Payment Status',
                            'value' => isset($field['additional_data']['status']) ? $field['additional_data']['status'] : '',
                        );
                    }

                    // Payment Amount
                    if (isset($field['additional_data']['amount'])) {
                        $data[$key . '_amount'] = array(
                            'type' => 'paypal',
                            'label' => 'Payment Amount',
                            'value' => isset($field['additional_data']['amount']) ? $field['additional_data']['amount'] : '',
                        );
                    }

                    // Payment Currency
                    if (isset($field['additional_data']['currency'])) {
                        $data[$key . '_currency'] = array(
                            'type' => 'paypal',
                            'label' => 'Payment Currency',
                            'value' => isset($field['additional_data']['currency']) ? $field['additional_data']['currency'] : '',
                        );
                    }

                    // Transaction Link
                    if (isset($field['additional_data']['transaction_link'])) {
                        $data[$key . '_transaction_link'] = array(
                            'type' => 'paypal',
                            'label' => 'Transaction Link',
                            'value' => isset($field['additional_data']['transaction_link']) ? $field['additional_data']['transaction_link'] : '',
                        );
                    }

                }
            } // End of foreach

            return $data;
        }
    } // End of class
}
