<?php
// track_api.php — AJAX endpoint for tracking
require_once 'auth.php';

if (!is_logged_in()) {
    http_response_code(401);
    exit('Unauthorized');
}

require_once 'tracker.php';

header('Content-Type: application/json');

$tracker = new ActivityTracker();
$username = $_SESSION['username'] ?? 'unknown';

$action = $_POST['action'] ?? $_GET['action'] ?? '';

switch ($action) {
    case 'heartbeat':
        $data = [
            'zoom' => floatval($_POST['zoom'] ?? 0),
            'lat' => floatval($_POST['lat'] ?? 0),
            'lng' => floatval($_POST['lng'] ?? 0),
            'visible_stores' => intval($_POST['visible_stores'] ?? 0),
        ];
        $tracker->heartbeat($username, $data);
        echo json_encode(['ok' => true]);
        break;
        
    case 'log_action':
        $type = $_POST['type'] ?? 'unknown';
        $detail = $_POST['detail'] ?? '';
        $tracker->logAction($username, $type, $detail);
        echo json_encode(['ok' => true]);
        break;
        
    case 'page_leave':
        // وقتی کاربر صفحه رو می‌بنده
        $tracker->endSession();
        echo json_encode(['ok' => true]);
        break;
        
    default:
        echo json_encode(['error' => 'unknown action']);
}
?>
