<?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_fwcrm_form_Util')) {

    class integrazo_fwcrm_form_Util
    {

        /**
         * Check if a given timestamp (in milliseconds) is today's date.
         */
        public function is_today_date_in_milliseconds($milliseconds)
        {
            $datetime = $this->convert_milliseconds_to_datetime($milliseconds);
            $current_date = new DateTime('now', new DateTimeZone(wp_timezone_string()));
            return $datetime->format('Y-m-d') === $current_date->format('Y-m-d');
        }

        /**
         * Check if a given timestamp (in milliseconds) is tomorrow's date.
         */
        public function is_tomorrow_date_in_milliseconds($milliseconds)
        {
            $datetime = $this->convert_milliseconds_to_datetime($milliseconds);
            $current_date = new DateTime('now', new DateTimeZone(wp_timezone_string()));
            $current_date->modify('+1 day');
            return $datetime->format('Y-m-d') === $current_date->format('Y-m-d');
        }

        /**
         * Check if a given timestamp (in milliseconds) is within the last two days.
         */
        public function is_last_two_days_in_milliseconds($milliseconds)
        {
            $datetime = $this->convert_milliseconds_to_datetime($milliseconds);
            $current_date = new DateTime('now', new DateTimeZone(wp_timezone_string()));
            $two_days_ago = (clone $current_date)->modify('-2 days');
            return $datetime->format('Y-m-d') >= $two_days_ago->format('Y-m-d') && $datetime->format('Y-m-d') < $current_date->format('Y-m-d');
        }

        /**
         * Get the current time in milliseconds.
         */
        public function get_current_time_in_milliseconds()
        {
            return round(microtime(true) * 1000);
        }

        /**
         * Format milliseconds to a local time string.
         */
        public function integrazo_fwcrm_form_format_milliseconds_to_local_time($milliseconds)
        {
            $datetime = $this->convert_milliseconds_to_datetime($milliseconds);
            return $datetime->format('Y-M-d h:i A');
        }

        /**
         * Format milliseconds to a local date string (date only).
         */
        public function integrazo_fwcrm_form_format_milliseconds_to_local_time_date_only($milliseconds)
        {
            $datetime = $this->convert_milliseconds_to_datetime($milliseconds);
            return $datetime->format('Y-M-d');
        }

        /**
         * Helper to convert milliseconds to DateTime object.
         */
        private function convert_milliseconds_to_datetime($milliseconds)
        {
            $seconds = $milliseconds / 1000;
            $datetime = new DateTime("@$seconds");
            $timezone = new DateTimeZone(wp_timezone_string());
            $datetime->setTimezone($timezone);
            return $datetime;
        }


        /**
         * Get total count of forms with field mapping.
         */
        public function get_total_form_mapping_count()
        {
            $forms = get_posts([
                'post_type' => 'wpcf7_contact_form',
                'fields'    => 'ids',
                'nopaging'  => true,
            ]);

            $total_mapped_forms = 0;
            foreach ($forms as $form_id) {
                $field_mapping = get_option('fw_crm_integrazo_fwcrm_form_' . $form_id . '_field_mapping');
                if (!empty($field_mapping)) {
                    $total_mapped_forms++;
                }
            }

            return $total_mapped_forms;
        }

        /**
         * Get all form IDs with field mapping.
         */
        public function get_all_form_mapping_ids()
        {
            $forms = get_posts([
                'post_type' => 'wpcf7_contact_form',
                'fields'    => 'ids',
                'nopaging'  => true,
            ]);

            $mapped_form_ids = [];
            foreach ($forms as $form_id) {
                $field_mapping = get_option('fw_crm_integrazo_fwcrm_form_' . $form_id . '_field_mapping');
                if (!empty($field_mapping)) {
                    $mapped_form_ids[] = $form_id;
                }
            }

            return $mapped_form_ids;
        }

        /**
         * Get list of premium fields.
         */
        public function get_premium_fields_list()
        {
            return ["phone", "mobile_number", "work_number", "lifecycle_stage_id", "subscription_status", "time_zone", "country", "tags"];
        }

        /**
         * Check if any premium fields are used on form submit.
         */
        public function is_used_premium_fields_on_submit($posted_data, $field_mapping)
        {
            $premium_fields = $this->get_premium_fields_list();
            foreach ($field_mapping as $field_name => $field_value) {
                if (in_array($field_value, $premium_fields) || strpos($field_value, 'cf_') === 0) {
                    if (!empty($posted_data[$field_name])) {
                        return true;
                    }
                }
            }

            return false;
        }

        /**
         * Check if any premium fields are used across all mappings.
         */
        public function is_used_premium_fields()
        {
            $all_form_ids = $this->get_all_form_mapping_ids();
            $premium_fields = $this->get_premium_fields_list();

            foreach ($all_form_ids as $form_id) {
                $field_mapping = get_option('fw_crm_integrazo_fwcrm_form_' . $form_id . '_field_mapping');
                if (!empty($field_mapping) && is_array($field_mapping)) {
                    foreach ($field_mapping as $field_name => $field_value) {
                        if (in_array($field_name, $premium_fields) || strpos($field_value, 'cf_') === 0) {
                            return true;
                        }
                    }
                }
            }

            return false;
        }
    }
    $integrazo_fwcrm_form_utilInstance = new integrazo_fwcrm_form_Util();
}
