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

/**
 * Centralizes sender identity lookups and signature generation so the rest of the
 * plugin can treat domain-based email addresses as a first-class feature.
 */
class VMO_Email_Identity_Manager {
    private $table;
    private $profiles_table;
    private $wpdb;
    private $fallback_sender = [
        'email' => '',
        'name' => 'Virtual Media Office',
        'role' => 'system'
    ];

    public function __construct() {
        global $wpdb;
        $this->wpdb = $wpdb;
        $this->table = $wpdb->prefix . 'vmo_email_sender_identities';
        $this->profiles_table = $wpdb->prefix . 'vmo_business_profiles';

        // Set fallback sender email from options with admin_email as default
        $this->fallback_sender['email'] = get_option('vmo_fallback_sender_email', get_option('admin_email'));
    }

    /**
     * Returns the best sender for a campaign, preferring the requested role.
     */
    public function get_sender_for_campaign($user_id, $requested_role = 'marketing') {
        $role = $requested_role ? sanitize_key($requested_role) : 'marketing';
        $identity = $this->get_identity_by_role($user_id, $role);
        if (!$identity) {
            $identity = $this->get_any_verified_identity($user_id);
        }

        $profile = $this->get_business_profile($user_id);
        $business_name = $this->resolve_business_name($profile);
        $sender_name = $identity['display_name'] ?? $business_name;
        if (!$sender_name) {
            $sender_name = $this->fallback_sender['name'];
        }

        $sender_email = $identity['email_address'] ?? $this->fallback_sender['email'];
        $signature = $this->build_signature_block($profile, $identity);

        return [
            'email' => $sender_email,
            'name' => $sender_name,
            'role' => $identity['email_role'] ?? $this->fallback_sender['role'],
            'reply_to' => $sender_email,
            'signature' => $signature,
            'identity' => $identity
        ];
    }

    /**
     * Appends the generated signature block to HTML emails exactly once.
     */
    public function append_signature_to_html($html, $signature_html) {
        if (!$signature_html || strpos($html, 'vmo-email-signature') !== false) {
            return $html;
        }

        if (stripos($html, '</body>') !== false) {
            return preg_replace('/<\/body>/i', $signature_html . '</body>', $html, 1);
        }

        return $html . $signature_html;
    }

