<?php
if (!defined('ABSPATH')) {
    die('You are not allowed to call this page directly.');
}

/**
 * Class FormShieldFormDetector
 * Специализирана детекция за Divi Contact Forms
 */
class FormShieldFormDetector {

    /**
     * Основна функция за намиране на Divi форми
     */
    public static function dcd_find_divi_forms(): array {
        // Clear cache to force rescan with new CF7 detection
        delete_transient('dcd_divi_scan');
        
        // Проверяваме кеша първо
        $cached = get_transient('dcd_divi_scan');
        if ($cached !== false) {
            return $cached;
        }

        $forms = array();

        // 1. Търсене в постове/страници/CPT
        $forms = array_merge($forms, self::dcd_scan_posts_for_divi_forms());

        // 2. Търсене в Divi Library
        $forms = array_merge($forms, self::dcd_scan_divi_library());

        // 3. Търсене в Theme Builder
        $forms = array_merge($forms, self::dcd_scan_theme_builder());

        // 4. Fallback фронтенд проверка
        $forms = array_merge($forms, self::dcd_scan_frontend());

        // Кешираме резултата за 30 минути
        set_transient('dcd_divi_scan', $forms, 30 * MINUTE_IN_SECONDS);

        return $forms;
    }

    /**
     * Проверява дали има Divi форми
     */
    public static function dcd_has_divi_form(): bool {
        return !empty(self::dcd_find_divi_forms());
    }

    /**
     * Търси Divi форми в постове/страници/CPT
     */
    private static function dcd_scan_posts_for_divi_forms(): array {
        $forms = array();
        
        // Вземаме всички публични post types
        $post_types = get_post_types(array('public' => true));
        
        // Търсим по батчове от 50 за по-добра производителност
        $paged = 1;
        $posts_per_page = 50;
        
        do {
            $query = new WP_Query(array(
                'post_type' => $post_types,
                'post_status' => array('publish', 'private'),
                'posts_per_page' => $posts_per_page,
                'paged' => $paged,
                'fields' => 'ids', // Само ID-тата за бързина
                'no_found_rows' => true,
                // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key
                'meta_key' => '_et_pb_old_content',
                'meta_compare' => 'EXISTS'
            ));

            if ($query->posts) {
                // Използваме get_posts за по-бързо зареждане
                $posts = get_posts(array(
                    'post__in' => $query->posts,
                    'post_type' => 'any',
                    'post_status' => array('publish', 'private'),
                    'numberposts' => -1,
                    'fields' => 'all'
                ));

                foreach ($posts as $post) {
                    // Skip if this page contains Contact Form 7 shortcodes
                    // This prevents CF7 forms from being detected as Divi forms
                    $cf7_patterns = array(
                        '/\[contact-form-7[^\]]*\]/i',
                        '/\[contact_form_7[^\]]*\]/i',
                        '/\[cf7[^\]]*\]/i',
                        '/contact-form-7/i',
                        '/wpcf7/i'
                    );
                    
                    $has_cf7 = false;
                    foreach ($cf7_patterns as $pattern) {
                        if (preg_match($pattern, $post->post_content)) {
                            $has_cf7 = true;
                            break;
                        }
                    }
                    
                    if ($has_cf7) {
                        continue; // Skip this post, it's a CF7 form, not a Divi form
                    }
                    
                    // Регекс за сигурно хващане на Divi contact form
                    $has_form = (bool) preg_match('/\[(\s*)et_pb_contact_form(\s|\/|\])/i', $post->post_content);
                    
                    if ($has_form) {
                        // Вземаме контекст около първото съвпадение
                        $match_excerpt = self::dcd_get_context_around_match($post->post_content, 'et_pb_contact_form');
                        
                        $forms[] = array(
                            'location' => 'post',
                            'post_id' => $post->ID,
                            'post_type' => $post->post_type,
                            'post_title' => $post->post_title,
                            'url' => get_permalink($post->ID),
                            'match_excerpt' => $match_excerpt
                        );
                    }
                }
            }

            $paged++;
        } while ($query->posts && count($query->posts) === $posts_per_page);

        return $forms;
    }

