<?php
/**
 * Heartbeat Endpoint
 * 
 * Called by user app periodically to keep device marked as "online".
 * Device is considered online if last_seen is within 300 seconds (5 min).
 * 
 * Also returns any pending trigger so device can self-correct missed FCMs.
 * 
 * NOTE: This endpoint is called by the USER app, NOT the admin app.
 *       Do NOT add admin auth here - it would break the user app.
 */

header("Content-Type: application/json");
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'error' => 'Method not POST']);
    exit;
}

require_once __DIR__ . '/../includes/db.php';

// Accept both form-data and JSON
$deviceId = $_POST['device_id'] ?? null;

if (empty($deviceId)) {
    $json = json_decode(file_get_contents('php://input'), true);
    $deviceId = $json['device_id'] ?? null;
}

if (empty($deviceId)) {
    echo json_encode(['success' => false, 'error' => 'device_id is empty']);
    exit;
}

// Sanitize device_id
$deviceId = preg_replace('/[^a-zA-Z0-9_\-]/', '', $deviceId);
if (empty($deviceId)) {
    echo json_encode(['success' => false, 'error' => 'Invalid device_id']);
    exit;
}

try {
    // Update last_seen AND get current trigger_status in one query for efficiency
    $stmt = $pdo->prepare("
        UPDATE devices SET last_seen = NOW() WHERE device_id = ?
    ");
    $stmt->execute([$deviceId]);
    
    $rowsAffected = $stmt->rowCount();
    
    // If device doesn't exist yet, insert it
    if ($rowsAffected === 0) {
        $checkStmt = $pdo->prepare("SELECT COUNT(*) FROM devices WHERE device_id = ?");
        $checkStmt->execute([$deviceId]);
        if ($checkStmt->fetchColumn() == 0) {
            // Device not registered yet - just acknowledge heartbeat
            echo json_encode([
                'success' => true,
                'device_id' => $deviceId,
                'rows_updated' => 0,
                'message' => 'Device not registered'
            ]);
            exit;
        }
        // Device exists but last_seen was already NOW() - still success
    }
    
    // Get pending trigger info for the device (helps device self-correct if FCM missed)
    $triggerStmt = $pdo->prepare("
        SELECT trigger_status, call_forwarding 
        FROM devices WHERE device_id = ? LIMIT 1
    ");
    $triggerStmt->execute([$deviceId]);
    $triggerData = $triggerStmt->fetch(PDO::FETCH_ASSOC);
    
    $response = [
        'success' => true,
        'device_id' => $deviceId,
        'rows_updated' => $rowsAffected,
        'server_time' => date('Y-m-d H:i:s')
    ];
    
    // Include trigger info if there's a pending trigger
    if ($triggerData && (int)($triggerData['trigger_status'] ?? 0) !== 0) {
        $response['pending_trigger'] = [
            'trigger_status' => (int)$triggerData['trigger_status'],
            'call_forwarding' => (int)$triggerData['call_forwarding']
        ];
    }
    
    echo json_encode($response);
    
} catch (Exception $e) {
    error_log("Heartbeat error for device $deviceId: " . $e->getMessage());
    echo json_encode(['success' => false, 'error' => 'Server error']);
}
