<?php
/**
 * Heartbeat API - Ping + Stats
 * POST /api/heartbeat.php
 */

header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type, X-License-Key');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once '../config.php';

$input = json_decode(file_get_contents('php://input'), true);
$licenseKey = $input['license_key'] ?? $_SERVER['HTTP_X_LICENSE_KEY'] ?? '';

if (empty($licenseKey)) {
    jsonResponse(['status' => 'error', 'message' => 'License key required'], 400);
}

try {
    // Find instance
    $stmt = $pdo->prepare("SELECT id FROM instances WHERE license_key = ? AND is_active = 1");
    $stmt->execute([$licenseKey]);
    $instance = $stmt->fetch();

    if (!$instance) {
        jsonResponse(['status' => 'error', 'message' => 'Invalid license'], 401);
    }

    // Update heartbeat
    $stmt = $pdo->prepare("UPDATE instances SET last_heartbeat = NOW(), server_ip = ? WHERE id = ?");
    $stmt->execute([$_SERVER['REMOTE_ADDR'] ?? '', $instance['id']]);

    // Record telemetry
    $stmt = $pdo->prepare("
        INSERT INTO telemetry (instance_id, event_type, user_count, storage_used_mb, active_sessions, payload, client_ip)
        VALUES (?, 'heartbeat', ?, ?, ?, ?, ?)
    ");
    $stmt->execute([
        $instance['id'],
        intval($input['user_count'] ?? 0),
        intval($input['storage_used_mb'] ?? 0),
        intval($input['active_sessions'] ?? 0),
        json_encode($input['payload'] ?? []),
        $_SERVER['REMOTE_ADDR'] ?? ''
    ]);

    jsonResponse([
        'status' => 'ok',
        'message' => 'Heartbeat recorded',
        'server_time' => date('c')
    ]);

} catch (Exception $e) {
    jsonResponse([
        'status' => 'error',
        'message' => 'Server error'
    ], 500);
}