    /**
     * Търси Divi форми в Library
     */
    private static function dcd_scan_divi_library(): array {
        $forms = array();
        
        $layouts = get_posts(array(
            'post_type' => 'et_pb_layout',
            'post_status' => array('publish', 'private'),
            'posts_per_page' => -1,
            'fields' => 'ids'
        ));

        foreach ($layouts as $layout_id) {
            $layout = get_post($layout_id);
            if (!$layout) continue;

            $has_form = (bool) preg_match('/\[(\s*)et_pb_contact_form(\s|\/|\])/i', $layout->post_content);
            
            if ($has_form) {
                $match_excerpt = self::dcd_get_context_around_match($layout->post_content, 'et_pb_contact_form');
                
                $forms[] = array(
                    'location' => 'library',
                    'post_id' => $layout_id,
                    'post_type' => 'et_pb_layout',
                    'post_title' => $layout->post_title,
                    'url' => get_permalink($layout_id),
                    'match_excerpt' => $match_excerpt
                );
            }
        }

        return $forms;
    }

    /**
     * Търси Divi форми в Theme Builder
     */
    private static function dcd_scan_theme_builder(): array {
        $forms = array();
        
        // Метод 1: et_theme_builder_template post type
        $templates = get_posts(array(
            'post_type' => 'et_theme_builder_template',
            'post_status' => array('publish', 'private'),
            'posts_per_page' => -1,
            'fields' => 'ids'
        ));

        foreach ($templates as $template_id) {
            $template = get_post($template_id);
            if (!$template) continue;

            $has_form = (bool) preg_match('/\[(\s*)et_pb_contact_form(\s|\/|\])/i', $template->post_content);
            
            if ($has_form) {
                $match_excerpt = self::dcd_get_context_around_match($template->post_content, 'et_pb_contact_form');
                
                $forms[] = array(
                    'location' => 'theme_builder',
                    'post_id' => $template_id,
                    'post_type' => 'et_theme_builder_template',
                    'post_title' => $template->post_title,
                    'url' => admin_url('admin.php?page=et_theme_builder'),
                    'match_excerpt' => $match_excerpt
                );
            }
        }

        // Метод 2: et_theme_builder option
        $theme_builder_option = get_option('et_theme_builder');
        if ($theme_builder_option) {
            $option_string = wp_json_encode($theme_builder_option, JSON_UNESCAPED_UNICODE);
            if (stripos($option_string, 'et_pb_contact_form') !== false) {
                $forms[] = array(
                    'location' => 'theme_builder',
                    'post_id' => null,
                    'post_type' => null,
                    'post_title' => 'Theme Builder Option',
                    'url' => admin_url('admin.php?page=et_theme_builder'),
                    'match_excerpt' => 'Found in et_theme_builder option'
                );
            }
        }

        return $forms;
    }

    /**
     * Fallback фронтенд проверка
     */
    private static function dcd_scan_frontend(): array {
        $forms = array();
        $urls_to_check = array();
        
        // Добавяме home page
        $urls_to_check[] = home_url('/');
        
        // Добавяме 3 най-нови страници/постове за по-бързо сканиране
        $recent_posts = get_posts(array(
            'post_type' => array('page', 'post'),
            'post_status' => 'publish',
            'posts_per_page' => 3,
            'fields' => 'ids'
        ));

        foreach ($recent_posts as $post_id) {
            $urls_to_check[] = get_permalink($post_id);
        }

        // Ограничаваме до 4 URL-а за по-бързо сканиране
        $urls_to_check = array_slice($urls_to_check, 0, 4);

        foreach ($urls_to_check as $url) {
            try {
                $response = wp_remote_get($url, array(
                    'timeout' => 3, // Намаляваме timeout за по-бързо сканиране
                    'user-agent' => 'FormShield-Divi-Detector/1.0'
                    // rely on default SSL verification (true)
                ));

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

                $body = wp_remote_retrieve_body($response);
                if (empty($body)) {
                    continue;
                }

                // Търсим Divi contact form селектори
                $selectors = array(
                    '.et_pb_contact_form',
                    '.et_pb_contact_form_container',
                    'data-et_pb_module_class="et_pb_contact_form"'
                );

                foreach ($selectors as $selector) {
                    if (strpos($body, $selector) !== false) {
                        $forms[] = array(
                            'location' => 'frontend_check',
                            'post_id' => null,
                            'post_type' => null,
                            'post_title' => 'Frontend Detection',
                            'url' => $url,
                            'match_excerpt' => 'Found selector: ' . $selector
                        );
                        break 2; // Излизаме от двата цикъла
                    }
                }

            } catch (Exception $e) {
                continue;
            }
        }

        return $forms;
    }

