<?php
// send_message_ajax.php
require 'config/db.php';


header('Content-Type: application/json'); // Ahora respondemos en JSON

if (!isset($_SESSION['user_id'])) { 
    echo json_encode(["status" => "error", "message" => "session_expired"]);
    exit; 
}

$my_id = (int)$_SESSION['user_id'];
$receiver_id = isset($_POST['receiver_id']) ? (int)$_POST['receiver_id'] : 0;
$message_text = isset($_POST['message']) ? trim($_POST['message']) : '';

if ($my_id === $receiver_id) {
    echo json_encode(["status" => "error", "message" => "self_message"]);
    exit;
}

if ($receiver_id > 0 && !empty($message_text)) {
    try {
        $sql = "INSERT INTO messages (sender_id, receiver_id, message, is_read, created_at) 
                VALUES (?, ?, ?, 0, NOW())";
        
        $stmt = $pdo->prepare($sql);
        
        if ($stmt->execute([$my_id, $receiver_id, $message_text])) {
            // DEVOLVEMOS ÉXITO Y EL ID DEL MENSAJE RECIÉN CREADO
            echo json_encode([
                "status" => "success", 
                "last_id" => $pdo->lastInsertId() 
            ]);
        } else {
            echo json_encode(["status" => "error", "message" => "execution_failed"]);
        }
    } catch (PDOException $e) {
        error_log("Chat Error: " . $e->getMessage());
        echo json_encode(["status" => "error", "message" => "db_error"]);
    }
} else {
    echo json_encode(["status" => "error", "message" => "invalid_data"]);
}