<?php
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') exit(0);

require_once 'live_call_common.php';

try {
    if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
        liveCallJson(['success' => false, 'message' => 'Method not allowed'], 405);
    }

    $pdo = getDBConnection();
    $settings = liveCallSettings($pdo);
    $input = liveCallReadInput();
    $userId = (int)($input['user_id'] ?? 0);
    $callType = strtolower(trim($input['call_type'] ?? 'audio'));

    if ($userId <= 0) {
        throw new Exception('Valid user_id is required');
    }
    if (!in_array($callType, ['audio', 'video'], true)) {
        throw new Exception('call_type must be audio or video');
    }
    if (!liveCallBool($settings['live_call_system_enabled'] ?? 'off') || !liveCallBool($settings['guru_online'] ?? 'off')) {
        throw new Exception('Guruji is currently offline');
    }
    if ($callType === 'audio' && !liveCallBool($settings['live_call_audio_enabled'] ?? 'on')) {
        throw new Exception('Audio call is currently disabled');
    }
    if ($callType === 'video' && !liveCallBool($settings['live_call_video_enabled'] ?? 'on')) {
        throw new Exception('Video call is currently disabled');
    }

    $active = liveCallActiveSession($pdo);
    if ($active !== null) {
        liveCallJson([
            'success' => false,
            'busy' => true,
            'message' => 'Guruji is busy. You can join the queue.',
            'active_session_id' => $active['id']
        ], 200);
    }

    $balance = liveCallBalance($pdo, $userId);
    $isFirstCall = !liveCallUserHasCompletedCall($pdo, $userId);
    $minimumBalance = $isFirstCall
        ? (float)($settings['live_call_min_first_call_balance'] ?? 200)
        : (float)($settings['live_call_min_wallet_balance'] ?? 100);

    if ($balance < $minimumBalance) {
        throw new Exception("Minimum wallet balance ₹" . number_format($minimumBalance, 0) . " required to start call");
    }

    $rate = $callType === 'video'
        ? (float)($settings['live_call_video_rate_per_minute'] ?? 40)
        : (float)($settings['live_call_audio_rate_per_minute'] ?? 20);
    $channelName = 'astro_call_' . $userId . '_' . time();
    $agoraUid = $userId + 1000;
    $guruUid = 1;

    $stmt = $pdo->prepare("
        INSERT INTO live_call_sessions (
            user_id, call_type, channel_name, agora_uid, guru_uid,
            status, rate_per_minute, last_heartbeat_at
        ) VALUES (?, ?, ?, ?, ?, 'ringing', ?, NOW())
    ");
    $stmt->execute([$userId, $callType, $channelName, $agoraUid, $guruUid, $rate]);
    $sessionId = (int)$pdo->lastInsertId();
    $agoraToken = liveCallAgoraToken($settings, $channelName, $agoraUid);

    liveCallJson([
        'success' => true,
        'message' => 'Call started',
        'session_id' => $sessionId,
        'call_type' => $callType,
        'channel_name' => $channelName,
        'agora_app_id' => $settings['live_call_agora_app_id'] ?? '',
        'agora_token' => $agoraToken,
        'agora_token_required' => trim((string)($settings['live_call_agora_app_certificate'] ?? '')) !== '',
        'agora_uid' => $agoraUid,
        'guru_uid' => $guruUid,
        'rate_per_minute' => $rate,
        'tick_seconds' => (int)($settings['live_call_tick_seconds'] ?? 10),
        'balance' => $balance,
        'is_first_call' => $isFirstCall
    ]);
} catch (Exception $e) {
    liveCallJson(['success' => false, 'message' => $e->getMessage()], 400);
}
?>
