<?php
namespace EasyChat\Library;










class PresenceService {
    const ONLINE_THRESHOLD_SECONDS = 90;
    const UPDATE_THROTTLE_SECONDS = 25;

    private $registry;
    private $db;
    private $prefix;

    public function __construct($registry) {
        $this->registry = $registry;
        $this->db = $registry->get('db');
        $this->prefix = easychat_db_prefix();
    }

    public function markManagerActive($manager_id, $source = 'web_foreground', $force = false) {
        $manager_id = (int)$manager_id;
        if ($manager_id <= 0 || !$this->db) {
            return false;
        }

        $source = $this->normalizeSource($source);
        $ip = $this->clientIp();
        $ip_sql = $this->db->escape($ip);

        $where = '';
        if (!$force) {
            $where = " AND (`last_active` IS NULL"
                . " OR TIMESTAMPDIFF(SECOND, `last_active`, NOW()) >= " . self::UPDATE_THROTTLE_SECONDS
                . " OR `ip` != '" . $ip_sql . "')";
        }

        $this->db->query("/* easychat_presence:" . $source . " */ UPDATE `{$this->prefix}managers`
            SET `last_active` = NOW(),
                `ip` = '" . $ip_sql . "'
            WHERE `id` = " . $manager_id . " AND `status` = 1" . $where);

        return true;
    }

    public function hasOnlineManagers($threshold_seconds = null) {
        $threshold_seconds = $this->normalizeThreshold($threshold_seconds);
        $query = $this->db->query("SELECT `id`
            FROM `{$this->prefix}managers`
            WHERE `status` = 1
              AND `last_active` IS NOT NULL
              AND TIMESTAMPDIFF(SECOND, `last_active`, NOW()) <= " . $threshold_seconds . "
            LIMIT 1");

        return $query && $query->num_rows > 0;
    }

    public function isLastActiveOnline($last_active, $threshold_seconds = null) {
        $last_active = trim((string)$last_active);
        if ($last_active === '') {
            return false;
        }

        $timestamp = strtotime($last_active);
        if (!$timestamp) {
            return false;
        }

        return (time() - $timestamp) <= $this->normalizeThreshold($threshold_seconds);
    }

    private function normalizeSource($source) {
        $source = preg_replace('/[^a-z0-9_:-]/i', '', (string)$source);
        if ($source === '') {
            return 'unknown';
        }

        return substr(strtolower($source), 0, 32);
    }

    private function normalizeThreshold($threshold_seconds) {
        $threshold_seconds = $threshold_seconds === null
            ? self::ONLINE_THRESHOLD_SECONDS
            : (int)$threshold_seconds;

        if ($threshold_seconds < 30) {
            return 30;
        }

        if ($threshold_seconds > 600) {
            return 600;
        }

        return $threshold_seconds;
    }

    private function clientIp() {
        return isset(\EasyChat\Library\RequestContext::server()['REMOTE_ADDR']) ? (string)\EasyChat\Library\RequestContext::server()['REMOTE_ADDR'] : '';
    }
}