    /**
     * Взема контекст около съвпадението
     */
    private static function dcd_get_context_around_match($content, $search_term, $context_length = 120): string {
        $pos = stripos($content, $search_term);
        if ($pos === false) {
            return '';
        }

        $start = max(0, $pos - ($context_length / 2));
        $length = $context_length;
        
        $excerpt = substr($content, $start, $length);
        
        // Добавяме ... ако не е началото
        if ($start > 0) {
            $excerpt = '...' . $excerpt;
        }
        
        // Добавяме ... ако не е края
        if ($start + $length < strlen($content)) {
            $excerpt .= '...';
        }

        return $excerpt;
    }

    /**
     * Проверява за WordPress коментарна форма
     */
    public static function dcd_has_comment_form(): array {
        $posts_with_comments = get_posts(array(
            'post_type' => array('post', 'page'),
            'post_status' => 'publish',
            'posts_per_page' => 1,
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_key,WordPress.DB.SlowDBQuery.slow_db_query_meta_value
            'meta_key' => 'comment_status',
            // phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_value
            'meta_value' => 'open'
        ));

        if (empty($posts_with_comments)) {
            return array(
                'has_comment_form' => false,
                'example_url' => null
            );
        }

        $post = $posts_with_comments[0];
        
        return array(
            'has_comment_form' => true,
            'example_url' => get_permalink($post->ID)
        );
    }

    /**
     * REST API endpoint за проверка на Divi форми
     */
    public static function rest_has_form() {
        $forms = self::dcd_find_divi_forms();
        
        return array(
            'has_form' => !empty($forms),
            'count' => count($forms)
        );
    }

    /**
     * REST API endpoint за локациите
     */
    public static function rest_locations() {
        return self::dcd_find_divi_forms();
    }

    /**
     * WP-CLI команда
     */
    public static function cli_detect() {
        $forms = self::dcd_find_divi_forms();
        
        if (empty($forms)) {
            WP_CLI::warning('No Divi contact forms found.');
            return 1;
        }

        WP_CLI::success('Found ' . count($forms) . ' Divi contact form(s):');
        
        foreach ($forms as $form) {
            WP_CLI::line(sprintf(
                '- %s: %s (%s) - %s',
                $form['location'],
                $form['post_title'] ?: 'No title',
                $form['url'] ?: 'No URL',
                $form['match_excerpt'] ?: 'No excerpt'
            ));
        }

        return 0;
    }

    /**
     * Admin бутон за Rescan
     */
    public static function admin_rescan() {
        // Изчистваме кеша
        delete_transient('dcd_divi_scan');
        
        // Стартираме ново сканиране
        $forms = self::dcd_find_divi_forms();
        
        return array(
            'success' => true,
            'forms_found' => count($forms),
            'message' => 'Rescan completed. Found ' . count($forms) . ' forms.'
        );
    }

