<?php
/**
To automatically use the server's default timezone:
*/
 //date_default_timezone_set(date_default_timezone_get());//
 date_default_timezone_set('Asia/Karachi');
 
/**
 * Floating Visitor Counter (Single File)
 * Uses existing database connection: connect.php
 */
require_once __DIR__ . '/connect.php';

/* =========================
   SAFETY CHECK
========================= */
if (!isset($conn)) {
    die('Database connection $conn not found in connect.php');
}

/* =========================
   Detect DB type
========================= */
$isPDO = ($conn instanceof PDO);

/* =========================
   Visitor info
========================= */
$ip  = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';
$ua  = $_SERVER['HTTP_USER_AGENT'] ?? 'UNKNOWN';
$now = date('Y-m-d H:i:s');

/* =========================
   Browser & OS Detection
========================= */
function getBrowser($ua) {
    $ua = strtolower($ua);
    if (strpos($ua, 'edg') !== false) return 'Edge';
    if (strpos($ua, 'opr') !== false || strpos($ua, 'opera') !== false) return 'Opera';
    if (strpos($ua, 'chrome') !== false) return 'Chrome';
    if (strpos($ua, 'safari') !== false) return 'Safari';
    if (strpos($ua, 'firefox') !== false) return 'Firefox';
    if (strpos($ua, 'trident') !== false || strpos($ua, 'msie') !== false) return 'Internet Explorer';
    return 'Unknown';
}

function getOS($ua) {
    $ua = strtolower($ua);
    if (strpos($ua, 'windows nt') !== false) return 'Windows';
    if (strpos($ua, 'android') !== false) return 'Android';
    if (strpos($ua, 'iphone') !== false || strpos($ua, 'ipad') !== false) return 'iOS';
    if (strpos($ua, 'mac os x') !== false) return 'macOS';
    if (strpos($ua, 'linux') !== false) return 'Linux';
    return 'Unknown';
}

$browser = getBrowser($ua);
$os      = getOS($ua);

/* =========================
   Insert visitor (20 min rule)
========================= */
if ($isPDO) {

    $stmt = $conn->prepare("
        SELECT COUNT(*) FROM visitor_stats
        WHERE ip_address = ? AND visit_time > DATE_SUB(NOW(), INTERVAL 20 MINUTE)
    ");
    $stmt->execute([$ip]);
    $exists = $stmt->fetchColumn();

    if (!$exists) {
        $ins = $conn->prepare("
            INSERT INTO visitor_stats (ip_address, user_agent, visit_time)
            VALUES (?, ?, NOW())
        ");
        $ins->execute([$ip, $ua]);
    }

    function countQ($sql) {
        global $conn;
        return (int)$conn->query($sql)->fetchColumn();
    }

} else { // MYSQLI

    $chk = $conn->prepare("
        SELECT COUNT(*) FROM visitor_stats
        WHERE ip_address = ? AND visit_time > DATE_SUB(NOW(), INTERVAL 20 MINUTE)
    ");
    $chk->bind_param("s", $ip);
    $chk->execute();
    $chk->bind_result($exists);
    $chk->fetch();
    $chk->close();

    if (!$exists) {
        $ins = $conn->prepare("
            INSERT INTO visitor_stats (ip_address, user_agent, visit_time)
            VALUES (?, ?, NOW())
        ");
        $ins->bind_param("ss", $ip, $ua);
        $ins->execute();
        $ins->close();
    }

    function countQ($sql) {
        global $conn;
        return (int)$conn->query($sql)->fetch_row()[0];
    }
}

/* =========================
   Counts
========================= */
$today       = countQ("SELECT COUNT(*) FROM visitor_stats WHERE DATE(visit_time)=CURDATE()");
$yesterday   = countQ("SELECT COUNT(*) FROM visitor_stats WHERE DATE(visit_time)=CURDATE()-INTERVAL 1 DAY");
$this_week   = countQ("SELECT COUNT(*) FROM visitor_stats WHERE YEARWEEK(visit_time,1)=YEARWEEK(CURDATE(),1)");
$last_week   = countQ("SELECT COUNT(*) FROM visitor_stats WHERE YEARWEEK(visit_time,1)=YEARWEEK(CURDATE(),1)-1");
$this_month  = countQ("SELECT COUNT(*) FROM visitor_stats WHERE MONTH(visit_time)=MONTH(CURDATE()) AND YEAR(visit_time)=YEAR(CURDATE())");
$last_month  = countQ("SELECT COUNT(*) FROM visitor_stats WHERE MONTH(visit_time)=MONTH(CURDATE()-INTERVAL 1 MONTH) AND YEAR(visit_time)=YEAR(CURDATE()-INTERVAL 1 MONTH)");
$all         = countQ("SELECT COUNT(*) FROM visitor_stats");
$online      = countQ("SELECT COUNT(*) FROM visitor_stats WHERE visit_time > DATE_SUB(NOW(), INTERVAL 20 MINUTE)");
?>

<!-- =========================
     FLOATING COUNTER UI - COMPACT VERSION
========================= -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
<style>
#vinaora-counter {
    position: fixed;
    right: 10px;
    bottom: 10px;
    width: 200px;
    font-family: 'Segoe UI', 'Roboto', 'Helvetica Neue', Arial, sans-serif;
    font-size: 12px;
    background: linear-gradient(145deg, #1a2980, #26d0ce);
    color: #fff;
    border-radius: 12px;
    z-index: 99999;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.25);
    overflow: hidden;
    backdrop-filter: blur(5px);
    border: 1px solid rgba(255, 255, 255, 0.15);
}

#vinaora-counter h4 {
    margin: 0;
    padding: 8px 12px;
    font-size: 12px;
    text-align: center;
    background: rgba(0, 0, 0, 0.25);
    font-weight: 600;
    border-bottom: 1px solid rgba(255, 255, 255, 0.1);
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
}

#vinaora-counter h4 i {
    font-size: 12px;
}

#vinaora-total {
    text-align: center;
    font-size: 20px;
    font-weight: 700;
    background: rgba(0, 0, 0, 0.35);
    padding: 10px;
    cursor: pointer;
    transition: all 0.2s ease;
    letter-spacing: 1px;
    font-family: 'Courier New', monospace;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
}