    /**
     * Builds the signature block + disclaimer based on the business profile.
     */
    private function build_signature_block($profile, $identity = null) {
        $user_id = isset($profile['user_id']) ? $profile['user_id'] : get_current_user_id();
        
        // Try to fetch custom signature
        $sig_table = $this->wpdb->prefix . 'vmo_email_signatures';
        // Check if table exists first to avoid errors during setup
        if ($this->table_exists($sig_table)) {
            $account = '';
            if (is_array($identity) && !empty($identity['email_address'])) {
                $account = sanitize_email($identity['email_address']);
            }
            if (!$account) {
                $account = 'default';
            }

            $custom_sig = $this->wpdb->get_row(
                $this->wpdb->prepare("SELECT * FROM $sig_table WHERE user_id = %d AND account = %s", $user_id, $account),
                ARRAY_A
            );

            if (!$custom_sig && $account !== 'default') {
                $custom_sig = $this->wpdb->get_row(
                    $this->wpdb->prepare("SELECT * FROM $sig_table WHERE user_id = %d AND account = %s", $user_id, 'default'),
                    ARRAY_A
                );
            }

            if ($custom_sig) {
                // Use Custom Signature
                $name = $custom_sig['name'];
                $role = $custom_sig['designation'];
                $color = $custom_sig['theme_color'] ?: '#000000';
                $logo = $custom_sig['logo_url'];
                $website = $custom_sig['website_url'];
                $socials = json_decode($custom_sig['social_links'], true) ?: [];
                
                // Build HTML Footer Style
                $html = '<div class="vmo-email-signature" style="margin-top:30px; padding: 20px; background-color: #f8f9fa; border-top: 3px solid ' . esc_attr($color) . '; font-family: Arial, sans-serif;">';
                
                $html .= '<table width="100%" border="0" cellspacing="0" cellpadding="0"><tr>';
                
                // Left Column: Logo & Name
                $html .= '<td valign="top" style="padding-right: 20px;">';
                if ($logo) {
                    $html .= '<img src="' . esc_url($logo) . '" alt="Logo" style="max-height: 40px; max-width: 140px; width: auto; height: auto; object-fit: contain; margin-bottom: 10px; display: block;">';
                }
                $html .= '<div style="font-size: 18px; font-weight: bold; color: #333;">' . esc_html($name) . '</div>';
                if ($role) {
                    $html .= '<div style="font-size: 14px; color: ' . esc_attr($color) . '; font-weight: 600;">' . esc_html($role) . '</div>';
                }
                $html .= '</td>';
                
                // Right Column: Contact & Socials
                $html .= '<td valign="top" align="right" style="font-size: 13px; color: #555; line-height: 1.6;">';
                if ($website) {
                    $html .= '🌐 <a href="' . esc_url($website) . '" style="color: #333; text-decoration: none; font-weight: bold;">' . esc_html(str_replace(['http://', 'https://'], '', $website)) . '</a><br>';
                }
                if (isset($identity['email_address'])) {
                    $html .= '✉️ <a href="mailto:' . esc_attr($identity['email_address']) . '" style="color: #555; text-decoration: none;">' . esc_html($identity['email_address']) . '</a><br>';
                }
                
                // Socials
                if (!empty($socials)) {
                    $html .= '<div style="margin-top: 8px;">';
                    foreach ($socials as $social) {
                        $html .= '<a href="' . esc_url($social['url']) . '" style="margin-left: 10px; text-decoration: none; color: ' . esc_attr($color) . '; font-weight: bold;">' . esc_html(ucfirst($social['platform'])) . '</a>';
                    }
                    $html .= '</div>';
                }
                $html .= '</td>';
                
                $html .= '</tr></table>';
                
                // Disclaimer
                $disclaimer = sprintf(
                    'This message was prepared for %s by the VMO AI Business Suite. If you received it in error please reply STOP.',
                    $name ?: 'this recipient'
                );
                $html .= '<div style="font-size:11px; color:#999; margin-top:15px; padding-top:10px; border-top:1px solid #e0e0e0;">' . esc_html($disclaimer) . '</div>';
                
                $html .= '</div>';

                return [
                    'html' => $html,
                    'text' => strip_tags($html),
                    'disclaimer' => $disclaimer
                ];
            }
        }

        $business_name = $this->resolve_business_name($profile);
        $tagline = $this->pluck_value($profile, ['business_tagline', 'tagline']);
        $industry = isset($profile['industry']) ? sanitize_text_field($profile['industry']) : '';

        $extracted = isset($profile['extracted_info']) && is_array($profile['extracted_info'])
            ? $profile['extracted_info']
            : [];

        $phone = $this->pluck_value($extracted, ['supportPhone', 'phone', 'primaryPhone', 'business_phone']);
        $website = $this->pluck_value($extracted, ['website', 'primaryUrl', 'site_url']);
        $location = $this->pluck_value($extracted, ['hq_location', 'location', 'address', 'city_state']);
        $contact_email = $identity['email_address'] ?? $this->pluck_value($extracted, ['supportEmail', 'contactEmail']);

        $details = [];
        if ($industry) {
            $details[] = $industry;
        } elseif ($tagline) {
            $details[] = sanitize_text_field($tagline);
        }
        if ($contact_email) {
            $details[] = 'Email: ' . $contact_email;
        }
        if ($phone) {
            $details[] = 'Phone: ' . $phone;
        }
        if ($website) {
            $details[] = 'Website: ' . $website;
        }
        if ($location) {
            $details[] = 'Location: ' . $location;
        }

        $disclaimer = sprintf(
            'This message was prepared for %s by the VMO AI Business Suite. If you received it in error please reply STOP.',
            $business_name ?: 'this recipient'
        );

        $detail_html = implode('<br>', array_map('esc_html', array_filter($details)));
        $signature_html = sprintf(
            '<div class="vmo-email-signature" style="margin-top:24px;border-top:1px solid #e2e8f0;padding-top:16px;font-size:14px;line-height:1.6;color:#0f172a;">'
            . '<strong>%s</strong><br>%s'
            . '<div style="margin-top:8px;font-size:13px;color:#475569;">%s</div>'
            . '<p style="font-size:12px;color:#94a3b8;margin-top:16px;">%s</p>'
            . '</div>',
            esc_html($business_name ?: $this->fallback_sender['name']),
            $tagline ? esc_html($tagline) : '',
            $detail_html,
            esc_html($disclaimer)
        );

        $signature_text_lines = array_filter(array_merge([
            $business_name,
            $tagline ?: $industry,
        ], $details));

        $signature_text = trim(implode("\n", $signature_text_lines)) . "\n\n" . $disclaimer;

        return [
            'html' => $signature_html,
            'text' => trim($signature_text),
            'disclaimer' => $disclaimer
        ];
    }

