<?php
/*******************************************************************************************************************
| SRS Webhook Handler
| Handles callbacks from SRS server for live streaming events
|*******************************************************************************************************************/

define('_ISVALID', true);
require_once '../../f_core/config.core.php';

// Set JSON response headers
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

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

try {
    $liveStreaming = new VLiveStreaming();
    $logger = VLogger::getInstance();
    
    // Get request data
    $input = file_get_contents('php://input');
    $data = json_decode($input, true);
    
    if (!$data) {
        throw new Exception('Invalid JSON data');
    }
    
    // Determine action from URL path
    $path = $_SERVER['REQUEST_URI'] ?? '';
    $action = '';
    
    // Parse SRS webhook action
    if (isset($data['action'])) {
        $action = $data['action'];
    } elseif (strpos($path, 'on_connect') !== false) {
        $action = 'on_connect';
    } elseif (strpos($path, 'on_close') !== false) {
        $action = 'on_close';
    } elseif (strpos($path, 'on_publish') !== false) {
        $action = 'on_publish';
    } elseif (strpos($path, 'on_unpublish') !== false) {
        $action = 'on_unpublish';
    } elseif (strpos($path, 'on_play') !== false) {
        $action = 'on_play';
    } elseif (strpos($path, 'on_stop') !== false) {
        $action = 'on_stop';
    } elseif (strpos($path, 'on_dvr') !== false) {
        $action = 'on_dvr';
    } elseif (strpos($path, 'on_hls') !== false) {
        $action = 'on_hls';
    } elseif (strpos($path, 'heartbeat') !== false) {
        $action = 'heartbeat';
    }
    
    $logger->info('SRS webhook received', [
        'action' => $action,
        'data' => $data,
        'path' => $path
    ]);
    
    // Handle heartbeat separately
    if ($action === 'heartbeat') {
        // Update SRS server status
        updateSRSStatus($data);
        
        echo json_encode(['code' => 0, 'message' => 'heartbeat received']);
        exit;
    }
    
    // Handle stream webhooks
    $response = $liveStreaming->handleSRSWebhook($action, $data);
    
    echo json_encode($response);
    
} catch (Exception $e) {
    $logger->error('SRS webhook error', [
        'error' => $e->getMessage(),
        'input' => $input ?? '',
        'path' => $_SERVER['REQUEST_URI'] ?? ''
    ]);
    
    // Return error response
    echo json_encode([
        'code' => 1,
        'message' => $e->getMessage()
    ]);
}

/**
 * Update SRS server status
 * @param array $data Heartbeat data
 */
function updateSRSStatus($data)
{
    try {
        $db = VDatabase::getInstance();
        
        $statusData = [
            'server_id' => $data['device_id'] ?? 'srs-server',
            'status' => 'online',
            'last_heartbeat' => date('Y-m-d H:i:s'),
            'data' => json_encode($data),
            'updated_at' => date('Y-m-d H:i:s')
        ];
        
        // Insert or update server status
        $existing = $db->doQuery("SELECT id FROM db_srs_servers WHERE server_id = ?", [$statusData['server_id']]);
        
        if ($db->doFetch($existing)) {
            $db->doUpdate('db_srs_servers', 'server_id', $statusData, $statusData['server_id']);
        } else {
            $statusData['created_at'] = date('Y-m-d H:i:s');
            $db->doInsert('db_srs_servers', $statusData);
        }
        
    } catch (Exception $e) {
        VLogger::getInstance()->error('Failed to update SRS status', [
            'error' => $e->getMessage(),
            'data' => $data
        ]);
    }
}
?>