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

if (!function_exists('vmo_get_platform_faq_grounding_text')) {
    $vmo_platform_faq_path = __DIR__ . '/vmo-platform-faq.php';
    if (file_exists($vmo_platform_faq_path)) {
        require_once $vmo_platform_faq_path;
    }
}

/**
 * VMO Email Auto-Reply Engine
 *
 * AI-powered auto-reply system for incoming emails:
 *  - Classifies incoming emails (auto-answerable vs needs-review)
 *  - Generates contextual replies using business profile + AI
 *  - Queues replies for optional approval before sending
 *  - Supports auto-send mode for low-risk categories
 */
class VMO_Email_Auto_Reply {

    private static $instance = null;

    /** Categories the AI can auto-respond to without approval */
    private static $auto_send_categories = [
        'greeting',
        'hours_inquiry',
        'location_inquiry',
        'product_inquiry',
        'general_info',
        'thank_you',
    ];

    /** Categories that require human approval */
    private static $approval_categories = [
        'complaint',
        'refund_request',
        'partnership',
        'legal',
        'custom_order',
        'support_issue',
        'booking_request',
        'pricing_inquiry',
        'availability_request',
        'custom_pricing',
    ];

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

    public function init() {
        $this->ensure_auto_reply_table();
        add_action('wp_ajax_vmo_process_auto_replies', [$this, 'ajax_process_auto_replies']);
        add_action('wp_ajax_vmo_get_auto_reply_queue', [$this, 'ajax_get_queue']);
        add_action('wp_ajax_vmo_approve_auto_reply', [$this, 'ajax_approve_reply']);
        add_action('wp_ajax_vmo_dismiss_auto_reply', [$this, 'ajax_dismiss_reply']);
        add_action('wp_ajax_vmo_submit_form', [$this, 'ajax_handle_form_submission']);
        add_action('wp_ajax_nopriv_vmo_submit_form', [$this, 'ajax_handle_form_submission']);
        add_action('wp_ajax_vmo_get_products_for_email', [$this, 'ajax_get_products_for_email']);
        add_action('wp_ajax_vmo_insert_product_block', [$this, 'ajax_insert_product_block']);
        add_action('vmo_inbound_email_saved', [$this, 'handle_inbound_email_saved'], 10, 5);
        add_action('vmo_process_auto_replies_cron', [$this, 'process_auto_replies_cron']);
        if (!wp_next_scheduled('vmo_process_auto_replies_cron')) {
            wp_schedule_event(time() + 360, 'vmo_every_five_minutes', 'vmo_process_auto_replies_cron');
        }
    }

    private function get_auto_reply_table() {
        global $wpdb;
        return $wpdb->prefix . 'vmo_email_auto_reply_queue';
    }