    private function get_identity_by_role($user_id, $role) {
        if (!$user_id || !$this->table_exists($this->table)) {
            return null;
        }

        $sql = $this->wpdb->prepare(
            "SELECT * FROM {$this->table}
             WHERE user_id = %d AND email_role = %s
             ORDER BY (verification_status = 'verified') DESC, is_primary DESC, verified_at DESC, created_at ASC
             LIMIT 1",
            $user_id,
            $role
        );

        return $this->wpdb->get_row($sql, ARRAY_A);
    }

    private function get_any_verified_identity($user_id) {
        if (!$user_id || !$this->table_exists($this->table)) {
            return null;
        }

        $sql = $this->wpdb->prepare(
            "SELECT * FROM {$this->table}
             WHERE user_id = %d
             ORDER BY (verification_status = 'verified') DESC, is_primary DESC, verified_at DESC, created_at ASC
             LIMIT 1",
            $user_id
        );

        return $this->wpdb->get_row($sql, ARRAY_A);
    }

    private function get_business_profile($user_id) {
        if (!$user_id || !$this->table_exists($this->profiles_table)) {
            return [];
        }

        $profile = $this->wpdb->get_row(
            $this->wpdb->prepare("SELECT * FROM {$this->profiles_table} WHERE user_id = %d LIMIT 1", $user_id),
            ARRAY_A
        );

        if (!$profile) {
            return [];
        }

        if (!empty($profile['extracted_info'])) {
            $decoded = json_decode($profile['extracted_info'], true);
            if (json_last_error() === JSON_ERROR_NONE) {
                $profile['extracted_info'] = $decoded;
            } else {
                $profile['extracted_info'] = [];
            }
        } else {
            $profile['extracted_info'] = [];
        }

        return $profile;
    }

    private function resolve_business_name($profile) {
        if (empty($profile)) {
            return '';
        }

        if (!empty($profile['business_name'])) {
            return sanitize_text_field($profile['business_name']);
        }

        $extracted = isset($profile['extracted_info']) && is_array($profile['extracted_info'])
            ? $profile['extracted_info']
            : [];

        $fallback = $this->pluck_value($extracted, ['businessName', 'company', 'brand']);

        return $fallback ? sanitize_text_field($fallback) : '';
    }

    private function pluck_value($source, $keys) {
        if (empty($source) || !is_array($source)) {
            return '';
        }

        foreach ($keys as $key) {
            if (!empty($source[$key])) {
                return sanitize_text_field($source[$key]);
            }
        }

        return '';
    }

    private function table_exists($table_name) {
        if (!$this->wpdb || !$table_name) {
            return false;
        }

        $escaped = str_replace(['\\', '%', '_'], ['\\\\', '\\%', '\\_'], $table_name);
        $result = $this->wpdb->get_var($this->wpdb->prepare("SHOW TABLES LIKE %s", $escaped));

        return !empty($result);
    }
}
