<?php

namespace FleekDash\Services\AnalyticsTracking;

/**
 * Session Manager
 *
 * Handles analytics session creation, updates, and tracking
 * Extracted from AnalyticsTrackingService for better organization
 *
 * @package FleekDash\Services\AnalyticsTracking
 * @since 2.2.0
 */
class SessionManager
{
    private $wpdb;
    private $table_sessions;

    public function __construct()
    {
        global $wpdb;
        $this->wpdb = $wpdb;
        $this->table_sessions = $wpdb->prefix . 'fleekdash_sessions';
    }

    /**
     * Get or create session ID
     *
     * @return string Session ID
     */
    public function getOrCreateSessionId()
    {
        if (isset($_COOKIE['fleekdash_session_id'])) {
            return \sanitize_text_field($_COOKIE['fleekdash_session_id']);
        }

        $session_id = uniqid('', true);
        if (function_exists('wp_generate_uuid4')) {
            $session_id = wp_generate_uuid4();
        }

        setcookie('fleekdash_session_id', $session_id, time() + (30 * 24 * 60 * 60), '/'); // 30 days

        return $session_id;
    }

    /**
     * Create or update session
     *
     * @param string $session_id Session identifier
     * @param string $page_url Current page URL
     * @param string $referrer Referrer URL
     * @param int|null $user_id WordPress user ID
     * @param string $ip_address Client IP address
     * @param array $geo_data Geo location data
     * @param array $device_data Device/browser data
     * @return bool Success status
     */
    public function createOrUpdateSession($session_id, $page_url, $referrer, $user_id, $ip_address, $geo_data, $device_data)
    {
        $existing_session = $this->wpdb->get_row(
            $this->wpdb->prepare(
                "SELECT * FROM {$this->table_sessions} WHERE session_id = %s",
                $session_id
            )
        );

        if ($existing_session) {
            // Update existing session
            return $this->wpdb->update(
                $this->table_sessions,
                [
                    'last_visit' => \current_time('mysql'),
                    'total_pageviews' => $existing_session->total_pageviews + 1,
                    'exit_page' => $page_url,
                    'is_bounce' => 0 // More than one page view = not a bounce
                ],
                ['session_id' => $session_id],
                ['%s', '%d', '%s', '%d'],
                ['%s']
            ) !== false;
        }

        // Create new session
        $referrer_domain = $referrer ? parse_url($referrer, PHP_URL_HOST) : null;
        $referrer_type = $this->classifyReferrer($referrer, $referrer_domain);

        return $this->wpdb->insert(
            $this->table_sessions,
            [
                'session_id' => $session_id,
                'user_id' => $user_id ?: null,
                'first_visit' => \current_time('mysql'),
                'last_visit' => \current_time('mysql'),
                'total_pageviews' => 1,
                'referrer' => $referrer,
                'referrer_domain' => $referrer_domain,
                'referrer_type' => $referrer_type,
                'landing_page' => $page_url,
                'exit_page' => $page_url,
                'country_code' => $geo_data['country_code'] ?? null,
                'country_name' => $geo_data['country_name'] ?? null,
                'city' => $geo_data['city'] ?? null,
                'device_type' => $device_data['device_type'] ?? null,
                'browser' => $device_data['browser'] ?? null,
                'os' => $device_data['os'] ?? null,
                'ip_address' => $ip_address,
                'user_agent' => $_POST['user_agent'] ?? ''
            ]
        ) !== false;
    }

    /**
     * Update session with time data
     *
     * @param string $session_id Session identifier
     * @param string $exit_page Exit page URL
     * @param int $time_on_page Time spent on page (seconds)
     * @return bool Success status
     */
    public function updateSession($session_id, $exit_page, $time_on_page)
    {
        $session = $this->wpdb->get_row(
            $this->wpdb->prepare(
                "SELECT * FROM {$this->table_sessions} WHERE session_id = %s",
                $session_id
            )
        );

        if (!$session) {
            return false;
        }

        $session_duration = strtotime($session->last_visit) - strtotime($session->first_visit) + $time_on_page;
        $is_bounce = $session->total_pageviews == 1 && $time_on_page < 30 ? 1 : 0;

        return $this->wpdb->update(
            $this->table_sessions,
            [
                'session_duration' => $session_duration,
                'exit_page' => $exit_page,
                'is_bounce' => $is_bounce
            ],
            ['session_id' => $session_id],
            ['%d', '%s', '%d'],
            ['%s']
        ) !== false;
    }

    /**
     * Classify referrer type
     *
     * @param string $referrer Full referrer URL
     * @param string $referrer_domain Referrer domain
     * @return string Referrer type (direct, search, social, internal, external)
     */
    private function classifyReferrer($referrer, $referrer_domain)
    {
        if (empty($referrer)) {
            return 'direct';
        }

        $site_domain = parse_url(\home_url(), PHP_URL_HOST);

        if ($referrer_domain === $site_domain) {
            return 'internal';
        }

        // Search engines
        $search_engines = ['google', 'bing', 'yahoo', 'duckduckgo', 'baidu', 'yandex'];
        foreach ($search_engines as $engine) {
            if (strpos($referrer_domain, $engine) !== false) {
                return 'search';
            }
        }

        // Social media
        $social_media = ['facebook', 'twitter', 'linkedin', 'instagram', 'pinterest', 'reddit'];
        foreach ($social_media as $platform) {
            if (strpos($referrer_domain, $platform) !== false) {
                return 'social';
            }
        }

        return 'external';
    }
}
