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

/**
 * VMO Contact Form Handler
 * Handles investor and contact form submissions from pitch deck
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

class VMO_Contact_Handler {
    
    public function __construct() {
        add_action('wp_ajax_vmo_submit_contact', array($this, 'handle_contact_submission'));
        add_action('wp_ajax_nopriv_vmo_submit_contact', array($this, 'handle_contact_submission'));
        add_action('wp_enqueue_scripts', array($this, 'enqueue_scripts'));
    }
    
    public function enqueue_scripts() {
        wp_localize_script('jquery', 'vmo_ajax', array(
            'ajaxurl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('vmo_contact_nonce')
        ));
    }
    
    /**
     * Handle contact form submission
     */
    public function handle_contact_submission() {
        // Verify nonce
        $security = sanitize_text_field(wp_unslash($_POST['security'] ?? $_POST['nonce'] ?? ''));
        if (!wp_verify_nonce($security, 'vmo_contact_nonce')) {
            wp_die('Security check failed');
        }

        if (!function_exists('vmo_crm_upsert_contact') || !function_exists('vmo_crm_log_interaction')) {
            wp_send_json_error('CRM is not available. Please try again later.');
            return;
        }
        
        // Get form data
        $name = sanitize_text_field(wp_unslash($_POST['name'] ?? ''));
        $email = sanitize_email(wp_unslash($_POST['email'] ?? ''));
        $company = sanitize_text_field(wp_unslash($_POST['company'] ?? ''));
        $investment_interest = sanitize_text_field(wp_unslash($_POST['investment_interest'] ?? ''));
        $investment_amount = sanitize_text_field(wp_unslash($_POST['investment_amount'] ?? ''));
        $message = sanitize_textarea_field(wp_unslash($_POST['message'] ?? ''));
        $referrer = esc_url_raw(wp_unslash($_POST['referrer'] ?? $_POST['referer'] ?? ''));
        $landing_page = esc_url_raw(wp_unslash($_POST['landing_page'] ?? $_POST['page_url'] ?? ''));
        $utm_source = sanitize_text_field(wp_unslash($_POST['utm_source'] ?? ''));
        $utm_medium = sanitize_text_field(wp_unslash($_POST['utm_medium'] ?? ''));
        $utm_campaign = sanitize_text_field(wp_unslash($_POST['utm_campaign'] ?? ''));
        $lead_score = $this->calculate_lead_score($investment_amount);
        $owner_id = $this->get_crm_owner_id();

        $contact = vmo_crm_upsert_contact($owner_id, array(
            'full_name' => $name,
            'email' => $email,
            'company' => $company,
        ), array(
            'source' => 'website_form',
            'primary_category' => 'lead',
            'lifecycle_stage' => 'new',
            'tags' => array('investor', 'pitch_deck'),
            'lead_score' => $lead_score,
            'value_potential' => $lead_score,
            'notes' => "Investment Interest: $investment_interest\nInvestment Amount: $investment_amount\nMessage: $message",
            'acquisition_details' => array(
                'form_type' => 'investor_pitch_deck',
                'investment_interest' => $investment_interest,
                'investment_amount' => $investment_amount,
                'referrer' => $referrer,
                'landing_page' => $landing_page,
                'utm_source' => $utm_source,
                'utm_medium' => $utm_medium,
                'utm_campaign' => $utm_campaign,
            ),
        ));

        if (empty($contact['contact_id'])) {
            wp_send_json_error('Failed to save contact information. Please try again.');
            return;
        }

        $contact_id = (string) $contact['contact_id'];
        $contact_data = array(
            'contact_id' => $contact_id,
            'source' => 'website_form',
            'name' => $name,
            'full_name' => $name,
            'email' => $email,
            'company' => $company,
            'tags' => 'investor,pitch_deck',
            'lead_score' => $lead_score,
        );
        
        // Log interaction
        $this->log_contact_interaction($owner_id, $contact_id, 'form_submission', array(
            'investment_interest' => $investment_interest,
            'investment_amount' => $investment_amount,
            'message' => $message,
            'form_type' => 'investor_pitch_deck',
            'referrer' => $referrer,
            'landing_page' => $landing_page,
            'utm_source' => $utm_source,
            'utm_medium' => $utm_medium,
            'utm_campaign' => $utm_campaign,
        ));
        
        // Send notification email to admin
        $this->send_admin_notification($contact_data, array(
            'investment_interest' => $investment_interest,
            'investment_amount' => $investment_amount,
            'message' => $message
        ));
        
        // Send confirmation email to investor
        $this->send_investor_confirmation($email, $name, $investment_interest);
        
        wp_send_json_success(array(
            'message' => 'Thank you for your interest! We will contact you within 24 hours.',
            'contact_id' => $contact_id
        ));
    }
    
    /**
     * Calculate lead score based on investment amount
     */
    private function calculate_lead_score($investment_amount) {
        if (strpos($investment_amount, '$15M') !== false) {
            return 100; // Hot lead - maximum investment
        } elseif (strpos($investment_amount, '$8M') !== false) {
            return 80; // Warm lead - substantial investment
        } elseif (strpos($investment_amount, '$3M') !== false) {
            return 60; // Qualified lead - minimum viable investment
        } else {
            return 40; // General interest
        }
    }
    
    /**
     * Log contact interaction
     */
    private function log_contact_interaction($user_id, $contact_id, $type, $data) {
        if (!function_exists('vmo_crm_log_interaction')) {
            return;
        }

        vmo_crm_log_interaction((int) $user_id, (string) $contact_id, array(
            'interaction_type' => 'other',
            'subtype' => sanitize_key($type),
            'direction' => 'inbound',
            'subject' => 'Investor pitch deck form submission',
            'summary' => 'Investment interest: ' . sanitize_text_field($data['investment_interest'] ?? '') . '; amount: ' . sanitize_text_field($data['investment_amount'] ?? ''),
            'outcome' => 'needs_follow_up',
            'metadata' => $data,
        ));
    }

    private function get_crm_owner_id() {
        $owner_id = 0;
        if (is_user_logged_in() && current_user_can('manage_options')) {
            $owner_id = (int) get_current_user_id();
        }
        if ($owner_id <= 0) {
            $admins = get_users(array('role' => 'administrator', 'number' => 1, 'fields' => 'ID'));
            $owner_id = !empty($admins[0]) ? (int) $admins[0] : 1;
        }
        return $owner_id;
    }
    
    /**
     * Send admin notification email
     */
    private function send_admin_notification($contact_data, $form_data) {
        // Use configurable email addresses with admin_email fallback
        $primary_email = get_option('vmo_contact_primary_email', get_option('admin_email'));
        $secondary_email = get_option('vmo_contact_secondary_email', '');
        $admin_email = get_option('admin_email');
        
        $subject = '🚨 NEW INVESTOR INQUIRY - ' . $form_data['investment_amount'];
        
        $message = "NEW INVESTOR INQUIRY RECEIVED\n\n";
        $message .= "═══════════════════════════════════\n";
        $message .= "INVESTOR DETAILS:\n";
        $message .= "Name: {$contact_data['name']}\n";
        $message .= "Email: {$contact_data['email']}\n";
        $message .= "Company: {$contact_data['company']}\n";
        $message .= "Contact ID: {$contact_data['contact_id']}\n";
        $message .= "Lead Score: {$contact_data['lead_score']}/100\n\n";
        
        $message .= "INVESTMENT DETAILS:\n";
        $message .= "Interest Level: {$form_data['investment_interest']}\n";
        $message .= "Investment Amount: {$form_data['investment_amount']}\n\n";
        
        $message .= "MESSAGE:\n";
        $message .= $form_data['message'] . "\n\n";
        
        $message .= "═══════════════════════════════════\n";
        $message .= "Submitted: " . current_time('Y-m-d H:i:s') . "\n";
        $message .= "Source: VMO AI Investor Pitch Deck\n";
        
        // Set headers for HTML email
        $headers = array(
            'Content-Type: text/plain; charset=UTF-8',
            'From: VMO AI System <noreply@' . parse_url(home_url(), PHP_URL_HOST) . '>'
        );
        if ($secondary_email) {
            $headers[] = 'Cc: ' . $secondary_email;
        }
        
        // Send to primary email with CC to secondary
        wp_mail($primary_email, $subject, $message, $headers);
        
        // Also send to WordPress admin email as backup
        if ($admin_email !== $primary_email && $admin_email !== $secondary_email) {
            wp_mail($admin_email, $subject, $message, array(
                'Content-Type: text/plain; charset=UTF-8',
                'From: VMO AI System <noreply@' . parse_url(home_url(), PHP_URL_HOST) . '>'
            ));
        }
    }
    
    /**
     * Send confirmation email to investor
     */
    private function send_investor_confirmation($email, $name, $investment_interest) {
        $subject = 'VMO AI - Thank you for your investment interest';
        
        $message = "Dear {$name},\n\n";
        $message .= "Thank you for your interest in investing in VMO AI Website Builder!\n\n";
        
        $message .= "We have received your inquiry with the following details:\n";
        $message .= "• Investment Interest: {$investment_interest}\n";
        $message .= "• Submitted: " . current_time('Y-m-d H:i:s') . "\n\n";
        
        $message .= "WHAT HAPPENS NEXT:\n";
        $message .= "1. Our investment team will review your inquiry within 24 hours\n";
        $message .= "2. You will receive a personalized investment package\n";
        $message .= "3. We will schedule a private demo and Q&A session\n";
        $message .= "4. Due diligence materials will be provided under NDA\n\n";
        
        $message .= "URGENT MARKET OPPORTUNITY:\n";
        $message .= "The AI website building market is exploding, and we have a limited window\n";
        $message .= "to capture first-mover advantage before competitors copy our technology.\n";
        $message .= "Early investors will have the greatest upside potential.\n\n";
        
        $message .= "For immediate questions, please contact our investment team:\n";
        $message .= "Email: " . get_option('vmo_contact_primary_email', get_option('admin_email')) . "\n";
        $vmo_secondary = get_option('vmo_contact_secondary_email', '');
        if ($vmo_secondary) { $message .= "Email: " . $vmo_secondary . "\n"; }
        $message .= "Phone: +1 (555) VMO-FUND\n\n";
        
        $message .= "Best regards,\n";
        $message .= "Jerreme Josephson\n";
        $message .= "The VMO AI Investment Team\n\n";
        
        $message .= "---\n";
        $message .= "VMO AI Website Builder\n";
        $message .= "Transforming the $40B website building industry with AI\n";
        
        $vmo_from = get_option('vmo_contact_primary_email', get_option('admin_email'));
        $headers = array(
            'Content-Type: text/plain; charset=UTF-8',
            'From: VMO AI Investments <' . $vmo_from . '>',
            'Reply-To: ' . $vmo_from
        );
        
        wp_mail($email, $subject, $message, $headers);
    }
}

// Initialize the contact handler
new VMO_Contact_Handler();
