<?php
/**
 * File: class-dashboard-metrics.php
 * Description: Class for calculating and updating dashboard metrics
 */

if (!defined('ABSPATH')) exit;

class Botami_Dashboard_Metrics {
    /**
     * Get total number of conversations
     * A conversation is defined as a unique user/session combination
     * 
     * @return int Number of conversations
     */
    public static function get_total_conversations() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'botamichat_messages';
        
        // Count distinct user_id and session_id combinations
        // This gives us the total number of unique conversations
        $query = "SELECT COUNT(DISTINCT 
                    CASE 
                        WHEN user_id IS NOT NULL THEN CONCAT('user_', user_id) 
                        ELSE CONCAT('session_', session_id) 
                    END
                  ) as total_conversations 
                  FROM {$table_name}";
        
        $result = $wpdb->get_var($query);
        
        return intval($result);
    }
    
    /**
     * Get total number of messages
     * 
     * @return int Number of messages
     */
    public static function get_total_messages() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'botamichat_messages';
        
        // Simple count of all messages
        $query = "SELECT COUNT(*) FROM {$table_name}";
        
        $result = $wpdb->get_var($query);
        
        return intval($result);
    }
    
    /**
     * Get total number of leads generated
     * 
     * @return int Number of leads
     */
    public static function get_total_leads() {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'botami_chatbot_leads';
        
        // Count all leads in the leads table
        $query = "SELECT COUNT(*) FROM {$table_name}";
        
        $result = $wpdb->get_var($query);
        
        return intval($result);
    }
    
    /**
     * Update all dashboard metrics in options table
     */
    public static function update_all_metrics() {
        // Get current metrics
        $total_conversations = self::get_total_conversations();
        $total_messages = self::get_total_messages();
        $total_leads = self::get_total_leads();
        
        // Update options
        update_option('botami_total_conversations', $total_conversations);
        update_option('botami_total_messages', $total_messages);
        update_option('botami_total_leads', $total_leads);
    }
}