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

require_once 'live_call_common.php';

try {
    $pdo = getDBConnection();
    liveCallEnsureSchema($pdo);

    if ($_SERVER['REQUEST_METHOD'] === 'POST') {
        $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');
        }

        $stmt = $pdo->prepare("
            SELECT id FROM live_call_queue
            WHERE user_id = ? AND status = 'waiting'
            LIMIT 1
        ");
        $stmt->execute([$userId]);
        $existing = $stmt->fetchColumn();
        if ($existing) {
            liveCallJson(['success' => true, 'message' => 'Already in queue', 'queue_id' => (int)$existing]);
        }

        $stmt = $pdo->prepare("
            INSERT INTO live_call_queue (user_id, call_type, status, created_at)
            VALUES (?, ?, 'waiting', NOW())
        ");
        $stmt->execute([$userId, $callType]);
        liveCallJson(['success' => true, 'message' => 'Joined queue', 'queue_id' => (int)$pdo->lastInsertId()]);
    }

    $stmt = $pdo->query("
        SELECT q.*, u.name AS user_name, u.mobile AS user_mobile
        FROM live_call_queue q
        LEFT JOIN users u ON u.id = q.user_id
        WHERE q.status = 'waiting'
        ORDER BY q.created_at ASC
    ");
    liveCallJson(['success' => true, 'queue' => $stmt->fetchAll(PDO::FETCH_ASSOC)]);
} catch (Exception $e) {
    liveCallJson(['success' => false, 'message' => $e->getMessage()], 400);
}
?>
