<?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
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['security'])), 'vmo_contact_nonce')) {
            wp_die('Security check failed');
        }
        
        global $wpdb;
        
        // Get form data
        $name = sanitize_text_field(wp_unslash($_POST['name']));
        $email = sanitize_email($_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($_POST['message']);
        
        // Generate unique contact ID
        $contact_id = 'INV_' . time() . '_' . substr(md5($email), 0, 8);
        
        // Prepare contact data
        $contacts_table = $wpdb->prefix . 'vmo_contacts';
        
        $contact_data = array(
            'contact_id' => $contact_id,
            'source' => 'website_form',
            'name' => $name,
            'email' => $email,
            'phone' => '', // Not collected in pitch deck form
            'company' => $company,
            'website' => '',
            'status' => 'new',
            'tags' => 'investor,pitch_deck',
            'notes' => "Investment Interest: $investment_interest\nInvestment Amount: $investment_amount\nMessage: $message",
            'lead_score' => $this->calculate_lead_score($investment_amount),
            'created_at' => current_time('mysql'),
            'updated_at' => current_time('mysql'),
            'last_contact' => current_time('mysql')
        );
        
        // Insert contact
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $result = $wpdb->insert($contacts_table, $contact_data);
        
        if ($result === false) {
            wp_send_json_error('Failed to save contact information. Please try again.');
            return;
        }
        
        // Log interaction
        $this->log_contact_interaction($contact_id, 'form_submission', array(
            'investment_interest' => $investment_interest,
            'investment_amount' => $investment_amount,
            'message' => $message,
            'form_type' => 'investor_pitch_deck'
        ));
        
        // 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($contact_id, $type, $data) {
        global $wpdb;
        
        $interactions_table = $wpdb->prefix . 'vmo_contact_interactions';
        
        $interaction_data = array(
            'contact_id' => $contact_id,
            'interaction_type' => $type,
            'interaction_date' => current_time('mysql'),
            'details' => json_encode($data),
            'created_at' => current_time('mysql')
        );
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $wpdb->insert($interactions_table, $interaction_data);
    }
    
    /**
     * 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();
