<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') exit(0);

require_once 'live_call_common.php';

try {
    $pdo = getDBConnection();
    $settings = liveCallSettings($pdo);
    $userId = isset($_GET['user_id']) ? (int)$_GET['user_id'] : 0;
    $active = liveCallActiveSession($pdo);
    $balance = $userId > 0 ? liveCallBalance($pdo, $userId) : 0;
    $hasCompletedCall = $userId > 0 ? liveCallUserHasCompletedCall($pdo, $userId) : false;
    if ($active && $userId > 0 && (int)$active['user_id'] === $userId) {
        $active['agora_token'] = liveCallAgoraToken($settings, (string)$active['channel_name'], (int)$active['agora_uid']);
        $active['agora_token_required'] = trim((string)($settings['live_call_agora_app_certificate'] ?? '')) !== '';
    }

    liveCallJson([
        'success' => true,
        'system_enabled' => liveCallBool($settings['live_call_system_enabled'] ?? 'off'),
        'guru_online' => liveCallBool($settings['guru_online'] ?? 'off'),
        'audio_enabled' => liveCallBool($settings['live_call_audio_enabled'] ?? 'on'),
        'video_enabled' => liveCallBool($settings['live_call_video_enabled'] ?? 'on'),
        'audio_rate_per_minute' => (float)($settings['live_call_audio_rate_per_minute'] ?? 20),
        'video_rate_per_minute' => (float)($settings['live_call_video_rate_per_minute'] ?? 40),
        'minimum_first_call_balance' => (float)($settings['live_call_min_first_call_balance'] ?? 200),
        'minimum_wallet_balance' => (float)($settings['live_call_min_wallet_balance'] ?? 100),
        'tick_seconds' => (int)($settings['live_call_tick_seconds'] ?? 10),
        'agora_app_id' => $settings['live_call_agora_app_id'] ?? '',
        'user_balance' => $balance,
        'is_first_call' => !$hasCompletedCall,
        'busy' => $active !== null,
        'active_session' => $active
    ]);
} catch (Exception $e) {
    liveCallJson(['success' => false, 'message' => $e->getMessage()], 400);
}
?>
