<?php
session_start();
require_once 'functions.php';
require_once '../main_db_connect.php'; // Ensure the DB connection is included

$response = ['success' => false, 'error' => ''];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!isset($_SESSION['sender_id'])) {
        $response['error'] = 'Sender ID not set in session.';
        echo json_encode($response);
        exit();
    }

    $senderId = $_SESSION['sender_id'];
    $userDetails = getUserDetails($senderId);
    $fullName = $userDetails['full_name'] ?? 'N/A';
    $username = $userDetails['username'] ?? 'N/A';
    $email = $userDetails['email'] ?? 'N/A';
    $phoneNumber = $userDetails['phone_number'] ?? 'N/A';
    $message = $_POST['message'];

    if (sendMessageWithDetails($senderId, $fullName, $username, $email, $phoneNumber, $message)) {
        $response['success'] = true;
        // Reload the dashboard to restore the UI state
        header("Location: user_dashboard.php?message_sent=1");
        exit();
    } else {
        $response['error'] = 'Failed to send message.';
    }
} else {
    $response['error'] = 'Invalid request method.';
}

echo json_encode($response);

function sendMessageWithDetails($senderId, $fullName, $username, $email, $phoneNumber, $message) {
    global $conn;
    $stmt = $conn->prepare("INSERT INTO messages (sender_id, full_name, username, email, phone_number, message) VALUES (?, ?, ?, ?, ?, ?)");
    if ($stmt === false) {
        error_log('Prepare failed: ' . htmlspecialchars($conn->error));
        return false;
    }
    $stmt->bind_param("isssss", $senderId, $fullName, $username, $email, $phoneNumber, $message);
    $result = $stmt->execute();
    if ($result === false) {
        error_log('Execute failed: ' . htmlspecialchars($stmt->error));
    }
    $stmt->close();
    return $result;
}
?>
