<?php
/**
 * Chat API Endpoint
 * Handles fetching participant details for the Firebase chat.
 */



header('Access-Control-Allow-Methods: GET, POST, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type');

if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

require_once 'bootstrap.php';

// Check authentication
if (!isset($_SESSION['user_id']) && !isset($_SESSION['admin_id'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'error' => 'Unauthorized']);
    exit;
}

$pdo = getDBConnection();
if (!$pdo) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => 'Database connection failed']);
    exit;
}

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $action = $_GET['action'] ?? 'get_messages';
    $booking_id = $_GET['booking_id'] ?? null;

    if (!$booking_id) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Booking ID required']);
        exit;
    }

    if ($action === 'get_participants') {
        // Fetch participant details for the chat UI
        $stmt = $pdo->prepare("
            SELECT b.reference_number, 
                   u.first_name as client_name, u.last_name as client_last_name,
                   d.first_name as driver_name, d.last_name as driver_last_name
            FROM bookings b
            LEFT JOIN users u ON b.user_id = u.id
            LEFT JOIN drivers d ON b.driver_id = d.id
            WHERE b.id = ?
        ");
        $stmt->execute([$booking_id]);
        $data = $stmt->fetch();

        if ($data) {
            echo json_encode(['success' => true, 'data' => $data]);
        } else {
            echo json_encode(['success' => false, 'error' => 'Booking not found']);
        }
        exit;
    }

    // Legacy support for fetching messages (optional, if they still want local DB fallback)
    $last_id = intval($_GET['last_id'] ?? 0);
    $stmt = $pdo->prepare("
        SELECT c.*, u.first_name, u.last_name, u.user_type
        FROM chats c
        JOIN users u ON c.sender_id = u.id
        WHERE c.booking_id = ? AND c.id > ?
        ORDER BY c.created_at ASC
    ");
    $stmt->execute([$booking_id, $last_id]);
    $messages = $stmt->fetchAll();

    echo json_encode(['success' => true, 'messages' => $messages]);

} elseif ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Legacy support for sending messages to local DB
    $input = json_decode(file_get_contents('php://input'), true);
    $booking_id = $input['booking_id'] ?? $_POST['booking_id'] ?? null;
    $message = trim($input['message'] ?? $_POST['message'] ?? '');
    $user_id = $_SESSION['user_id'] ?? $_SESSION['admin_id'];

    if (!$booking_id || empty($message)) {
        http_response_code(400);
        echo json_encode(['success' => false, 'error' => 'Booking ID and message are required']);
        exit;
    }

    $stmt = $pdo->prepare("INSERT INTO chats (booking_id, sender_id, message) VALUES (?, ?, ?)");
    $stmt->execute([$booking_id, $user_id, $message]);

    echo json_encode(['success' => true, 'message_id' => $pdo->lastInsertId()]);
} else {
    http_response_code(405);
}
?>
