<?php
// ============================================
// User Activity Tracking Helper
// ============================================

function activity_ensure_table($pdo){
    static $done=false; if($done) return; $done=true;
    $pdo->exec("CREATE TABLE IF NOT EXISTS user_activity (
        id INT AUTO_INCREMENT PRIMARY KEY,
        user_id INT NOT NULL,
        session_id VARCHAR(128) NOT NULL,
        ip VARCHAR(64) DEFAULT NULL,
        country VARCHAR(80) DEFAULT NULL,
        region VARCHAR(80) DEFAULT NULL,
        city VARCHAR(80) DEFAULT NULL,
        user_agent TEXT,
        browser VARCHAR(64) DEFAULT NULL,
        browser_version VARCHAR(32) DEFAULT NULL,
        os VARCHAR(64) DEFAULT NULL,
        device VARCHAR(32) DEFAULT NULL,
        login_at DATETIME DEFAULT NULL,
        last_seen_at DATETIME DEFAULT NULL,
        INDEX (user_id), INDEX (session_id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
}

function activity_client_ip(){
    foreach(['HTTP_CF_CONNECTING_IP','HTTP_X_FORWARDED_FOR','HTTP_X_REAL_IP','REMOTE_ADDR'] as $k){
        if(!empty($_SERVER[$k])){
            $ip=trim(explode(',',$_SERVER[$k])[0]);
            if(filter_var($ip,FILTER_VALIDATE_IP)) return $ip;
        }
    }
    return $_SERVER['REMOTE_ADDR']??'';
}

function activity_parse_ua($ua){
    $b='Unknown'; $v=''; $os='Unknown'; $d='Desktop';
    if(preg_match('#(Edg|Edge)/([\d.]+)#',$ua,$m)){$b='Edge';$v=$m[2];}
    elseif(preg_match('#OPR/([\d.]+)#',$ua,$m)){$b='Opera';$v=$m[1];}
    elseif(preg_match('#Firefox/([\d.]+)#',$ua,$m)){$b='Firefox';$v=$m[1];}
    elseif(preg_match('#Chrome/([\d.]+)#',$ua,$m)){$b='Chrome';$v=$m[1];}
    elseif(preg_match('#Version/([\d.]+).*Safari#',$ua,$m)){$b='Safari';$v=$m[1];}
    elseif(preg_match('#MSIE ([\d.]+)#',$ua,$m)){$b='IE';$v=$m[1];}

    if(stripos($ua,'Windows NT 10')!==false)$os='Windows 10/11';
    elseif(stripos($ua,'Windows')!==false)$os='Windows';
    elseif(stripos($ua,'Android')!==false){$os='Android';$d='Mobile';}
    elseif(stripos($ua,'iPhone')!==false){$os='iOS';$d='Mobile';}
    elseif(stripos($ua,'iPad')!==false){$os='iPadOS';$d='Tablet';}
    elseif(stripos($ua,'Mac OS')!==false)$os='macOS';
    elseif(stripos($ua,'Linux')!==false)$os='Linux';

    if(stripos($ua,'Mobile')!==false && $d==='Desktop') $d='Mobile';
    return [$b,$v,$os,$d];
}

function activity_geoip($ip){
    if(!$ip || $ip==='127.0.0.1' || strpos($ip,'192.168.')===0 || strpos($ip,'10.')===0) return null;
    $ctx=stream_context_create(['http'=>['timeout'=>2]]);
    $j=@file_get_contents("http://ip-api.com/json/{$ip}?fields=status,country,regionName,city",false,$ctx);
    if(!$j) return null;
    $d=json_decode($j,true);
    if(!$d || ($d['status']??'')!=='success') return null;
    return ['country'=>$d['country']??null,'region'=>$d['regionName']??null,'city'=>$d['city']??null];
}

function activity_log_login($pdo,$user_id){
    activity_ensure_table($pdo);
    $ip=activity_client_ip();
    $ua=$_SERVER['HTTP_USER_AGENT']??'';
    [$b,$v,$os,$d]=activity_parse_ua($ua);
    $geo=activity_geoip($ip);
    $sid=session_id();
    $st=$pdo->prepare("INSERT INTO user_activity
      (user_id,session_id,ip,country,region,city,user_agent,browser,browser_version,os,device,login_at,last_seen_at)
      VALUES(?,?,?,?,?,?,?,?,?,?,?,NOW(),NOW())");
    $st->execute([$user_id,$sid,$ip,$geo['country']??null,$geo['region']??null,$geo['city']??null,$ua,$b,$v,$os,$d]);
    $_SESSION['activity_id']=$pdo->lastInsertId();
}

function activity_heartbeat($pdo){
    if(empty($_SESSION['uid']) || empty($_SESSION['activity_id'])) return;
    activity_ensure_table($pdo);
    // throttle: only update once per 30s
    $t=$_SESSION['activity_last_ping']??0;
    if(time()-$t < 30) return;
    $_SESSION['activity_last_ping']=time();
    $pdo->prepare("UPDATE user_activity SET last_seen_at=NOW() WHERE id=?")
        ->execute([$_SESSION['activity_id']]);
}