    /**
     * Основна функция за сканиране (за backward compatibility)
     */
    public static function scan_site_for_forms() {
        $forms = array();
        
        // 1. Divi форми
        $divi_forms = self::dcd_find_divi_forms();
        foreach ($divi_forms as $divi_form) {
            // Проверяваме дали е Frontend Detection
            if (isset($divi_form['location']) && $divi_form['location'] === 'frontend_check') {
                $forms[] = array(
                    'id' => 'frontend_detector',
                    'name' => 'Form Detection System',
                    'plugin' => 'FormShield Detector',
                    'enabled' => 1,
                    'blocked_attempts' => 0,
                    'type' => 'form-detector',
                    'shortcode' => 'form-detector',
                    'page_id' => 0,
                    'location' => 'Form Detection System'
                );
            } else {
                // Проверяваме дали има необходимите ключове
                $post_id = isset($divi_form['post_id']) ? $divi_form['post_id'] : 0;
                $post_title = isset($divi_form['post_title']) ? $divi_form['post_title'] : 'Divi Contact Form';
                
                $forms[] = array(
                    'id' => 'divi_' . ($post_id ?: uniqid()),
                    'name' => $post_title,
                    'plugin' => 'Divi Contact Form',
                    'enabled' => 1,
                    'blocked_attempts' => 0,
                    'type' => 'divi',
                    'shortcode' => 'divi_contact_form',
                    'page_id' => $post_id,
                    'location' => $post_title
                );
            }
        }

        // 2. WordPress коментари (всички страници с коментари)
        // WordPress коментарите се откриват чрез FormShieldWPCommentsIntegration
        // и не се дублират тук

        // 3. Contact Form 7 - не създаваме скенер, защото FormShieldCF7Integration се грижи за това
        // Contact Form 7 формите се откриват чрез FormShieldCF7Integration

        // 4. Ninja Forms
        if (is_plugin_active('ninja-forms/ninja-forms.php')) {
            $ninja_forms = self::scan_for_ninja_forms();
            foreach ($ninja_forms as $ninja_form) {
                $forms[] = array(
                    'id' => 'ninja_' . $ninja_form['id'],
                    'name' => $ninja_form['title'],
                    'plugin' => 'Ninja Forms',
                    'enabled' => 1,
                    'blocked_attempts' => 0,
                    'type' => 'ninja-forms',
                    'shortcode' => 'ninja-forms',
                    'page_id' => 0,
                    'location' => $ninja_form['title']
                );
            }
        }

        // Записваме в опциите с error handling
        try {
            $options = get_option('formshield_options', array());
            if (!is_array($options)) {
                $options = array();
            }
            $options['detected_forms'] = $forms;
            $options['last_scan_time'] = current_time('mysql');
            $options['last_scan_timestamp'] = current_time('timestamp');
            
            $result = update_option('formshield_options', $options);
            // Options updated successfully
        } catch (Exception $e) {
            // Log error but don't fail the scan
        } catch (Error $e) {
            // Catch fatal errors
        }

        return $forms;
    }

    /**
     * Сканира за WordPress коментари
     */
    private static function scan_for_comment_forms() {
        $forms = array();
        
        // Вземаме всички публични post types които поддържат коментари
        $post_types = get_post_types(array('public' => true));
        
        foreach ($post_types as $post_type) {
            $posts = get_posts(array(
                'post_type' => $post_type,
                'post_status' => 'publish',
                'posts_per_page' => -1,
                'comment_status' => 'open'
            ));
            
            foreach ($posts as $post) {
                if (comments_open($post->ID)) {
                    $forms[] = array(
                        'post_id' => $post->ID,
                        'post_title' => $post->post_title
                    );
                }
            }
        }
        
        // Ако няма страници с коментари, добави общата система за коментари
        if (empty($forms)) {
            $forms[] = array(
                'post_id' => 0,
                'post_title' => 'WordPress Comments System'
            );
        }
        
        return $forms;
    }

    /**
     * Сканира за Contact Form 7
     */
    private static function scan_for_contact_form_7() {
        $forms = array();
        
        if (class_exists('WPCF7_ContactForm')) {
            $cf7_forms = get_posts(array(
                'post_type' => 'wpcf7_contact_form',
                'post_status' => 'publish',
                'posts_per_page' => -1
            ));
            
            foreach ($cf7_forms as $form) {
                // Get the Contact Form 7 slug (not WordPress post ID)
                $cf7_slug = $form->post_name;
                
                // If no slug, fallback to post ID
                if (empty($cf7_slug)) {
                    $cf7_slug = $form->ID;
                }
                
                $forms[] = array(
                    'id' => $cf7_slug,
                    'title' => $form->post_title
                );
            }
        }
        
        return $forms;
    }

    /**
     * Сканира за Ninja Forms
     */
    private static function scan_for_ninja_forms() {
        $forms = array();
        
        if (class_exists('Ninja_Forms')) {
            // Get forms using Ninja Forms API
            $ninja_forms = Ninja_Forms()->form()->get_forms();
            
            foreach ($ninja_forms as $form) {
                $forms[] = array(
                    'id' => $form->get_id(),
                    'title' => $form->get_setting('title')
                );
            }
        }
        
        return $forms;
    }

    /**
     * Автоматично сканиране при активиране
     */
    public static function auto_scan_on_activation() {
        $forms = self::dcd_find_divi_forms();
        return $forms;
    }
    

}
