<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

require_once "../php/db_connect.php";

// Check if user is logged in
if (!isset($_SESSION["user_id"], $_SESSION["role"])) {
    header("Location: index.php");
    exit();
}

$sender_user_id = (int) $_SESSION["user_id"];
$receiver_user_id = (int) ($_POST["receiver_user_id"] ?? 0);
$order_id = !empty($_POST["order_id"]) ? (int) $_POST["order_id"] : null;
$message_text = trim($_POST["message_text"] ?? "");

// Basic validation
if ($receiver_user_id <= 0 || $message_text === "") {
    echo json_encode([
        'status' => 'error',
        'error' => 'Invalid message.'
    ]);
    exit();
}

if ($sender_user_id === $receiver_user_id) {
    echo json_encode([
        'status' => 'error',
        'error' => 'You cannot message yourself.'
    ]);
    exit();
}

// Verify receiver exists
$checkUser = $conn->prepare("SELECT id FROM users WHERE id = ? LIMIT 1");
$checkUser->bind_param("i", $receiver_user_id);
$checkUser->execute();
$userResult = $checkUser->get_result();

if (!$userResult || $userResult->num_rows === 0) {
    echo json_encode([
        'status' => 'error',
        'error' => 'Receiver not found.'
    ]);
    exit();
}

// Insert message into database
$stmt = $conn->prepare("
    INSERT INTO messages (
        sender_user_id,
        receiver_user_id,
        order_id,
        message_text,
        is_read,
        created_at
    )
    VALUES (?, ?, ?, ?, 0, NOW())
");

$stmt->bind_param(
    "iiis",
    $sender_user_id,
    $receiver_user_id,
    $order_id,
    $message_text
);

// Execute and handle errors
if (!$stmt->execute()) {
    echo json_encode([
        'status' => 'error',
        'error' => $stmt->error
    ]);
    exit();
}

// Return JSON response
header('Content-Type: application/json');
echo json_encode([
    'status' => 'success',
    'message_text' => $message_text,
    'created_at' => date('M d, Y h:i A')
]);
exit();
?>