    private function ensure_auto_reply_table() {
        global $wpdb;
        $table = $this->get_auto_reply_table();

        require_once ABSPATH . 'wp-admin/includes/upgrade.php';
        $charset_collate = $wpdb->get_charset_collate();
        $sql = "CREATE TABLE {$table} (
            id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
            user_id BIGINT UNSIGNED NOT NULL,
            mailbox_id BIGINT UNSIGNED NULL,
            automation_type VARCHAR(80) NOT NULL,
            trigger_type VARCHAR(80) NOT NULL,
            trigger_value VARCHAR(255) NULL,
            action_type VARCHAR(80) NOT NULL,
            action_data LONGTEXT NULL,
            status VARCHAR(40) NOT NULL DEFAULT 'pending',
            created_at DATETIME NOT NULL,
            updated_at DATETIME NULL,
            completed_at DATETIME NULL,
            PRIMARY KEY (id),
            KEY user_status (user_id, status),
            KEY trigger_lookup (user_id, automation_type, trigger_value)
        ) {$charset_collate};";
        dbDelta($sql);
    }

    private function verify_ajax_request() {
        if (check_ajax_referer('vmo_nonce', 'nonce', false)) {
            return true;
        }
        if (check_ajax_referer('vmo_builder_nonce', 'security', false)) {
            return true;
        }
        if (check_ajax_referer('vmo_ajax_nonce', 'security', false)) {
            return true;
        }
        $rest_nonce = isset($_SERVER['HTTP_X_WP_NONCE']) ? sanitize_text_field((string) $_SERVER['HTTP_X_WP_NONCE']) : '';
        return $rest_nonce && wp_verify_nonce($rest_nonce, 'wp_rest');
    }

    private function get_form_contract_secret(int $user_id, bool $create = false): string {
        if ($user_id <= 0) {
            return '';
        }

        $secret = get_user_meta($user_id, 'vmo_form_contract_secret', true);
        $secret = is_string($secret) ? trim($secret) : '';
        if (strlen($secret) >= 32) {
            return $secret;
        }

        if (!$create) {
            return '';
        }

        $secret = wp_generate_password(64, false, false);
        update_user_meta($user_id, 'vmo_form_contract_secret', $secret);
        return $secret;
    }

    private function normalize_form_contract_id($form_id, $fallback = 'contact'): string {
        $form_id = sanitize_key((string) $form_id);
        if ($form_id === '') {
            $form_id = sanitize_key((string) $fallback);
        }
        return $form_id ?: 'contact';
    }

    private function verify_form_signature(int $site_id, string $form_id, string $secret): bool {
        $signature = isset($_POST['form_signature']) ? sanitize_text_field(wp_unslash($_POST['form_signature'])) : '';
        $timestamp = isset($_POST['form_timestamp']) ? absint(wp_unslash($_POST['form_timestamp'])) : 0;
        if ($signature === '' || $timestamp <= 0 || $secret === '') {
            return false;
        }

        if ($timestamp > 9999999999) {
            $timestamp = (int) floor($timestamp / 1000);
        }

        if (abs(time() - $timestamp) > DAY_IN_SECONDS) {
            return false;
        }

        $payload = $site_id . '|' . $form_id . '|' . $timestamp;
        $expected = hash_hmac('sha256', $payload, $secret);
        return hash_equals($expected, $signature);
    }

    private function decode_form_contract_token(string $token): string {
        $token = trim($token);
        if ($token === '') {
            return '';
        }

        $normalized = strtr($token, '-_', '+/');
        $padding = strlen($normalized) % 4;
        if ($padding) {
            $normalized .= str_repeat('=', 4 - $padding);
        }

        $decoded = base64_decode($normalized, true);
        if (is_string($decoded) && $decoded !== '') {
            return $decoded;
        }

        return $token;
    }

    private function verify_form_contract_token(int $site_id, string $form_id, string $secret): bool {
        $token = '';
        foreach (array('form_contract', 'form_token', 'vmo_form_token') as $field) {
            if (!empty($_POST[$field])) {
                $token = sanitize_text_field(wp_unslash($_POST[$field]));
                break;
            }
        }

        if ($token === '' || $secret === '') {
            return false;
        }

        $raw_token = $this->decode_form_contract_token($token);
        $parts = explode(':', $raw_token);
        if (count($parts) !== 4) {
            return false;
        }

        $token_site_id = absint($parts[0]);
        $token_form_id = $this->normalize_form_contract_id($parts[1], $form_id);
        $issued_at = absint($parts[2]);
        $signature = sanitize_text_field($parts[3]);

        if ($token_site_id !== $site_id || $issued_at <= 0 || $signature === '') {
            return false;
        }
        if ($token_form_id !== $form_id && !in_array($token_form_id, array('*', 'all'), true)) {
            return false;
        }
        if ($issued_at > time() + HOUR_IN_SECONDS || $issued_at < time() - (180 * DAY_IN_SECONDS)) {
            return false;
        }

        $payload = $token_site_id . '|' . $token_form_id . '|' . $issued_at;
        $expected = hash_hmac('sha256', $payload, $secret);
        return hash_equals($expected, $signature);
    }

    private function verify_form_submission_contract(int $site_id, string $form_type) {
        $form_id = $this->normalize_form_contract_id($_POST['form_id'] ?? ($_POST['vmo_form'] ?? ''), $form_type);

        if (is_user_logged_in()) {
            $current_user_id = get_current_user_id();
            if (($current_user_id === $site_id || current_user_can('manage_options')) && $this->verify_ajax_request()) {
                $this->get_form_contract_secret($site_id, true);
                return true;
            }
        }

        $secret = $this->get_form_contract_secret($site_id, false);
        if ($secret === '') {
            return new WP_Error('missing_form_contract', 'This form is not configured with a VMO security token yet.');
        }

        if ($this->verify_form_signature($site_id, $form_id, $secret) || $this->verify_form_contract_token($site_id, $form_id, $secret)) {
            return true;
        }

        return new WP_Error('invalid_form_contract', 'Invalid or expired form security token.');
    }

    private function get_requested_auto_reply_account(): string {
        $account = isset($_REQUEST['account']) ? sanitize_email(wp_unslash($_REQUEST['account'])) : '';
        return $account ?: '';
    }

    private function get_requested_auto_reply_mailbox_id(): int {
        return isset($_REQUEST['mailbox_id']) ? max(0, intval($_REQUEST['mailbox_id'])) : 0;
    }

    private function get_account_settings_map(int $uid): array {
        $settings = get_user_meta($uid, 'vmo_ai_auto_reply_account_settings', true);
        return is_array($settings) ? $settings : array();
    }

    private function get_auto_reply_setting_for_account(int $uid, string $account): array {
        $mode = get_user_meta($uid, 'vmo_ai_auto_reply_mode', true);
        if (!in_array($mode, ['draft_only', 'auto_send_safe', 'ask_every_reply'], true)) {
            $mode = 'draft_only';
        }

        if ($account === '') {
            return array(
                'enabled' => !empty(get_user_meta($uid, 'vmo_ai_auto_reply_enabled', true)) ? 1 : 0,
                'mode' => $mode,
            );
        }

        $settings = $this->get_account_settings_map($uid);
        if (!empty($settings[$account]) && is_array($settings[$account])) {
            $row_mode = isset($settings[$account]['mode']) ? sanitize_key((string) $settings[$account]['mode']) : $mode;
            if (!in_array($row_mode, ['draft_only', 'auto_send_safe', 'ask_every_reply'], true)) {
                $row_mode = $mode;
            }
            return array(
                'enabled' => !empty($settings[$account]['enabled']) ? 1 : 0,
                'mode' => $row_mode,
            );
        }

        return array('enabled' => 0, 'mode' => $mode);
    }

    private function resolve_account_for_email(int $uid, array $email): string {
        $mailbox_id = isset($email['mailbox_id']) ? intval($email['mailbox_id']) : 0;
        if ($mailbox_id > 0) {
            global $wpdb;
            $accounts_table = $wpdb->prefix . 'vmo_email_accounts';
            if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $accounts_table)) === $accounts_table) {
                $account = $wpdb->get_var($wpdb->prepare(
                    "SELECT email FROM {$accounts_table} WHERE user_id = %d AND id = %d LIMIT 1",
                    $uid,
                    $mailbox_id
                ));
                $account = $account ? sanitize_email((string) $account) : '';
                if ($account) return $account;
            }
        }

        $to_email = isset($email['to_email']) ? sanitize_email((string) $email['to_email']) : '';
        return $to_email ?: '';
    }

    private function email_matches_requested_account(int $uid, array $email, string $requested_account, int $requested_mailbox_id): bool {
        if ($requested_mailbox_id > 0) {
            $email_mailbox_id = isset($email['mailbox_id']) ? intval($email['mailbox_id']) : 0;
            if ($email_mailbox_id > 0 && $email_mailbox_id !== $requested_mailbox_id) {
                return false;
            }
        }

        if ($requested_account !== '') {
            $resolved = $this->resolve_account_for_email($uid, $email);
            if ($resolved === '') return false;
            return strcasecmp($resolved, $requested_account) === 0;
        }

        return true;
    }

    /* ═══════════════════════════════════════════
     *  8A — AI AUTO-REPLY ENGINE
     * ═══════════════════════════════════════════ */

    /**
     * AJAX: Scan recent inbox emails and generate auto-replies.
     * Called by the dashboard when the user visits the Emails tab.
     */
    public function ajax_process_auto_replies() {
        if (!$this->verify_ajax_request()) wp_send_json_error('Security check failed');
        $uid = get_current_user_id();
        if (!$uid) wp_send_json_error('Not logged in');
        $this->ensure_auto_reply_table();
        $requested_account = $this->get_requested_auto_reply_account();
        $requested_mailbox_id = $this->get_requested_auto_reply_mailbox_id();

        global $wpdb;
        $emails_table = $wpdb->prefix . 'vmo_emails';
        $auto_table   = $this->get_auto_reply_table();

        // Fetch unread inbox emails from last 24 hours that haven't been auto-replied to.
        // Account enablement is checked in PHP so older rows without mailbox_id can still be matched by to_email.
        $recent_emails = $wpdb->get_results($wpdb->prepare(
            "SELECT e.id, e.mailbox_id, e.from_email, e.to_email, e.subject, e.message, e.created_at
             FROM {$emails_table} e
             WHERE e.user_id = %d
               AND e.folder = 'inbox'
               AND e.is_read = 0
               AND e.created_at >= DATE_SUB(NOW(), INTERVAL 24 HOUR)
               AND NOT EXISTS (
                   SELECT 1 FROM {$auto_table} a 
                   WHERE a.user_id = %d AND a.trigger_value = e.id AND a.automation_type = 'auto_reply'
               )
             ORDER BY e.created_at DESC
             LIMIT 50",
            $uid, $uid
        ), ARRAY_A);

        $processable = array();
        foreach ($recent_emails as $email) {
            if (!$this->email_matches_requested_account($uid, $email, $requested_account, $requested_mailbox_id)) {
                continue;
            }
            $account = $this->resolve_account_for_email($uid, $email);
            $setting = $this->get_auto_reply_setting_for_account($uid, $account);
            if (empty($setting['enabled'])) {
                continue;
            }
            $email['_auto_reply_account'] = $account;
            $email['_auto_reply_mode'] = $setting['mode'] ?? 'draft_only';
            $processable[] = $email;
            if (count($processable) >= 10) {
                break;
            }
        }

        if (empty($processable)) {
            $message = $requested_account ? 'No new emails for this account, or Auto Reply is disabled for it.' : 'No new emails for accounts with Auto Reply enabled.';
            wp_send_json_success(['processed' => 0, 'queued' => 0, 'message' => $message]);
            return;
        }

        // Get business context for AI reply generation
        $business_context = $this->get_business_context($uid);
        $processed = 0;
        $queued = 0;
        $auto_sent = 0;

        foreach ($processable as $email) {
            $result = $this->process_single_email($email, $uid, $business_context, array(
                'mode' => $email['_auto_reply_mode'] ?? 'draft_only',
                'account' => $email['_auto_reply_account'] ?? '',
            ));
            if ($result) {
                $processed++;
                if ($result['action'] === 'auto_sent') $auto_sent++;
                if ($result['action'] === 'queued') $queued++;
            }
        }

        wp_send_json_success([
            'processed'  => $processed,
            'auto_sent'  => $auto_sent,
            'queued'     => $queued,
            'message'    => $processed > 0
                ? "{$auto_sent} auto-replied, {$queued} awaiting your approval"
                : 'No new emails to process',
        ]);
    }

    public function handle_inbound_email_saved($user_id, $mailbox_id, $email_id, $account = '', $email_data = array()) {
        $user_id = intval($user_id);
        $email_id = intval($email_id);
        if ($user_id <= 0 || $email_id <= 0) {
            return null;
        }
        if (function_exists('vmo_is_user_service_locked') && vmo_is_user_service_locked($user_id)) {
            return null;
        }
        return $this->process_email_by_id($user_id, $email_id, array(
            'mailbox_id' => intval($mailbox_id),
            'account' => sanitize_email((string) $account),
        ));
    }

    public function process_auto_replies_cron() {
        global $wpdb;
        $this->ensure_auto_reply_table();
        $emails_table = $wpdb->prefix . 'vmo_emails';
        $auto_table = $this->get_auto_reply_table();
        if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $emails_table)) !== $emails_table) {
            return array('processed' => 0, 'queued' => 0, 'auto_sent' => 0);
        }

        $rows = $wpdb->get_results(
            "SELECT e.id, e.user_id
             FROM {$emails_table} e
             WHERE e.folder = 'inbox'
               AND e.created_at >= DATE_SUB(NOW(), INTERVAL 3 DAY)
               AND NOT EXISTS (
                   SELECT 1 FROM {$auto_table} a
                   WHERE a.user_id = e.user_id AND a.trigger_value = e.id AND a.automation_type = 'auto_reply'
               )
             ORDER BY e.created_at ASC
             LIMIT 100",
            ARRAY_A
        );

        $summary = array('processed' => 0, 'queued' => 0, 'auto_sent' => 0);
        foreach (($rows ?: array()) as $row) {
            $result = $this->process_email_by_id(intval($row['user_id'] ?? 0), intval($row['id'] ?? 0));
            if (!$result) {
                continue;
            }
            $summary['processed']++;
            if (($result['action'] ?? '') === 'queued') {
                $summary['queued']++;
            } elseif (($result['action'] ?? '') === 'auto_sent') {
                $summary['auto_sent']++;
            }
        }

        return $summary;
    }

    public function process_email_by_id($uid, $email_id, $options = array()) {
        global $wpdb;
        $uid = intval($uid);
        $email_id = intval($email_id);
        if ($uid <= 0 || $email_id <= 0) {
            return null;
        }
        if (function_exists('vmo_is_user_service_locked') && vmo_is_user_service_locked($uid)) {
            return null;
        }
        $this->ensure_auto_reply_table();
        if ($this->auto_reply_exists_for_email($uid, $email_id)) {
            return null;
        }

        $emails_table = $wpdb->prefix . 'vmo_emails';
        $email = $wpdb->get_row($wpdb->prepare(
            "SELECT id, mailbox_id, from_email, to_email, subject, message, created_at
             FROM {$emails_table}
             WHERE user_id = %d AND id = %d AND folder = 'inbox'
             LIMIT 1",
            $uid,
            $email_id
        ), ARRAY_A);
        if (!$email) {
            return null;
        }

        $account = !empty($options['account']) ? sanitize_email((string) $options['account']) : $this->resolve_account_for_email($uid, $email);
        $setting = $this->get_auto_reply_setting_for_account($uid, $account);
        if (empty($setting['enabled'])) {
            return null;
        }

        $email['_auto_reply_account'] = $account;
        $email['_auto_reply_mode'] = $setting['mode'] ?? 'draft_only';
        return $this->process_single_email($email, $uid, $this->get_business_context($uid), array(
            'mode' => $email['_auto_reply_mode'],
            'account' => $account,
        ));
    }

    private function auto_reply_exists_for_email($uid, $email_id) {
        global $wpdb;
        $auto_table = $this->get_auto_reply_table();
        return (bool) $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$auto_table}
             WHERE user_id = %d AND automation_type = 'auto_reply' AND trigger_value = %s
             LIMIT 1",
            intval($uid),
            (string) intval($email_id)
        ));
    }

    /**
     * Process a single incoming email: classify → generate reply → queue or send.
     */
    private function process_single_email($email, $uid, $business_context, $auto_reply_setting = array()) {
        $this->ensure_auto_reply_table();
        // Step 1: Classify the email
        $classification = $this->classify_email($email, $business_context);
        if (!$classification) return null;

        $category = $classification['category'] ?? 'unknown';
        $confidence = floatval($classification['confidence'] ?? 0);
        $mode = isset($auto_reply_setting['mode']) ? sanitize_key((string) $auto_reply_setting['mode']) : get_user_meta($uid, 'vmo_ai_auto_reply_mode', true);
        if (!in_array($mode, ['draft_only', 'auto_send_safe', 'ask_every_reply'], true)) {
            $mode = 'draft_only';
        }

        // Step 2: Generate AI reply
        $reply = $this->generate_reply($email, $classification, $business_context);
        if (!$reply) return null;

        // Step 3: Decide action based on category and confidence
        $auto_send = ($mode === 'auto_send_safe')
            && in_array($category, self::$auto_send_categories, true)
            && $confidence >= 0.8
            && $this->is_non_binding_auto_reply($email, $classification, $business_context);
        $action = $auto_send ? 'auto_sent' : 'queued';

        global $wpdb;
        $auto_table = $this->get_auto_reply_table();

        // Store in the operational auto-reply approval queue.
        $wpdb->insert($auto_table, [
            'user_id'         => $uid,
            'mailbox_id'      => isset($email['mailbox_id']) ? intval($email['mailbox_id']) : null,
            'automation_type' => 'auto_reply',
            'trigger_type'    => 'incoming_email',
            'trigger_value'   => $email['id'],
            'action_type'     => $action,
            'action_data'     => wp_json_encode([
                'original_email_id' => intval($email['id'] ?? 0),
                'mailbox_id'      => isset($email['mailbox_id']) ? intval($email['mailbox_id']) : null,
                'account'         => sanitize_email($email['_auto_reply_account'] ?? $this->resolve_account_for_email($uid, $email)),
                'from_email'     => sanitize_email($email['from_email']),
                'original_subject' => sanitize_text_field($email['subject']),
                'category'       => $category,
                'confidence'     => $confidence,
                'reply_subject'  => sanitize_text_field($reply['subject']),
                'reply_body'     => wp_kses_post($reply['body']),
                'generated_at'   => current_time('mysql'),
            ]),
            'status'          => $auto_send ? 'completed' : 'pending',
            'created_at'      => current_time('mysql'),
            'updated_at'      => current_time('mysql'),
            'completed_at'    => $auto_send ? current_time('mysql') : null,
        ], ['%d', '%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s']);

        // Auto-send if confident enough
        if ($auto_send) {
            $this->send_auto_reply($email, $reply, $uid);
        } else {
            $this->create_pending_reply_draft($uid, (int) $wpdb->insert_id, $email, $reply);
            $this->create_auto_reply_action($uid, (int) $wpdb->insert_id, $email, $category);
            if (function_exists('vmo_log_unified_action')) {
                vmo_log_unified_action($uid, 'auto_reply_approval_required', [
                    'from_email' => $email['from_email'] ?? '',
                    'subject' => $email['subject'] ?? '',
                    'original_email_id' => intval($email['id'] ?? 0),
                    'mailbox_id' => isset($email['mailbox_id']) ? intval($email['mailbox_id']) : null,
                    'automation_id' => (int) $wpdb->insert_id,
                    'category' => $category,
                ]);
            }
        }

        return ['action' => $action, 'category' => $category];
    }

    private function create_pending_reply_draft($uid, $automation_id, $email, $reply) {
        if (!class_exists('VMO_Email_Storage')) {
            $storage_file = dirname(__FILE__) . '/class-vmo-email-storage.php';
            if (file_exists($storage_file) && is_readable($storage_file)) {
                require_once $storage_file;
            }
        }
        if (!class_exists('VMO_Email_Storage')) {
            return;
        }

        $storage = new VMO_Email_Storage();
        $account = $this->resolve_account_for_email($uid, is_array($email) ? $email : array());
        $storage->save_email([
            'user_id'     => $uid,
            'mailbox_id'  => isset($email['mailbox_id']) ? intval($email['mailbox_id']) : null,
            'folder'      => 'drafts',
            'type'        => 'transactional',
            'from_email'  => $account,
            'to_email'    => sanitize_email($email['from_email'] ?? ''),
            'subject'     => sanitize_text_field($reply['subject'] ?? ('Re: ' . ($email['subject'] ?? ''))),
            'message'     => wp_kses_post($reply['body'] ?? ''),
            'status'      => 'draft',
            'reply_to_email_id' => intval($email['id'] ?? 0),
            'is_read'     => 1,
            'is_ai_generated' => 1,
            'external_id' => 'auto_reply_automation_' . $automation_id,
        ]);
    }

    private function create_auto_reply_action($uid, $automation_id, $email, $category) {
        global $wpdb;
        $actions_table = $wpdb->prefix . 'vmo_actions';
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $wpdb->esc_like($actions_table))) !== $actions_table) {
            return;
        }

        $wpdb->insert($actions_table, [
            'user_id'     => $uid,
            'title'       => 'Approve AI email reply: ' . sanitize_text_field($email['subject'] ?? 'Incoming email'),
            'description' => 'VMO drafted an email reply that needs human approval before sending. Category: ' . sanitize_text_field($category),
            'source'      => 'email_report',
            'source_id'   => $automation_id,
            'priority'    => in_array($category, ['complaint', 'refund_request', 'legal', 'booking_request'], true) ? 'high' : 'normal',
            'category'    => 'follow-up',
            'status'      => 'pending',
            'due_date'    => current_time('Y-m-d'),
            'created_at'  => current_time('mysql'),
            'updated_at'  => current_time('mysql'),
        ]);
    }

    /**
     * Classify an incoming email using AI.
     */
    private function get_platform_faq_grounding_context(array $business_context, string $audience = 'email_auto_reply', int $max_chars = 8500): string {
        if (!function_exists('vmo_platform_faq_should_ground_current_site') || !function_exists('vmo_get_platform_faq_grounding_text')) {
            return '';
        }

        $business_name = (string) ($business_context['business_name'] ?? '');
        $website = (string) ($business_context['website'] ?? '');
        if (!vmo_platform_faq_should_ground_current_site($business_name, $website)) {
            return '';
        }

        return vmo_get_platform_faq_grounding_text($audience, $max_chars);
    }

    private function classify_email($email, $business_context) {
        if (!function_exists('vmo_openai_chat')) return null;

        $platform_faq = $this->get_platform_faq_grounding_context((array) $business_context, 'email_auto_reply_classify', 7500);

        $system = "You are an email classifier for a business. Classify the incoming email into one of these categories:\n"
            . "SAFE (auto-reply OK only when factual and non-binding): greeting, hours_inquiry, location_inquiry, product_inquiry, general_info, thank_you\n"
            . "NEEDS APPROVAL: pricing_inquiry, custom_pricing, availability_request, complaint, refund_request, partnership, legal, custom_order, support_issue, booking_request\n"
            . "SKIP (do not reply): spam, newsletter, automated, no_reply\n\n"
            . "Pricing or product-price questions require approval unless the message asks only for a fixed catalog product price or checkout link already present in business context. Booking dates, custom quotes, refunds, complaints, delivery promises, legal matters, and anything that commits the business always require approval.\n\n"
            . "Business: " . ($business_context['business_name'] ?? 'Unknown') . "\n"
            . "Industry: " . ($business_context['industry'] ?? 'General') . "\n\n"
            . ($platform_faq !== '' ? $platform_faq . "\n\n" : '')
            . "Respond ONLY with JSON: {\"category\": \"...\", \"confidence\": 0.0-1.0, \"skip\": true/false, \"reason\": \"...\"}";

        $user_msg = "From: " . sanitize_email($email['from_email']) . "\n"
            . "Subject: " . sanitize_text_field($email['subject']) . "\n"
            . "Body:\n" . wp_strip_all_tags(substr($email['message'] ?? '', 0, 1500));

        $model = function_exists('vmo_get_optimal_model') ? vmo_get_optimal_model('email_classification') : 'gpt-5.5-mini';

        $resp = vmo_openai_chat([
            ['role' => 'system', 'content' => $system],
            ['role' => 'user', 'content' => $user_msg],
        ], $model, ['temperature' => 0.1, 'max_tokens' => 200, 'timeout' => 15]);

        if (is_wp_error($resp)) return null;

        $data = json_decode(wp_remote_retrieve_body($resp), true);
        $raw = $data['choices'][0]['message']['content'] ?? '';
        $parsed = json_decode($raw, true);
        if (!is_array($parsed)) {
            // Try extracting JSON from markdown
            if (preg_match('/\{[^}]+\}/s', $raw, $m)) {
                $parsed = json_decode($m[0], true);
            }
        }

        if (!is_array($parsed) || !empty($parsed['skip'])) return null;
        return $parsed;
    }

    private function is_non_binding_auto_reply($email, $classification, $business_context) {
        $category = sanitize_key((string) ($classification['category'] ?? ''));
        $subject = wp_strip_all_tags((string) ($email['subject'] ?? ''));
        $body = wp_strip_all_tags((string) ($email['message'] ?? ''));
        $text = strtolower($subject . ' ' . $body);

        $binding_terms = array(
            'custom quote', 'quote me', 'can you do', 'could you do', 'will you do', 'for $',
            'discount', 'refund', 'complaint', 'cancel', 'contract', 'legal', 'lawsuit',
            'available', 'availability', 'book', 'booking', 'appointment', 'schedule', 'saturday', 'sunday',
            'deliver by', 'delivery included', 'guarantee', 'promise', 'confirm that', 'confirm this',
            'custom order', 'special order', 'bespoke', 'negotiate', 'price match'
        );
        foreach ($binding_terms as $term) {
            if (strpos($text, $term) !== false) {
                return false;
            }
        }

        if ($category === 'pricing_inquiry' || $category === 'custom_pricing' || $category === 'availability_request') {
            return false;
        }

        if ($category === 'product_inquiry') {
            $products = trim((string) ($business_context['products'] ?? ''));
            if ($products === '') {
                return false;
            }
        }

        return true;
    }

    /**
     * Generate an AI-powered reply to the incoming email.
     */
    private function generate_reply($email, $classification, $business_context) {
        if (!function_exists('vmo_openai_chat')) return null;

        $bname = $business_context['business_name'] ?? 'Our Team';
        $platform_faq = $this->get_platform_faq_grounding_context((array) $business_context, 'email_auto_reply_generate', 9000);
        $system = "You are a professional, friendly business assistant replying on behalf of \"{$bname}\".\n"
            . "Write a helpful, warm reply to the incoming email. Keep it concise (2-4 paragraphs).\n"
            . "Be professional but approachable. Include relevant business information when helpful.\n\n"
            . "Use approved FAQ/business context first for product, pricing, capability, plan, hosted/direct, and policy questions. If VMO FAQ SOURCE OF TRUTH is present, it wins over any weaker website text or generic assumption. Do not invent details. If asked whether VMO can build a website from scratch, answer yes.\n\n"
            . "BUSINESS CONTEXT:\n"
            . "Name: {$bname}\n"
            . "Industry: " . ($business_context['industry'] ?? '') . "\n"
            . "Services: " . ($business_context['services'] ?? '') . "\n"
            . "Hours: " . ($business_context['hours'] ?? 'Monday-Friday 9am-5pm') . "\n"
            . "Phone: " . ($business_context['phone'] ?? '') . "\n"
            . "Email: " . ($business_context['email'] ?? '') . "\n"
            . "Address: " . ($business_context['address'] ?? '') . "\n\n"
            . "Website: " . ($business_context['website'] ?? home_url('/')) . "\n"
            . "Products/prices: " . ($business_context['products'] ?? '') . "\n\n"
            . ($platform_faq !== '' ? $platform_faq . "\n\n" : '')
            . "Email category: " . ($classification['category'] ?? 'general') . "\n\n"
            . "Respond with JSON: {\"subject\": \"Re: ...\", \"body\": \"<html reply body>\"}";

        $user_msg = "Reply to this email:\n\n"
            . "From: " . sanitize_email($email['from_email']) . "\n"
            . "Subject: " . sanitize_text_field($email['subject']) . "\n"
            . "Body:\n" . wp_strip_all_tags(substr($email['message'] ?? '', 0, 2000));

        $model = function_exists('vmo_get_optimal_model') ? vmo_get_optimal_model('email_generation') : 'gpt-5.5-mini';

        $resp = vmo_openai_chat([
            ['role' => 'system', 'content' => $system],
            ['role' => 'user', 'content' => $user_msg],
        ], $model, ['temperature' => 0.5, 'max_tokens' => 800, 'timeout' => 25]);

        if (is_wp_error($resp)) return null;

        $data = json_decode(wp_remote_retrieve_body($resp), true);
        $raw = $data['choices'][0]['message']['content'] ?? '';
        $parsed = json_decode($raw, true);
        if (!is_array($parsed)) {
            if (preg_match('/\{.*\}/s', $raw, $m)) {
                $parsed = json_decode($m[0], true);
            }
        }

        if (!is_array($parsed) || empty($parsed['body'])) return null;
        if (empty($parsed['subject'])) {
            $parsed['subject'] = 'Re: ' . sanitize_text_field($email['subject']);
        }
        return $parsed;
    }

    /**
     * Send an auto-generated reply via the existing email system.
     */
    private function send_auto_reply($original_email, $reply, $uid) {
        $from_email = $this->resolve_account_for_email($uid, is_array($original_email) ? $original_email : array());

        // Use email router if available
        if (!class_exists('VMO_Email_Router')) {
            $router_file = dirname(__FILE__) . '/class-vmo-email-router.php';
            if (file_exists($router_file) && is_readable($router_file)) {
                require_once $router_file;
            }
        }

        if (class_exists('VMO_Email_Router')) {
            $router = VMO_Email_Router::get_instance();
            $result = $router->send_email(
                sanitize_email($original_email['from_email']),
                sanitize_text_field($reply['subject']),
                wp_kses_post($reply['body']),
                'transactional',
                [
                    'user_id' => $uid,
                    'context' => 'ai_auto_reply',
                    'reply_to_email_id' => intval($original_email['id'] ?? 0),
                    'mailbox_id' => isset($original_email['mailbox_id']) ? intval($original_email['mailbox_id']) : null,
                    'from_email' => $from_email,
                    'skip_storage' => true,
                ]
            );
            $sent = is_array($result) ? !empty($result['success']) : (bool) $result;
        } else {
            $headers = ['Content-Type: text/html; charset=UTF-8'];
            if ($from_email) {
                $headers[] = sprintf('From: %s', $from_email);
                $headers[] = sprintf('Reply-To: %s', $from_email);
            }
            $sent = wp_mail(
                sanitize_email($original_email['from_email']),
                sanitize_text_field($reply['subject']),
                wp_kses_post($reply['body']),
                $headers
            );
        }

        // Store in sent folder
        if (!class_exists('VMO_Email_Storage')) {
            $storage_file = dirname(__FILE__) . '/class-vmo-email-storage.php';
            if (file_exists($storage_file) && is_readable($storage_file)) {
                require_once $storage_file;
            }
        }
        if ($sent && class_exists('VMO_Email_Storage')) {
            $storage = new VMO_Email_Storage();
            $storage->save_email([
                'user_id'     => $uid,
                'folder'      => 'sent',
                'type'        => 'transactional',
                'mailbox_id'  => isset($original_email['mailbox_id']) ? intval($original_email['mailbox_id']) : null,
                'from_email'  => $from_email,
                'to_email'    => sanitize_email($original_email['from_email']),
                'subject'     => sanitize_text_field($reply['subject']),
                'message'     => wp_kses_post($reply['body']),
                'status'      => 'sent',
                'reply_to_email_id' => intval($original_email['id'] ?? 0),
                'is_ai_generated' => 1,
            ]);
        }

        // Log to CRM unified actions
        if (function_exists('vmo_log_unified_action')) {
            vmo_log_unified_action($uid, 'auto_reply_sent', [
                'to_email' => $original_email['from_email'],
                'subject'  => $reply['subject'],
            ]);
        }

        return $sent;
    }

    /**
     * AJAX: Get pending auto-reply queue for user approval.
     */
    public function ajax_get_queue() {
        if (!$this->verify_ajax_request()) wp_send_json_error('Security check failed');
        $uid = get_current_user_id();
        if (!$uid) wp_send_json_error('Not logged in');

        global $wpdb;
        $table = $this->get_auto_reply_table();
        $requested_account = $this->get_requested_auto_reply_account();
        $requested_mailbox_id = $this->get_requested_auto_reply_mailbox_id();

        $pending = $wpdb->get_results($wpdb->prepare(
            "SELECT id, action_data, created_at 
             FROM {$table}
             WHERE user_id = %d AND automation_type = 'auto_reply' AND status = 'pending'
             ORDER BY created_at DESC
             LIMIT 20",
            $uid
        ), ARRAY_A);

        $queue = [];
        foreach ($pending as $row) {
            $data = json_decode($row['action_data'], true);
            if (!is_array($data)) continue;
            $mailbox_id = isset($data['mailbox_id']) ? intval($data['mailbox_id']) : 0;
            if (!$this->email_matches_requested_account($uid, array(
                'mailbox_id' => $mailbox_id,
                'to_email' => isset($data['account']) ? sanitize_email((string) $data['account']) : '',
            ), $requested_account, $requested_mailbox_id)) {
                continue;
            }
            $queue[] = [
                'id'               => intval($row['id']),
                'original_email_id'=> intval($data['original_email_id'] ?? 0),
                'mailbox_id'       => $mailbox_id ?: null,
                'from_email'       => $data['from_email'] ?? '',
                'original_subject' => $data['original_subject'] ?? '',
                'category'         => $data['category'] ?? '',
                'reply_subject'    => $data['reply_subject'] ?? '',
                'reply_body'       => $data['reply_body'] ?? '',
                'generated_at'     => $data['generated_at'] ?? $row['created_at'],
            ];
        }

        wp_send_json_success(['queue' => $queue, 'count' => count($queue)]);
    }

    /**
     * AJAX: Approve and send a queued auto-reply.
     */
    public function ajax_approve_reply() {
        if (!$this->verify_ajax_request()) wp_send_json_error('Security check failed');
        $uid = get_current_user_id();
        if (!$uid) wp_send_json_error('Not logged in');

        $reply_id = intval($_POST['reply_id'] ?? 0);
        if (!$reply_id) wp_send_json_error('Invalid reply ID');

        global $wpdb;
        $table = $this->get_auto_reply_table();

        $row = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$table} WHERE id = %d AND user_id = %d AND status = 'pending'",
            $reply_id, $uid
        ), ARRAY_A);

        if (!$row) wp_send_json_error('Reply not found or already processed');

        $data = json_decode($row['action_data'], true);
        if (!is_array($data) || empty($data['reply_body'])) {
            wp_send_json_error('Invalid reply data');
        }

        // Allow user to edit the reply body before sending
        $edited_body = isset($_POST['edited_body']) ? wp_kses_post(wp_unslash($_POST['edited_body'])) : $data['reply_body'];
        $edited_subject = isset($_POST['edited_subject']) ? sanitize_text_field(wp_unslash($_POST['edited_subject'])) : $data['reply_subject'];

        // Send the reply
        $fake_email = [
            'id'         => intval($data['original_email_id'] ?? $row['trigger_value'] ?? 0),
            'mailbox_id' => isset($data['mailbox_id']) ? intval($data['mailbox_id']) : null,
            'to_email'   => isset($data['account']) ? sanitize_email((string) $data['account']) : '',
            'from_email' => $data['from_email'],
            'subject'    => $data['original_subject'],
        ];
        $reply = [
            'subject' => $edited_subject,
            'body'    => $edited_body,
        ];

        $sent = $this->send_auto_reply($fake_email, $reply, $uid);

        // Update status
        $wpdb->update($table, [
            'status'     => 'completed',
            'action_type' => 'approved_sent',
            'updated_at' => current_time('mysql'),
            'completed_at' => current_time('mysql'),
        ], ['id' => $reply_id], ['%s', '%s', '%s', '%s'], ['%d']);

        wp_send_json_success(['sent' => (bool) $sent]);
    }

    /**
     * AJAX: Dismiss (skip) a queued auto-reply.
     */
    public function ajax_dismiss_reply() {
        if (!$this->verify_ajax_request()) wp_send_json_error('Security check failed');
        $uid = get_current_user_id();
        if (!$uid) wp_send_json_error('Not logged in');

        $reply_id = intval($_POST['reply_id'] ?? 0);
        if (!$reply_id) wp_send_json_error('Invalid reply ID');

        global $wpdb;
        $table = $this->get_auto_reply_table();
        $wpdb->update($table, [
            'status' => 'dismissed',
            'updated_at' => current_time('mysql'),
        ], ['id' => $reply_id, 'user_id' => $uid], ['%s', '%s'], ['%d', '%d']);

        wp_send_json_success(['dismissed' => true]);
    }

    /**
     * Get business context from consultation profile for AI reply generation.
     */
    private function get_business_context($uid) {
        $ctx = ['business_name' => get_bloginfo('name'), 'website' => home_url('/')];

        if (function_exists('vmo_get_consultation_profile')) {
            $profile = vmo_get_consultation_profile($uid);
            $ext = is_array($profile['extracted_information'] ?? null) ? $profile['extracted_information'] : [];

            foreach (['business_name', 'businessName', 'company_name'] as $k) {
                if (!empty($ext[$k])) { $ctx['business_name'] = sanitize_text_field($ext[$k]); break; }
            }
            foreach (['industry', 'business_type', 'niche'] as $k) {
                if (!empty($ext[$k])) { $ctx['industry'] = sanitize_text_field($ext[$k]); break; }
            }
            foreach (['services', 'offerings', 'products'] as $k) {
                if (!empty($ext[$k])) {
                    $ctx['services'] = is_array($ext[$k]) ? implode(', ', $ext[$k]) : sanitize_text_field($ext[$k]);
                    break;
                }
            }
            foreach (['business_phone', 'phone', 'supportPhone'] as $k) {
                if (!empty($ext[$k])) { $ctx['phone'] = sanitize_text_field($ext[$k]); break; }
            }
            foreach (['business_email', 'email', 'supportEmail'] as $k) {
                if (!empty($ext[$k])) { $ctx['email'] = sanitize_email($ext[$k]); break; }
            }
            foreach (['address', 'business_address', 'location'] as $k) {
                if (!empty($ext[$k])) { $ctx['address'] = sanitize_text_field($ext[$k]); break; }
            }
            foreach (['business_hours', 'hours', 'operating_hours'] as $k) {
                if (!empty($ext[$k])) { $ctx['hours'] = sanitize_text_field($ext[$k]); break; }
            }
        }

        global $wpdb;
        $products_table = $wpdb->prefix . 'vmo_store_products';
        if ($wpdb->get_var($wpdb->prepare('SHOW TABLES LIKE %s', $products_table)) === $products_table) {
            $rows = $wpdb->get_results($wpdb->prepare(
                "SELECT name, description, price_cents, currency
                 FROM {$products_table}
                 WHERE user_id = %d AND status = 'active'
                 ORDER BY created_at DESC
                 LIMIT 12",
                $uid
            ), ARRAY_A);
            if ($rows) {
                $products = array();
                foreach ($rows as $row) {
                    $name = sanitize_text_field($row['name'] ?? '');
                    if ($name === '') continue;
                    $currency = strtoupper(sanitize_text_field($row['currency'] ?: 'USD'));
                    $price = $currency . ' ' . number_format(((int) ($row['price_cents'] ?? 0)) / 100, 2);
                    $description = wp_strip_all_tags((string) ($row['description'] ?? ''));
                    $products[] = trim($name . ' - ' . $price . ($description ? ' - ' . substr($description, 0, 140) : ''));
                }
                if ($products) {
                    $ctx['products'] = implode('; ', $products);
                }
            }
        }

        return $ctx;
    }

    /* ═══════════════════════════════════════════
     *  8B — PRODUCT / CHECKOUT BLOCK INSERTION
     * ═══════════════════════════════════════════ */

    /**
     * AJAX: Get available products for email insertion from VMO Pay / Store.
     */
    public function ajax_get_products_for_email() {
        if (!$this->verify_ajax_request()) wp_send_json_error('Security check failed');
        $uid = get_current_user_id();
        if (!$uid) wp_send_json_error('Not logged in');

        $products = [];
        global $wpdb;
        $products_table = $wpdb->prefix . 'vmo_store_products';
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $wpdb->esc_like($products_table))) === $products_table) {
            $rows = $wpdb->get_results($wpdb->prepare(
                "SELECT id, name, description, price_cents, currency, images
                 FROM {$products_table}
                 WHERE user_id = %d AND status = 'active'
                 ORDER BY created_at DESC LIMIT 20",
                $uid
            ), ARRAY_A);
            foreach (($rows ?: []) as $row) {
                $images = [];
                if (!empty($row['images'])) {
                    $decoded = json_decode($row['images'], true);
                    if (is_array($decoded)) {
                        $images = array_values(array_filter(array_map('esc_url_raw', $decoded)));
                    }
                }
                $currency = strtoupper(sanitize_text_field($row['currency'] ?: 'USD'));
                $products[] = [
                    'source'  => 'vmo_pay',
                    'id'      => intval($row['id']),
                    'name'    => sanitize_text_field($row['name']),
                    'description' => wp_strip_all_tags((string) ($row['description'] ?? '')),
                    'price'   => $currency . ' ' . number_format(((int) $row['price_cents']) / 100, 2),
                    'currency' => $currency,
                    'url'     => esc_url(add_query_arg(['vmo_buy_product' => intval($row['id'])], home_url('/'))),
                    'image'   => $images[0] ?? '',
                ];
            }
        }

        wp_send_json_success(['products' => $products]);
    }

    /**
     * AJAX: Generate product block HTML for email insertion.
     */
    public function ajax_insert_product_block() {
        if (!$this->verify_ajax_request()) wp_send_json_error('Security check failed');
        $uid = get_current_user_id();
        if (!$uid) wp_send_json_error('Not logged in');

        $selected = json_decode(wp_unslash($_POST['products'] ?? '[]'), true);
        if (!is_array($selected) || empty($selected)) {
            wp_send_json_error('No products selected');
        }

        // Build inline-styled product cards (email-safe)
        $html = '<div style="margin:24px 0;">';
        $html .= '<table cellpadding="0" cellspacing="0" border="0" width="100%" style="border-collapse:collapse;">';
        $html .= '<tr>';

        $col = 0;
        foreach (array_slice($selected, 0, 4) as $product) {
            if ($col > 0 && $col % 2 === 0) {
                $html .= '</tr><tr>';
            }

            $name  = esc_html(sanitize_text_field($product['name'] ?? 'Product'));
            $price = esc_html(sanitize_text_field($product['price'] ?? ''));
            $desc  = esc_html(sanitize_text_field($product['description'] ?? ''));
            $url   = esc_url($product['url'] ?? '#');
            $img   = esc_url($product['image'] ?? '');

            $html .= '<td width="50%" valign="top" style="padding:8px;">';
            $html .= '<div style="background:#f8f9fa;border-radius:12px;padding:16px;text-align:center;border:1px solid #e2e8f0;">';
            if ($img) {
                $html .= '<img src="' . $img . '" alt="' . $name . '" width="120" height="120" style="border-radius:8px;object-fit:cover;margin-bottom:10px;" />';
            }
            $html .= '<h3 style="margin:0 0 6px;font-size:16px;color:#1a1a2e;">' . $name . '</h3>';
            if ($desc) {
                $html .= '<p style="margin:0 0 8px;font-size:13px;color:#666;">' . $desc . '</p>';
            }
            if ($price) {
                $html .= '<p style="margin:0 0 10px;font-size:18px;font-weight:700;color:#0ea5e9;">' . $price . '</p>';
            }
            $html .= '<a href="' . $url . '" style="display:inline-block;padding:10px 24px;background:linear-gradient(135deg,#0fe1ff,#7c5cff);color:#fff;text-decoration:none;border-radius:8px;font-weight:600;font-size:14px;">Buy Now</a>';
            $html .= '</div>';
            $html .= '</td>';
            $col++;
        }

        // Fill remaining cells for 2-col layout
        if ($col % 2 !== 0) {
            $html .= '<td width="50%"></td>';
        }
        $html .= '</tr></table></div>';

        wp_send_json_success(['html' => $html]);
    }

    /* ═══════════════════════════════════════════
     *  8C — FORM → MAILBOX ROUTING
     * ═══════════════════════════════════════════ */

    /**
     * AJAX: Handle form submissions from VMO-built websites.
     * Routes form data into the business owner's email inbox.
     */
    public function ajax_handle_form_submission() {
        $site_id = intval($_POST['site_owner'] ?? 0);
        if (!$site_id) {
            // Try nonce verification for logged-in submissions
            if (is_user_logged_in()) {
                $site_id = get_current_user_id();
            } else {
                wp_send_json_error(['message' => 'Invalid form submission']);
                return;
            }
        }

        if (function_exists('vmo_is_user_service_locked') && vmo_is_user_service_locked($site_id)) {
            wp_send_json_error(['message' => 'This inbox is paused until billing is resolved.'], 403);
            return;
        }

        $form_type = sanitize_key($_POST['form_type'] ?? 'contact');
        $contract_status = $this->verify_form_submission_contract($site_id, $form_type);
        if (is_wp_error($contract_status)) {
            wp_send_json_error(['message' => $contract_status->get_error_message()], 403);
            return;
        }

        // Rate limit: max 20 submissions per IP per hour
        $ip = sanitize_text_field($_SERVER['REMOTE_ADDR'] ?? '');
        $rate_key = 'vmo_form_rate_' . md5($ip);
        $count = intval(get_transient($rate_key));
        if ($count >= 20) {
            wp_send_json_error(['message' => 'Too many submissions. Please try again later.']);
            return;
        }
        set_transient($rate_key, $count + 1, HOUR_IN_SECONDS);

        // Collect form data
        $form_data  = isset($_POST['form_data']) ? json_decode(wp_unslash($_POST['form_data']), true) : [];
        if (!is_array($form_data)) $form_data = [];

        // Sanitize all form data
        $clean_data = [];
        foreach ($form_data as $key => $val) {
            $clean_key = sanitize_key($key);
            $clean_data[$clean_key] = sanitize_textarea_field($val);
        }

        $sender_name  = $clean_data['name'] ?? $clean_data['full_name'] ?? $clean_data['first_name'] ?? 'Website Visitor';
        $sender_email = sanitize_email($clean_data['email'] ?? $clean_data['email_address'] ?? '');
        $sender_phone = sanitize_text_field($clean_data['phone'] ?? $clean_data['phone_number'] ?? '');
        $subject_line = sanitize_text_field($clean_data['subject'] ?? '');
        $message_body = sanitize_textarea_field($clean_data['message'] ?? $clean_data['comments'] ?? $clean_data['inquiry'] ?? '');

        // Build email subject based on form type
        $type_labels = [
            'contact'    => 'Contact Form',
            'newsletter' => 'Newsletter Signup',
            'appointment' => 'Appointment Request',
            'feedback'   => 'Feedback',
            'quote'      => 'Quote Request',
            'support'    => 'Support Request',
            'booking'    => 'Booking Request',
        ];
        $type_label = $type_labels[$form_type] ?? ucfirst(str_replace('_', ' ', $form_type));
        $email_subject = $subject_line ?: "[{$type_label}] from {$sender_name}";

        // Build rich HTML email body
        $email_body = $this->build_form_email_body($type_label, $sender_name, $sender_email, $sender_phone, $clean_data);

        // Determine mailbox routing
        $mailbox_id = $this->resolve_mailbox_for_form($form_type, $site_id);

        // Store in inbox
        if (!class_exists('VMO_Email_Storage')) {
            $storage_file = dirname(__FILE__) . '/class-vmo-email-storage.php';
            if (file_exists($storage_file) && is_readable($storage_file)) {
                require_once $storage_file;
            }
        }
        if (class_exists('VMO_Email_Storage')) {
            $storage = new VMO_Email_Storage();
            $storage->save_email([
                'user_id'     => $site_id,
                'mailbox_id'  => $mailbox_id,
                'folder'      => 'inbox',
                'type'        => 'transactional',
                'from_email'  => $sender_email ?: 'visitor@' . wp_parse_url(home_url(), PHP_URL_HOST),
                'to_email'    => '', // owner's inbox
                'subject'     => $email_subject,
                'message'     => $email_body,
                'is_read'     => 0,
            ]);
        }

        // Create CRM contact if email or phone provided
        if (($sender_email || $sender_phone) && function_exists('vmo_upsert_contact')) {
            $contact_id = vmo_upsert_contact($site_id, [
                'name'   => $sender_name,
                'email'  => $sender_email,
                'phone'  => $sender_phone,
                'source' => 'website_form',
                'primary_category' => 'lead',
                'lifecycle_stage' => 'new',
                'tags'   => $form_type . ',website_form',
                'notes'  => wp_strip_all_tags($email_body),
            ]);
            if ($contact_id && function_exists('vmo_crm_log_interaction')) {
                vmo_crm_log_interaction((int) $site_id, $contact_id, [
                    'interaction_type' => 'email',
                    'subtype' => 'form_' . sanitize_key($form_type),
                    'direction' => 'inbound',
                    'subject' => $email_subject,
                    'summary' => wp_strip_all_tags($email_body),
                    'outcome' => 'needs_follow_up',
                    'metadata' => [
                        'form_type' => $form_type,
                        'mailbox_id' => $mailbox_id,
                    ],
                ]);
            }
        }

        // Notify business owner via WordPress admin email
        $owner_email = get_the_author_meta('user_email', $site_id);
        if ($owner_email) {
            wp_mail(
                $owner_email,
                $email_subject,
                $email_body,
                ['Content-Type: text/html; charset=UTF-8']
            );
        }

        // Log to unified actions
        if (function_exists('vmo_log_unified_action')) {
            vmo_log_unified_action($site_id, 'form_submission', [
                'form_type' => $form_type,
                'sender'    => $sender_name,
                'email'     => $sender_email,
            ]);
        }

        wp_send_json_success([
            'message' => 'Thank you! Your message has been received.',
            'form_type' => $form_type,
        ]);
    }

    /**
     * Build a nicely formatted HTML email from form submission data.
     */
    private function build_form_email_body($type_label, $name, $email, $phone, $data) {
        $html = '<div style="font-family:-apple-system,BlinkMacSystemFont,\'Segoe UI\',Roboto,sans-serif;max-width:600px;margin:0 auto;">';
        $html .= '<div style="background:linear-gradient(135deg,#0fe1ff,#7c5cff);padding:20px;border-radius:12px 12px 0 0;">';
        $html .= '<h2 style="margin:0;color:#fff;font-size:20px;">📬 New ' . esc_html($type_label) . '</h2>';
        $html .= '</div>';
        $html .= '<div style="background:#fff;padding:24px;border:1px solid #e2e8f0;border-top:0;border-radius:0 0 12px 12px;">';

        // Contact info
        $html .= '<div style="margin-bottom:16px;padding-bottom:16px;border-bottom:1px solid #f0f0f0;">';
        $html .= '<strong style="color:#1a1a2e;">From:</strong> ' . esc_html($name);
        if ($email) $html .= ' &lt;' . esc_html($email) . '&gt;';
        if ($phone) $html .= '<br/><strong style="color:#1a1a2e;">Phone:</strong> ' . esc_html($phone);
        $html .= '</div>';

        // All form fields
        foreach ($data as $key => $val) {
            if (in_array($key, ['name', 'full_name', 'first_name', 'email', 'email_address', 'phone', 'phone_number'])) continue;
            if (empty($val)) continue;
            $label = ucfirst(str_replace(['_', '-'], ' ', $key));
            $html .= '<p style="margin:8px 0;"><strong style="color:#1a1a2e;">' . esc_html($label) . ':</strong><br/>' . nl2br(esc_html($val)) . '</p>';
        }

        $html .= '<hr style="border:0;border-top:1px solid #e2e8f0;margin:16px 0;">';
        $html .= '<p style="font-size:12px;color:#999;">Submitted via VMO Website • ' . esc_html(current_time('F j, Y g:i A')) . '</p>';
        if ($email) {
            $html .= '<a href="mailto:' . esc_attr($email) . '" style="display:inline-block;padding:10px 20px;background:#0ea5e9;color:#fff;text-decoration:none;border-radius:6px;font-weight:600;margin-top:8px;">Reply to ' . esc_html($name) . '</a>';
        }
        $html .= '</div></div>';

        return $html;
    }

    /**
     * Resolve which mailbox a form submission should be routed to.
     */
    private function resolve_mailbox_for_form($form_type, $user_id) {
        // Route map: form type → mailbox role
        $route_map = [
            'contact'     => 'info',
            'support'     => 'support',
            'quote'       => 'sales',
            'booking'     => 'booking',
            'appointment' => 'booking',
            'feedback'    => 'info',
            'newsletter'  => 'marketing',
        ];

        $role = $route_map[$form_type] ?? 'info';

        global $wpdb;
        $accounts_table = $wpdb->prefix . 'vmo_email_accounts';
        if (function_exists('vmo_ensure_email_accounts_table')) {
            vmo_ensure_email_accounts_table();
        }

        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $accounts_table)) === $accounts_table) {
            $role_fallbacks = [
                'booking' => ['booking', 'appointments', 'sales', 'info', 'general', 'primary'],
                'marketing' => ['marketing', 'newsletter', 'info', 'general', 'primary'],
                'support' => ['support', 'customer_care', 'customercare', 'info', 'general', 'primary'],
                'sales' => ['sales', 'info', 'general', 'primary'],
                'billing' => ['billing', 'transactions', 'info', 'general', 'primary'],
                'info' => ['info', 'general', 'primary'],
            ];
            $candidate_roles = $role_fallbacks[$role] ?? [$role, 'info', 'general', 'primary'];
            $candidate_roles = array_values(array_unique(array_map('sanitize_key', $candidate_roles)));

            foreach ($candidate_roles as $candidate_role) {
                $mailbox_id = $wpdb->get_var($wpdb->prepare(
                    "SELECT id FROM {$accounts_table}
                     WHERE user_id = %d
                       AND (role = %s OR category = %s)
                       AND (status IS NULL OR status = '' OR status = 'active')
                     ORDER BY verified DESC, id ASC
                     LIMIT 1",
                    $user_id,
                    $candidate_role,
                    $candidate_role
                ));
                if ($mailbox_id) {
                    return intval($mailbox_id);
                }
            }

            $identity_table = $wpdb->prefix . 'vmo_email_sender_identities';
            if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $identity_table)) === $identity_table) {
                $identity_email = $wpdb->get_var($wpdb->prepare(
                    "SELECT email_address FROM {$identity_table} WHERE user_id = %d AND email_role = %s LIMIT 1",
                    $user_id,
                    $role
                ));
                if (!$identity_email) {
                    $identity_email = $wpdb->get_var($wpdb->prepare(
                        "SELECT email_address FROM {$identity_table} WHERE user_id = %d AND is_primary = 1 LIMIT 1",
                        $user_id
                    ));
                }
                $identity_email = sanitize_email((string) $identity_email);
                if ($identity_email) {
                    $mailbox_id = $wpdb->get_var($wpdb->prepare(
                        "SELECT id FROM {$accounts_table}
                         WHERE user_id = %d AND (email = %s OR email_address = %s)
                         LIMIT 1",
                        $user_id,
                        $identity_email,
                        $identity_email
                    ));
                    if ($mailbox_id) {
                        return intval($mailbox_id);
                    }
                }
            }
        }

        return 0; // default mailbox
    }
}
