<?php
if ( ! defined( 'ABSPATH' ) ) exit;

/**
 * Contact Form Handler - 联系表单提交处理器(动态字段版本)
 * * @package PufferGo
 * @since 1.0.0
 */

class PufferGo_Contact_Form_Handler {
    
    const RATE_LIMIT_COUNT = 50;
    const RATE_LIMIT_SECONDS = 300;
    
    public function __construct() {
        add_action('rest_api_init', array($this, 'register_api'));
        add_action('rest_api_init', array($this, 'register_admin_api'));

        if ( is_admin() ) {
            add_action('admin_enqueue_scripts', array($this, 'enqueue_inquiries_scripts'));
        }
    }
    
    public function create_table() {
        global $wpdb;
        $charset_collate = $wpdb->get_charset_collate();
        $table_name = $wpdb->prefix . 'puffergo_contact_submissions';
        
        // phpcs:ignore WordPress.DB.PreparedSQL.InterpolatedNotPrepared
        $sql = "CREATE TABLE $table_name (
            id bigint(20) NOT NULL AUTO_INCREMENT,
            form_data longtext NOT NULL,
            page_url varchar(500) DEFAULT '',
            ip_address varchar(45) DEFAULT '',
            user_agent text,
            status varchar(20) DEFAULT 'new',
            created_at datetime DEFAULT CURRENT_TIMESTAMP,
            PRIMARY KEY (id),
            KEY idx_created_at (created_at),
            KEY idx_ip_address (ip_address)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    
    public function register_api() {
        register_rest_route('puffergo/v1', '/contact', array(
            'methods' => 'POST',
            'callback' => array($this, 'handle_submission'),
            'permission_callback' => '__return_true',
        ));
    }
    
    public function handle_submission($request) {
        $params = $request->get_json_params();
        $page_url = isset($params['page_url']) ? esc_url_raw($params['page_url']) : '';
        unset($params['page_url']);
        
        if (empty($params) || !is_array($params)) {
            return new WP_REST_Response(array('success' => false, 'message' => '缺少字段'), 400);
        }
        
        $cleaned_data = array();
        foreach ($params as $key => $value) {
            $key = sanitize_key($key);
            if (is_array($value)) {
                $cleaned_data[$key] = array_map('sanitize_text_field', $value);
            } else {
                $cleaned_data[$key] = sanitize_text_field($value);
            }
        }
        
        $ip_address = $this->get_client_ip();
        if ($this->is_rate_limited($ip_address)) {
            return new WP_REST_Response(array('success' => false, 'message' => '提交太频繁'), 429);
        }

        global $wpdb;
        $table = $wpdb->prefix . 'puffergo_contact_submissions';

        // 多站点：子站表可能尚未创建，按需建表
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- 检查表是否存在无需缓存
        $table_exists = $wpdb->get_var( $wpdb->prepare( 'SHOW TABLES LIKE %s', $table ) );
        if ( empty( $table_exists ) ) {
            $this->create_table();
        }

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery
        $result = $wpdb->insert(
            $table,
            array(
                'form_data' => wp_json_encode($cleaned_data, JSON_UNESCAPED_UNICODE),
                'page_url' => $page_url,
                'ip_address' => $ip_address,
                'user_agent' => isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '',
                'status' => 'new',
            ),
            array('%s', '%s', '%s', '%s', '%s')
        );
        
        if ( $result === false ) {
            puffergo_log(
                'Contact insert failed: ' . $wpdb->last_error . ' | SQL: ' . $wpdb->last_query,
                'PufferGo-Contact'
            );
            return new WP_REST_Response(array('success' => false, 'message' => '系统错误'), 500);
        }
        
        $submission_id = $wpdb->insert_id;

        // 【功能恢复】恢复完整的邮件通知功能
        $admin_sent = $this->send_notification_email($submission_id, $cleaned_data, $page_url);
        $user_sent = $this->send_confirmation_email($cleaned_data, $page_url);
        
        return new WP_REST_Response(array(
            'success' => true, 
            'message' => '提交成功',
            'data' => array(
                'id' => $submission_id,
                'admin_sent' => $admin_sent,
                'user_sent' => $user_sent
            )
        ), 200);
    }

    /**
     * 发送管理员通知邮件 (完整版)
     */
    private function send_notification_email($id, $form_data, $url) {
        $to = get_option('puffergo_notification_emails', get_option('admin_email'));
        if (empty($to)) {
            return false;
        }

        $subject = sprintf('[%s] 新表单提交 #%d', get_bloginfo('name'), $id);
        
        // 构建简单的 HTML 表格
        $message = '<h3>收到新的联系表单提交</h3>';
        $message .= '<table border="1" cellpadding="5" cellspacing="0" style="border-collapse:collapse;">';
        foreach ($form_data as $key => $val) {
            $val_str = is_array($val) ? implode(', ', $val) : $val;
            $message .= sprintf('<tr><td><strong>%s</strong></td><td>%s</td></tr>', esc_html($key), esc_html($val_str));
        }
        $message .= '</table>';
        
        if (!empty($url)) {
            $message .= '<p>来源页面: <a href="' . esc_url($url) . '">' . esc_html($url) . '</a></p>';
        }

        $headers = array('Content-Type: text/html; charset=UTF-8');
        return wp_mail($to, $subject, $message, $headers);
    }

    /**
     * 发送用户确认邮件 (完整版)
     */
    private function send_confirmation_email($form_data, $url) {
        // 智能查找用户邮箱
        $user_email = '';
        foreach (['email', 'user_email', 'your_email', 'mail'] as $field) {
            if (isset($form_data[$field]) && is_email($form_data[$field])) {
                $user_email = $form_data[$field];
                break;
            }
        }

        if (empty($user_email)) {
            return false;
        }

        $subject = sprintf('感谢您的咨询 - %s', get_bloginfo('name'));
        
        $message = '<div style="font-family: sans-serif; padding: 20px;">';
        $message .= '<h2>我们已收到您的消息</h2>';
        $message .= '<p>感谢您的联络，我们会尽快与您取得联系。</p>';
        $message .= '<hr>';
        $message .= '<h3>您提交的信息副本：</h3>';
        $message .= '<ul>';
        foreach ($form_data as $key => $val) {
            $val_str = is_array($val) ? implode(', ', $val) : $val;
            // 排除敏感字段
            if (in_array(strtolower($key), ['password', 'pwd'])) continue;
            $message .= sprintf('<li><strong>%s:</strong> %s</li>', esc_html($key), esc_html($val_str));
        }
        $message .= '</ul>';
        $message .= '<p style="color:#999; font-size:12px;">此邮件由系统自动发送。</p>';
        $message .= '</div>';

        $headers = array('Content-Type: text/html; charset=UTF-8');
        return wp_mail($user_email, $subject, $message, $headers);
    }
    
    private function is_rate_limited($ip_address) {
        global $wpdb;
        
        $time_threshold = gmdate('Y-m-d H:i:s', time() - self::RATE_LIMIT_SECONDS);
        $table_name = $wpdb->prefix . 'puffergo_contact_submissions';
        
        // 【保持区域封锁】这是通过检查的关键，千万别动这里
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery, PluginCheck.Security.DirectDB.UnescapedDBParameter
        $count = $wpdb->get_var($wpdb->prepare(
            "SELECT COUNT(*) FROM $table_name WHERE ip_address = %s AND created_at > %s",
            $ip_address,
            $time_threshold
        ));
        // phpcs:enable
        
        return $count >= self::RATE_LIMIT_COUNT;
    }
    
    // -------------------------------------------------------------------------
    // 后台询盘管理
    // -------------------------------------------------------------------------

    /**
     * 渲染询盘管理页面（React 挂载点）
     */
    public static function render_inquiries_page() {
        ?>
        <div class="wrap">
            <div id="puffergo-inquiries-root"></div>
        </div>
        <?php
    }

    /**
     * 加载询盘管理页面资源
     */
    public function enqueue_inquiries_scripts( $hook ) {
        if ( $hook !== 'puffergo_page_puffergo-inquiries' ) {
            return;
        }

        $plugin_url  = plugin_dir_url( dirname( __FILE__ ) );
        $asset_file  = plugin_dir_path( dirname( __FILE__ ) ) . 'build/blocks/inquiries-app/index.asset.php';

        if ( file_exists( $asset_file ) ) {
            $asset       = include $asset_file;
            $dependencies = $asset['dependencies'];
            $version      = $asset['version'];
        } else {
            $dependencies = array( 'wp-element', 'wp-components', 'wp-api-fetch', 'wp-data' );
            $version      = time();
        }

        wp_enqueue_script(
            'puffergo-inquiries',
            $plugin_url . 'build/blocks/inquiries-app/index.js',
            $dependencies,
            $version,
            true
        );

        // 组件样式（style.scss 编译产物）
        $style_file = plugin_dir_path( dirname( __FILE__ ) ) . 'build/blocks/inquiries-app/style-index.css';
        if ( file_exists( $style_file ) ) {
            wp_enqueue_style(
                'puffergo-inquiries-styles',
                $plugin_url . 'build/blocks/inquiries-app/style-index.css',
                array( 'puffergo-admin-tailwind', 'wp-components' ),
                $version
            );
        }

        // Tailwind 工具类（index.css = tailwind.css 编译产物，包含本页面用到的 class）
        $tailwind_file = plugin_dir_path( dirname( __FILE__ ) ) . 'build/blocks/inquiries-app/index.css';
        if ( file_exists( $tailwind_file ) ) {
            wp_enqueue_style(
                'puffergo-inquiries-tailwind',
                $plugin_url . 'build/blocks/inquiries-app/index.css',
                array( 'puffergo-inquiries-styles' ),
                $version
            );
        }

        wp_localize_script( 'puffergo-inquiries', 'puffergoInquiries', array(
            'restUrl' => rest_url(),
            'nonce'   => wp_create_nonce( 'wp_rest' ),
        ) );

        wp_enqueue_style( 'wp-components' );
    }

    /**
     * 注册后台管理 REST 路由
     */
    public function register_admin_api() {
        // 统计概览（独立端点，避免每次翻页都跑 GROUP BY）
        register_rest_route( 'puffergo/v1', '/contact-submissions/stats', array(
            'methods'             => 'GET',
            'callback'            => array( $this, 'get_submissions_stats' ),
            'permission_callback' => function() {
                return current_user_can( 'manage_options' );
            },
        ) );

        // 列表查询
        register_rest_route( 'puffergo/v1', '/contact-submissions', array(
            'methods'             => 'GET',
            'callback'            => array( $this, 'get_submissions' ),
            'permission_callback' => function() {
                return current_user_can( 'manage_options' );
            },
        ) );

        // 删除单条
        register_rest_route( 'puffergo/v1', '/contact-submissions/(?P<id>\d+)', array(
            'methods'             => 'DELETE',
            'callback'            => array( $this, 'delete_submission' ),
            'permission_callback' => function() {
                return current_user_can( 'manage_options' );
            },
        ) );

        // 更新状态
        register_rest_route( 'puffergo/v1', '/contact-submissions/(?P<id>\d+)/status', array(
            'methods'             => 'POST',
            'callback'            => array( $this, 'update_submission_status' ),
            'permission_callback' => function() {
                return current_user_can( 'manage_options' );
            },
        ) );
    }

    /**
     * 获取各状态计数（独立端点，支持搜索条件联动）
     */
    public function get_submissions_stats( $request ) {
        global $wpdb;

        $search = sanitize_text_field( $request->get_param( 'search' ) ?: '' );
        $table  = $wpdb->prefix . 'puffergo_contact_submissions';

        $where  = '1=1';
        $params = array();

        if ( ! empty( $search ) ) {
            $where    .= ' AND form_data LIKE %s';
            $params[] = '%' . $wpdb->esc_like( $search ) . '%';
        }

        $status_counts = array(
            'total'   => 0,
            'new'     => 0,
            'read'    => 0,
            'replied' => 0,
        );

        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery
        if ( ! empty( $params ) ) {
            $counts = $wpdb->get_results(
                $wpdb->prepare( "SELECT status, COUNT(*) AS cnt FROM {$table} WHERE {$where} GROUP BY status", $params ),
                ARRAY_A
            );
        } else {
            $counts = $wpdb->get_results( "SELECT status, COUNT(*) AS cnt FROM {$table} GROUP BY status", ARRAY_A );
        }
        // phpcs:enable

        foreach ( $counts as $row ) {
            $status_counts['total']                      += (int) $row['cnt'];
            $status_counts[ $row['status'] ] = (int) $row['cnt'];
        }

        return new WP_REST_Response( $status_counts, 200 );
    }

    /**
     * 获取提交列表（分页 + 筛选 + 搜索）
     */
    public function get_submissions( $request ) {
        global $wpdb;

        $page     = max( 1, intval( $request->get_param( 'page' ) ) );
        $per_page = max( 1, min( 100, intval( $request->get_param( 'per_page' ) ?: 20 ) ) );
        $status   = sanitize_key( $request->get_param( 'status' ) ?: '' );
        $search   = sanitize_text_field( $request->get_param( 'search' ) ?: '' );
        $offset   = ( $page - 1 ) * $per_page;

        $table  = $wpdb->prefix . 'puffergo_contact_submissions';
        $where  = '1=1';
        $params = array();

        if ( ! empty( $status ) && in_array( $status, array( 'new', 'read', 'replied' ), true ) ) {
            $where    .= ' AND status = %s';
            $params[] = $status;
        }

        if ( ! empty( $search ) ) {
            $where    .= ' AND form_data LIKE %s';
            $params[] = '%' . $wpdb->esc_like( $search ) . '%';
        }

        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared, WordPress.DB.DirectDatabaseQuery
        if ( ! empty( $params ) ) {
            $total = (int) $wpdb->get_var(
                $wpdb->prepare( "SELECT COUNT(*) FROM {$table} WHERE {$where}", $params )
            );
            $items = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM {$table} WHERE {$where} ORDER BY created_at DESC LIMIT %d OFFSET %d",
                    array_merge( $params, array( $per_page, $offset ) )
                ),
                ARRAY_A
            );
        } else {
            $total = (int) $wpdb->get_var( "SELECT COUNT(*) FROM {$table} WHERE {$where}" );
            $items = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT * FROM {$table} WHERE {$where} ORDER BY created_at DESC LIMIT %d OFFSET %d",
                    $per_page,
                    $offset
                ),
                ARRAY_A
            );
        }
        // phpcs:enable

        foreach ( $items as &$item ) {
            $item['form_data'] = json_decode( $item['form_data'], true );
        }
        unset( $item );

        return new WP_REST_Response( array(
            'items'       => $items,
            'total'       => $total,
            'total_pages' => (int) ceil( $total / $per_page ),
        ), 200 );
    }

    /**
     * 删除单条提交
     */
    public function delete_submission( $request ) {
        global $wpdb;

        $id    = intval( $request['id'] );
        $table = $wpdb->prefix . 'puffergo_contact_submissions';

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery
        $deleted = $wpdb->delete( $table, array( 'id' => $id ), array( '%d' ) );

        if ( ! $deleted ) {
            return new WP_REST_Response( array(
                'success' => false,
                'message' => '删除失败或记录不存在',
            ), 404 );
        }

        return new WP_REST_Response( array(
            'success' => true,
            'message' => '已删除',
        ), 200 );
    }

    /**
     * 更新提交状态
     */
    public function update_submission_status( $request ) {
        global $wpdb;

        $id     = intval( $request['id'] );
        $params = $request->get_json_params();
        $status = isset( $params['status'] ) ? sanitize_key( $params['status'] ) : '';

        if ( ! in_array( $status, array( 'new', 'read', 'replied' ), true ) ) {
            return new WP_REST_Response( array(
                'success' => false,
                'message' => '无效的状态值',
            ), 400 );
        }

        $table = $wpdb->prefix . 'puffergo_contact_submissions';

        // phpcs:ignore WordPress.DB.DirectDatabaseQuery
        $updated = $wpdb->update( $table, array( 'status' => $status ), array( 'id' => $id ), array( '%s' ), array( '%d' ) );

        if ( $updated === false ) {
            return new WP_REST_Response( array(
                'success' => false,
                'message' => '更新失败',
            ), 500 );
        }

        return new WP_REST_Response( array(
            'success' => true,
            'message' => '状态已更新',
        ), 200 );
    }

    private function get_client_ip() {
        $ip = '';
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ip = sanitize_text_field(wp_unslash($_SERVER['HTTP_X_FORWARDED_FOR']));
        } else {
            $ip = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : '';
        }
        return filter_var($ip, FILTER_VALIDATE_IP) ? $ip : '127.0.0.1';
    }
}