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

class Botami_Lead_Generator {
    private static $instance = null;
    
    // Cache group for leads
    private $cache_group = 'chatbot_leads';
    private $cache_time = 3600; // 1 hour
    
    // Singleton pattern
    public static function getInstance() {
        if (self::$instance === null) {
            self::$instance = new self();
        }
        return self::$instance;
    }
    
    public function __construct() {
        // Set up non-persistent cache group
        wp_cache_add_non_persistent_groups($this->cache_group);
    }
    
    // Create lead table on activation
    public function create_leads_table() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'botami_chatbot_leads';
        $charset_collate = $wpdb->get_charset_collate();
        
        $sql = "CREATE TABLE IF NOT EXISTS $table_name (
            id BIGINT(20) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            name VARCHAR(255) NOT NULL,
            email VARCHAR(255) NOT NULL,
            custom_field_label VARCHAR(255) DEFAULT NULL,
            custom_field_value TEXT DEFAULT NULL,
            user_id BIGINT(20) UNSIGNED DEFAULT NULL,
            session_id VARCHAR(40) DEFAULT NULL,
            created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
            KEY idx_user_id (user_id),
            KEY idx_session_id (session_id),
            KEY idx_email (email)
        ) $charset_collate;";
        
        require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
        dbDelta($sql);
    }
    
    /**
     * Save a new lead to the database
     * 
     * @param string $name User's name
     * @param string $email User's email
     * @param string $custom_field_label Label for the custom field
     * @param string $custom_field_value Value for the custom field
     * @return bool|int The ID of the inserted lead or false on failure
     */
    public function save_lead($name, $email, $custom_field_label = '', $custom_field_value = '') {
        global $wpdb;
        $table_name = $wpdb->prefix . 'botami_chatbot_leads';
        
        $data = [
            'name' => $name,
            'email' => $email,
            'custom_field_label' => $custom_field_label,
            'custom_field_value' => $custom_field_value,
            'created_at' => current_time('mysql')
        ];
        
        // Add user_id if user is logged in
        if (is_user_logged_in()) {
            $data['user_id'] = get_current_user_id();
            $cache_key = 'lead_submitted_user_' . $data['user_id'];
        } else {
            // Get session ID for non-logged in users
            $session_handler = Botami_Session_Handler::getInstance();
            $data['session_id'] = $session_handler->get_session_id();
            $cache_key = 'lead_submitted_session_' . $data['session_id'];
        }
        
        // Direct database call necessary for custom table operations
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
        $result = $wpdb->insert($table_name, $data);
        
        if ($result === false) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Failed to save lead: ' . $wpdb->last_error);
            }
            return false;
        }
        
        // Clear cache for this user/session since they now have a lead
        wp_cache_delete($cache_key, $this->cache_group);
        wp_cache_delete('leads_count', $this->cache_group);
        
        return $wpdb->insert_id;
    }
    
    /**
     * Check if the current user or session has already submitted a lead
     * 
     * @return bool True if a lead exists for the current user/session
     */
    public function has_submitted_lead() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'botami_chatbot_leads';
        
        if (is_user_logged_in()) {
            $user_id = get_current_user_id();
            $cache_key = 'lead_submitted_user_' . $user_id;
            
            // Try cache first
            $cached_result = wp_cache_get($cache_key, $this->cache_group);
            if ($cached_result !== false) {
                return (bool) $cached_result;
            }
            
            // Direct database call necessary for custom table operations
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $query = $wpdb->prepare(
                "SELECT COUNT(*) FROM {$table_name} WHERE user_id = %d",
                $user_id
            );
        } else {
            $session_handler = Botami_Session_Handler::getInstance();
            $session_id = $session_handler->get_session_id();
            $cache_key = 'lead_submitted_session_' . $session_id;
            
            // Try cache first
            $cached_result = wp_cache_get($cache_key, $this->cache_group);
            if ($cached_result !== false) {
                return (bool) $cached_result;
            }
            
            // Direct database call necessary for custom table operations
            // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
            $query = $wpdb->prepare(
                "SELECT COUNT(*) FROM {$table_name} WHERE session_id = %s",
                $session_id
            );
        }
        
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $count = $wpdb->get_var($query);
        $has_submitted = (int)$count > 0;
        
        // Cache the result
        wp_cache_set($cache_key, $has_submitted ? 1 : 0, $this->cache_group, $this->cache_time);
        
        return $has_submitted;
    }
    
    /**
     * Export all leads to CSV
     * 
     * @return string|bool CSV content as a string or false on failure
     */
    public function export_leads_to_csv() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'botami_chatbot_leads';
        
        // Direct database call necessary for custom table operations
        // No caching needed for export operations as they are one-time requests
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $results = $wpdb->get_results(
            "SELECT name, email, custom_field_label, custom_field_value, created_at 
            FROM {$table_name} 
            ORDER BY created_at DESC",
            ARRAY_A
        );
        
        if (empty($results)) {
            return false;
        }

        // Create CSV header
        $csv_content = "Name,Email,";
        
        // Add dynamic field label if present
        if (!empty($results[0]['custom_field_label'])) {
            $csv_content .= $results[0]['custom_field_label'] . ",";
        } else {
            $csv_content .= "Custom Field,";
        }
        
        $csv_content .= "Date\n";
        
        // Add data rows
        foreach ($results as $row) {
            $csv_content .= implode(',', array_map(function($field) {
                // Handle empty values
                if ($field === null) $field = '';
                
                // Escape quotes and wrap in quotes
                $field = str_replace('"', '""', $field);
                return '"' . $field . '"';
            }, array(
                $row['name'],
                $row['email'],
                $row['custom_field_value'],
                $row['created_at']
            ))) . "\n";
        }
        
        return $csv_content;
    }
    
    /**
     * Get the total number of leads
     * 
     * @return int Number of leads
     */
    public function get_leads_count() {
        global $wpdb;
        $table_name = $wpdb->prefix . 'botami_chatbot_leads';
        
        $cache_key = 'leads_count';
        
        // Try cache first
        $cached_count = wp_cache_get($cache_key, $this->cache_group);
        if ($cached_count !== false) {
            return (int) $cached_count;
        }
        
        // Direct database call
        // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
        $count = $wpdb->get_var("SELECT COUNT(*) FROM {$table_name}");
        
        $final_count = $count ? intval($count) : 0;
        
        // Cache the result
        wp_cache_set($cache_key, $final_count, $this->cache_group, $this->cache_time);
        
        return $final_count;
    }
}