<?php
// File: send_message.php
// Location: siro_v1/ride/chat/send_message.php
require_once __DIR__ . '/../../connect.php';

error_log("--- [send_message.php] Received new chat message logging request ---");

$ride_id         = filterRequest("ride_id");
$sender_id       = filterRequest("sender_id");
$receiver_id     = filterRequest("receiver_id");
$sender_type     = filterRequest("sender_type");
$message_content = filterRequest("message_content");

if (empty($ride_id) || empty($sender_id) || empty($receiver_id) || empty($sender_type) || empty($message_content)) {
    error_log("❌ [send_message.php] Missing required fields.");
    jsonError("All fields (ride_id, sender_id, receiver_id, sender_type, message_content) are required.");
    exit();
}

if (!in_array($sender_type, ['passenger', 'driver'])) {
    error_log("❌ [send_message.php] Invalid sender_type: $sender_type");
    jsonError("sender_type must be either 'passenger' or 'driver'.");
    exit();
}

try {
    $stmt = $con->prepare("
        INSERT INTO `ride_chat_logs` 
            (`ride_id`, `sender_id`, `receiver_id`, `sender_type`, `message_content`, `created_at`)
        VALUES (?, ?, ?, ?, ?, NOW())
    ");
    $stmt->execute([$ride_id, $sender_id, $receiver_id, $sender_type, $message_content]);
    
    error_log("✅ [send_message.php] Saved message successfully for ride_id: $ride_id");
    jsonSuccess(null, "Message saved successfully.");

} catch (PDOException $e) {
    error_log("❌ [send_message.php] Database Error: " . $e->getMessage());
    jsonError("Database error: " . $e->getMessage());
}
?>
