<?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);
    $input = liveCallReadInput();
    $sessionId = (int)($input['session_id'] ?? 0);
    $reason = trim($input['reason'] ?? 'Call ended');

    if ($sessionId <= 0) {
        throw new Exception('session_id is required');
    }

    $session = liveCallSessionById($pdo, $sessionId);
    if (!$session) {
        throw new Exception('Call session not found');
    }

    if (!in_array($session['status'], ['ended', 'cancelled', 'rejected'], true)) {
        $stmt = $pdo->prepare("
            UPDATE live_call_sessions
            SET status = 'ended', ended_at = NOW(), end_reason = ?, updated_at = NOW()
            WHERE id = ?
        ");
        $stmt->execute([$reason, $sessionId]);
    }

    $updated = liveCallSessionById($pdo, $sessionId);
    liveCallJson([
        'success' => true,
        'message' => 'Call ended',
        'session' => $updated,
        'balance' => liveCallBalance($pdo, (int)$updated['user_id'])
    ]);
} catch (Exception $e) {
    liveCallJson(['success' => false, 'message' => $e->getMessage()], 400);
}
?>
