<?php
// phpcs:disable WordPress.DB.DirectDatabaseQuery,WordPress.DB.PreparedSQL -- Analytics are stored in plugin-owned custom tables.

/**
 * Analytics functionality for the Instant Popup Builder plugin.
 *
 * @link       https://instantpopupbuilder.com
 * @since      1.0.6.3
 *
 * @package    Instant_Popup_Builder
 * @subpackage Instant_Popup_Builder/includes
 */

/**
 * The analytics class.
 *
 * This class handles all analytics tracking for popups including views, clicks,
 * conversions, and basic reporting functionality.
 *
 * @since      1.0.6.3
 * @package    Instant_Popup_Builder
 * @subpackage Instant_Popup_Builder/includes
 * @author     7th Sky Software's
 */
class Instant_Popup_Builder_Analytics {

    /**
     * Track an analytics event
     *
     * @since    1.0.6.3
     * @param    int     $popup_id      The popup ID
     * @param    string  $event_type    The type of event (view, click, close, conversion)
     * @param    array   $event_data    Additional event data
     * @return   bool                   Success status
     */
    public static function track_event($popup_id, $event_type, $event_data = array()) {
        global $wpdb;

        // Get user information
        $user_ip = self::get_user_ip();
        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT'])) : '';
        $session_id = self::get_session_id();
        $page_url = isset($_SERVER['HTTP_REFERER']) ? esc_url_raw(wp_unslash($_SERVER['HTTP_REFERER'])) : '';
        $referrer = isset($_SERVER['HTTP_REFERER']) ? esc_url_raw(wp_unslash($_SERVER['HTTP_REFERER'])) : '';

        // Insert detailed analytics
        $analytics_table = $wpdb->prefix . 'instant_popup_analytics';
        $result = $wpdb->insert(
            $analytics_table,
            array(
                'popup_id' => $popup_id,
                'event_type' => $event_type,
                'user_ip' => $user_ip,
                'user_agent' => $user_agent,
                'session_id' => $session_id,
                'page_url' => $page_url,
                'referrer' => $referrer,
                'event_data' => wp_json_encode($event_data),
                'event_timestamp' => current_time('mysql')
            ),
            array('%d', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')
        );

        // Update summary counts in main table
        if ($result) {
            self::update_summary_counts($popup_id, $event_type);
        }

        return $result !== false;
    }

    /**
     * Update summary counts in the main popup table
     *
     * @since    1.0.6.3
     * @param    int     $popup_id     The popup ID
     * @param    string  $event_type   The type of event
     */
    private static function update_summary_counts($popup_id, $event_type) {
        global $wpdb;
        $table_name = $wpdb->prefix . 'instant_popup_builder';
        $escaped_table_name = esc_sql($table_name);

        if ($event_type === 'view') {
            $current_views = $wpdb->get_var($wpdb->prepare(
                "SELECT views FROM `{$escaped_table_name}` WHERE id = %d",
                $popup_id
            ));
            $new_views = intval($current_views) + 1;

            $wpdb->update(
                $table_name,
                array('views' => strval($new_views)),
                array('id' => $popup_id),
                array('%s'),
                array('%d')
            );
        } elseif ($event_type === 'click' || $event_type === 'conversion') {
            $current_clicks = $wpdb->get_var($wpdb->prepare(
                "SELECT clicks FROM `{$escaped_table_name}` WHERE id = %d",
                $popup_id
            ));
            $new_clicks = intval($current_clicks) + 1;

            $wpdb->update(
                $table_name,
                array('clicks' => strval($new_clicks)),
                array('id' => $popup_id),
                array('%s'),
                array('%d')
            );
        }
    }

    /**
     * Get analytics summary for a popup
     *
     * @since    1.0.6.3
     * @param    int    $popup_id    The popup ID
     * @param    int    $days        Number of days to look back (default: 30)
     * @return   array               Analytics summary
     */
    public static function get_popup_summary($popup_id, $days = 30) {
        global $wpdb;

        $analytics_table = $wpdb->prefix . 'instant_popup_analytics';
        $escaped_analytics_table = esc_sql($analytics_table);
        $date_limit = gmdate('Y-m-d H:i:s', strtotime("-$days days"));

        // Get event counts
        $events = $wpdb->get_results($wpdb->prepare(
            "SELECT event_type, COUNT(*) as count
             FROM `{$escaped_analytics_table}`
             WHERE popup_id = %d AND event_timestamp >= %s
             GROUP BY event_type",
            $popup_id,
            $date_limit
        ));

        $summary = array(
            'views' => 0,
            'clicks' => 0,
            'closes' => 0,
            'conversions' => 0,
            'conversion_rate' => 0,
            'click_through_rate' => 0
        );

        foreach ($events as $event) {
            $summary[$event->event_type] = intval($event->count);
        }

        // Calculate rates
        if ($summary['views'] > 0) {
            $summary['conversion_rate'] = round(($summary['conversions'] / $summary['views']) * 100, 2);
            $summary['click_through_rate'] = round(($summary['clicks'] / $summary['views']) * 100, 2);
        }

        return $summary;
    }

    /**
     * Get analytics for all popups
     *
     * @since    1.0.6.3
     * @param    int    $days    Number of days to look back (default: 30)
     * @return   array           Analytics data for all popups
     */
    public static function get_all_popups_summary($days = 30) {
        global $wpdb;

        $popup_table = $wpdb->prefix . 'instant_popup_builder';
        $analytics_table = $wpdb->prefix . 'instant_popup_analytics';
        $escaped_popup_table = esc_sql($popup_table);
        $escaped_analytics_table = esc_sql($analytics_table);
        $date_limit = gmdate('Y-m-d H:i:s', strtotime("-$days days"));

        $results = $wpdb->get_results($wpdb->prepare(
            "SELECT p.id, p.title, p.views as total_views, p.clicks as total_clicks,
                    COUNT(CASE WHEN a.event_type = 'view' AND a.event_timestamp >= %s THEN 1 END) as recent_views,
                    COUNT(CASE WHEN a.event_type = 'click' AND a.event_timestamp >= %s THEN 1 END) as recent_clicks,
                    COUNT(CASE WHEN a.event_type = 'conversion' AND a.event_timestamp >= %s THEN 1 END) as recent_conversions
             FROM `{$escaped_popup_table}` p
             LEFT JOIN `{$escaped_analytics_table}` a ON p.id = a.popup_id
             GROUP BY p.id, p.title, p.views, p.clicks",
            $date_limit,
            $date_limit,
            $date_limit
        ));

        $summary = array();
        foreach ($results as $result) {
            $conversion_rate = $result->recent_views > 0 ?
                round(($result->recent_conversions / $result->recent_views) * 100, 2) : 0;
            $ctr = $result->recent_views > 0 ?
                round(($result->recent_clicks / $result->recent_views) * 100, 2) : 0;

            $summary[] = array(
                'id' => $result->id,
                'title' => $result->title,
                'total_views' => intval($result->total_views),
                'total_clicks' => intval($result->total_clicks),
                'recent_views' => intval($result->recent_views),
                'recent_clicks' => intval($result->recent_clicks),
                'recent_conversions' => intval($result->recent_conversions),
                'conversion_rate' => $conversion_rate,
                'click_through_rate' => $ctr
            );
        }

        return $summary;
    }

    /**
     * Get user IP address
     *
     * @since    1.0.6.3
     * @return   string    User IP address
     */
    private static function get_user_ip() {
        $ip = '';

        if ( isset( $_SERVER['HTTP_CLIENT_IP'] ) ) {
            $ip = sanitize_text_field( wp_unslash( $_SERVER['HTTP_CLIENT_IP'] ) );
        } elseif ( isset( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
            $ip = sanitize_text_field( wp_unslash( $_SERVER['HTTP_X_FORWARDED_FOR'] ) );
        } elseif ( isset( $_SERVER['REMOTE_ADDR'] ) ) {
            $ip = sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) );
        }

        return sanitize_text_field($ip);
    }

    /**
     * Get or create session ID
     *
     * @since    1.0.6.3
     * @return   string    Session ID
     */
    private static function get_session_id() {
        if (!session_id()) {
            session_start();
        }

        if (!isset($_SESSION['ipb_session_id'])) {
            $_SESSION['ipb_session_id'] = wp_generate_uuid4();
        }

      return isset( $_SESSION['ipb_session_id'] ) ? sanitize_text_field( wp_unslash( $_SESSION['ipb_session_id'] ) ) : '';
    }

    /**
     * Clean old analytics data
     *
     * @since    1.0.6.3
     * @param    int    $days    Number of days to keep (default: 90)
     * @return   bool           Success status
     */
    public static function cleanup_old_data($days = 90) {
        global $wpdb;

        $analytics_table = $wpdb->prefix . 'instant_popup_analytics';
        $escaped_analytics_table = esc_sql($analytics_table);
        $date_limit = gmdate('Y-m-d H:i:s', strtotime("-$days days"));

        $result = $wpdb->query($wpdb->prepare(
            "DELETE FROM `{$escaped_analytics_table}` WHERE event_timestamp < %s",
            $date_limit
        ));

        return $result !== false;
    }
}