#vinaora-total:hover {
    background: rgba(0, 0, 0, 0.45);
}

#vinaora-total i {
    font-size: 16px;
    color: #4cd964;
}

#vinaora-details {
    display: none;
    background: #ffffff;
    color: #2c3e50;
    padding: 10px;
    line-height: 1.4;
    max-height: 300px;
    overflow-y: auto;
}

#vinaora-details::-webkit-scrollbar {
    width: 4px;
}

#vinaora-details::-webkit-scrollbar-track {
    background: #f1f1f1;
    border-radius: 2px;
}

#vinaora-details::-webkit-scrollbar-thumb {
    background: #1a2980;
    border-radius: 2px;
}

.v-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 6px 0;
    border-bottom: 1px solid #f0f0f0;
    transition: all 0.15s ease;
}

.v-item:last-child {
    border-bottom: none;
}

.v-item:hover {
    background: #f8f9fa;
    padding: 6px 4px;
    border-radius: 4px;
}

.v-item span {
    display: flex;
    align-items: center;
    gap: 6px;
    font-weight: 500;
    font-size: 11px;
}

.v-item span i {
    width: 18px;
    text-align: center;
    font-size: 12px;
    color: #1a2980;
}

.v-item b {
    font-weight: 700;
    color: #1a2980;
    background: #f0f7ff;
    padding: 2px 6px;
    border-radius: 10px;
    min-width: 35px;
    text-align: center;
    font-size: 11px;
}

.separator {
    margin: 8px 0;
    text-align: center;
    position: relative;
}

.separator:before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    right: 0;
    height: 1px;
    background: linear-gradient(90deg, transparent, #ddd, transparent);
}

.separator span {
    background: #fff;
    padding: 0 8px;
    color: #666;
    font-size: 9px;
    font-weight: 600;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    position: relative;
}

.stats-label, .user-info-label {
    font-size: 10px;
    color: #666;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    margin-bottom: 6px;
    font-weight: 600;
}

.user-info-label {
    margin-top: 10px;
}

.badge {
    background: linear-gradient(145deg, #1a2980, #26d0ce);
    color: white;
    padding: 1px 5px;
    border-radius: 8px;
    font-size: 9px;
    font-weight: 600;
    margin-left: 4px;
}

#vinaora-close {
    position: absolute;
    top: 6px;
    right: 8px;
    background: rgba(255, 255, 255, 0.1);
    border: none;
    color: white;
    width: 18px;
    height: 18px;
    border-radius: 50%;
    cursor: pointer;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 10px;
    transition: all 0.2s ease;
    opacity: 0.7;
}

