<?php
// Lightweight heartbeat - SQLite version
header('Content-Type: application/json');
header('Cache-Control: no-cache');

$dbPath = __DIR__ . '/data/database.sqlite';

try {
    $db = new PDO('sqlite:' . $dbPath);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $db->exec('PRAGMA journal_mode = WAL');
    $db->exec('PRAGMA busy_timeout = 3000');
    
    // إنشاء الجدول إذا لم يكن موجوداً
    $db->exec('CREATE TABLE IF NOT EXISTS heartbeats (
        session_id TEXT PRIMARY KEY,
        time INTEGER DEFAULT 0,
        ms INTEGER DEFAULT 0,
        user_id INTEGER DEFAULT 0
    )');
    
    $sid = isset($_COOKIE['PHPSESSID']) ? $_COOKIE['PHPSESSID'] : '';
    $uid = isset($_GET['uid']) ? intval($_GET['uid']) : 0;
    
    if ($sid) {
        $stmt = $db->prepare('INSERT OR REPLACE INTO heartbeats (session_id, time, ms, user_id) VALUES (:sid, :time, :ms, :uid)');
        $stmt->execute([
            ':sid' => $sid,
            ':time' => time(),
            ':ms' => round(microtime(true) * 1000),
            ':uid' => $uid
        ]);
    }
    
    // تنظيف السجلات القديمة (أكثر من 15 ثانية)
    $cutoff = time() - 15;
    $db->exec("DELETE FROM heartbeats WHERE time < {$cutoff}");
    
    echo json_encode(['ok' => true]);
    
} catch (PDOException $e) {
    echo json_encode(['ok' => false, 'error' => $e->getMessage()]);
}
