<?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();
    liveCallEnsureSchema($pdo);
    $settings = liveCallSettings($pdo);
    $input = liveCallReadInput();
    $sessionId = (int)($input['session_id'] ?? 0);
    $userId = (int)($input['user_id'] ?? 0);
    if ($sessionId <= 0 || $userId <= 0) {
        throw new Exception('session_id and user_id are required');
    }

    $session = liveCallSessionById($pdo, $sessionId);
    if (!$session || (int)$session['user_id'] !== $userId) {
        throw new Exception('Call session not found');
    }

    if (in_array($session['status'], ['ended', 'cancelled', 'rejected'], true)) {
        liveCallJson([
            'success' => true,
            'call_ended' => true,
            'status' => $session['status'],
            'end_reason' => $session['end_reason'] ?? 'Call ended',
            'balance' => liveCallBalance($pdo, $userId)
        ]);
    }

    if (in_array($session['status'], ['requested', 'ringing'], true)) {
        $stmt = $pdo->prepare("
            UPDATE live_call_sessions
            SET last_heartbeat_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute([$sessionId]);
        liveCallJson([
            'success' => true,
            'call_ended' => false,
            'waiting_for_guru' => true,
            'balance' => liveCallBalance($pdo, $userId),
            'charged_amount' => (float)$session['charged_amount'],
            'billed_seconds' => (int)$session['billed_seconds'],
            'extended_seconds' => (int)$session['admin_extension_seconds'],
            'status' => $session['status']
        ]);
    }

    $tickSeconds = max(5, (int)($settings['live_call_tick_seconds'] ?? 10));
    $ratePerMinute = (float)$session['rate_per_minute'];
    $charge = round(($ratePerMinute / 60) * $tickSeconds, 2);
    $balance = liveCallBalance($pdo, $userId);
    $extendedSeconds = max(0, (int)$session['admin_extension_seconds']);
    $newBalance = $balance;
    $endCall = false;
    $endReason = null;

    $pdo->beginTransaction();
    try {
        if ($balance >= $charge) {
            $newBalance = liveCallDebit($pdo, $userId, $charge, $sessionId);
            $stmt = $pdo->prepare("
                UPDATE live_call_sessions
                SET status = 'active',
                    started_at = COALESCE(started_at, NOW()),
                    billed_seconds = billed_seconds + ?,
                    charged_amount = charged_amount + ?,
                    last_heartbeat_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$tickSeconds, $charge, $sessionId]);
        } elseif ($extendedSeconds > 0) {
            $useSeconds = min($tickSeconds, $extendedSeconds);
            $stmt = $pdo->prepare("
                UPDATE live_call_sessions
                SET status = 'active',
                    started_at = COALESCE(started_at, NOW()),
                    billed_seconds = billed_seconds + ?,
                    admin_extension_seconds = admin_extension_seconds - ?,
                    last_heartbeat_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$useSeconds, $useSeconds, $sessionId]);
        } else {
            $endCall = true;
            $endReason = 'Wallet balance finished';
            $stmt = $pdo->prepare("
                UPDATE live_call_sessions
                SET status = 'ended', ended_at = NOW(), end_reason = ?, last_heartbeat_at = NOW()
                WHERE id = ?
            ");
            $stmt->execute([$endReason, $sessionId]);
        }
        $pdo->commit();
    } catch (Exception $e) {
        $pdo->rollBack();
        throw $e;
    }

    $updated = liveCallSessionById($pdo, $sessionId);
    liveCallJson([
        'success' => true,
        'call_ended' => $endCall,
        'end_reason' => $endReason,
        'balance' => $newBalance,
        'charged_amount' => (float)$updated['charged_amount'],
        'billed_seconds' => (int)$updated['billed_seconds'],
        'extended_seconds' => (int)$updated['admin_extension_seconds'],
        'status' => $updated['status']
    ]);
} catch (Exception $e) {
    liveCallJson(['success' => false, 'message' => $e->getMessage()], 400);
}
?>