#vinaora-close:hover {
    background: rgba(255, 255, 255, 0.2);
    opacity: 1;
}

.compact-text {
    font-size: 10px !important;
}
</style>

<div id="vinaora-counter">
    <button id="vinaora-close" title="Close">
        <i class="fas fa-times"></i>
    </button>
    
    <h4>
        <i class="fas fa-chart-line"></i>
        DSIS Visitors Counter
    </h4>

    <div id="vinaora-total">
        <i class="fas fa-eye"></i>
        <?php echo str_pad($all, 6, '0', STR_PAD_LEFT); ?>
    </div>

    <div id="vinaora-details">
        <div class="stats-label">Visitor Stats</div>
        
        <div class="v-item">
            <span>
                <i class="fas fa-sun" style="color: #f39c12;"></i>
                Today
            </span>
            <b><?php echo $today; ?></b>
        </div>
        
        <div class="v-item">
            <span>
                <i class="fas fa-moon" style="color: #8e44ad;"></i>
                Yesterday
            </span>
            <b><?php echo $yesterday; ?></b>
        </div>
        
        <div class="v-item">
            <span>
                <i class="fas fa-calendar-week" style="color: #3498db;"></i>
                Week
            </span>
            <b><?php echo $this_week; ?></b>
        </div>
        
        <div class="v-item">
            <span>
                <i class="fas fa-calendar-alt" style="color: #9b59b6;"></i>
                Last Week
            </span>
            <b><?php echo $last_week; ?></b>
        </div>
        
        <div class="v-item">
            <span>
                <i class="fas fa-calendar" style="color: #e74c3c;"></i>
                Month
            </span>
            <b><?php echo $this_month; ?></b>
        </div>
        
        <div class="v-item">
            <span>
                <i class="fas fa-chart-bar" style="color: #2ecc71;"></i>
                Last Month
            </span>
            <b><?php echo $last_month; ?></b>
        </div>
        
        <div class="v-item">
            <span>
                <i class="fas fa-globe-americas" style="color: #1abc9c;"></i>
                Total
            </span>
            <b><?php echo $all; ?></b>
        </div>

        <div class="separator">
            <span>Status</span>
        </div>

        <div class="user-info-label">Your Session</div>
        
        <div class="v-item">
            <span>
                <i class="fas fa-signal" style="color: #2ecc71;"></i>
                Online
                <span class="badge">Live</span>
            </span>
            <b><?php echo $online; ?></b>
        </div>
        
        <div class="v-item">
            <span>
                <i class="fas fa-network-wired" style="color: #34495e;"></i>
                IP
            </span>
            <b class="compact-text"><?php echo $ip; ?></b>
        </div>
        
        <div class="v-item">
            <span>
                <i class="fas fa-desktop" style="color: #e67e22;"></i>
                Device
            </span>
            <b class="compact-text"><?php echo $browser . ' / ' . $os; ?></b>
        </div>
        
        <div class="v-item">
            <span>
                <i class="fas fa-clock" style="color: #95a5a6;"></i>
                Time
            </span>
            <b class="compact-text"><?php echo $now; ?></b>
        </div>
    </div>
</div>

<script>
document.getElementById('vinaora-total').onclick = function () {
    const d = document.getElementById('vinaora-details');
    if (d.style.display === 'block') {
        d.style.display = 'none';
        this.style.borderRadius = '0 0 12px 12px';
    } else {
        d.style.display = 'block';
        this.style.borderRadius = '0';
    }
};

document.getElementById('vinaora-close').onclick = function () {
    document.getElementById('vinaora-counter').style.display = 'none';
};

// Auto-hide after 10 seconds of inactivity
let hideTimeout;
function resetHideTimeout() {
    clearTimeout(hideTimeout);
    hideTimeout = setTimeout(() => {
        const details = document.getElementById('vinaora-details');
        if (details.style.display === 'block') {
            details.style.display = 'none';
            document.getElementById('vinaora-total').style.borderRadius = '0 0 12px 12px';
        }
    }, 10000);
}

// Reset timeout on mouse movement
document.addEventListener('mousemove', resetHideTimeout);
resetHideTimeout(); // Start the timeout
</script>