<?php
/**
 * Send Chat Notification API
 * This is called by the frontend after sending a message to Firebase RTDB
 */


require_once 'bootstrap.php';
require_once '../admin/includes/notification_helper.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    http_response_code(405);
    echo json_encode(['success' => false, 'error' => 'Method not allowed']);
    exit;
}

$input = json_decode(file_get_contents('php://input'), true);
$booking_id = $input['booking_id'] ?? null;
$message = $input['message'] ?? '';
$sender_name = $input['sender_name'] ?? 'Someone';
$sender_type = $input['sender_type'] ?? 'customer'; // 'customer', 'admin', 'driver'

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

try {
    $pdo = getDBConnection();

    // Find recipient
    $stmt = $pdo->prepare("SELECT user_id, reference_number FROM bookings WHERE id = ?");
    $stmt->execute([$booking_id]);
    $booking = $stmt->fetch();

    if (!$booking) {
        http_response_code(404);
        echo json_encode(['success' => false, 'error' => 'Booking not found']);
        exit;
    }

    if ($sender_type === 'admin') {
        // Recipient is customer
        addNotification(
            $booking['user_id'],
            "New message from Admin",
            "Admin: " . (strlen($message) > 50 ? substr($message, 0, 47) . '...' : $message),
            'info',
            "chat.php?booking_id=" . $booking_id,
            'customer'
        );
    } else {
        // Recipient is admin (customer or driver sent the message)
        // For simplicity, we notify all admins or a specific one if assigned?
        // Let's notify all admins for now as there's no "assigned admin" in bookings table
        notifyAdmins(
            "New message for #{$booking['reference_number']}",
            "{$sender_name}: " . (strlen($message) > 50 ? substr($message, 0, 47) . '...' : $message),
            'info',
            "messages.php?booking_id=" . $booking_id
        );
    }

    echo json_encode(['success' => true]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
