<?php
require "../config/database.php";
require "../includes/auth.php";
require "../includes/csrf.php";

error_reporting(0);

header("Content-Type: application/json; charset=utf-8");
requireApiAuth();

$data = json_decode(file_get_contents("php://input"), true);
if (!is_array($data)) {
    http_response_code(400);
    echo json_encode(["success" => false, "error" => "invalid_payload"]);
    exit;
}

if (!requireCsrfFromPayload($data, "csrf")) {
    http_response_code(403);
    echo json_encode(["success" => false, "error" => "invalid_csrf"]);
    exit;
}

$senderId = (int)$_SESSION["user"]["id"];
$receiverId = (int)($data["receiver_id"] ?? 0);
$text = trim((string)($data["text"] ?? ""));

if ($receiverId <= 0 || $text === "") {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "receiver_and_text_required"]);
    exit;
}

if ($receiverId === $senderId) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "cannot_message_self"]);
    exit;
}

if (mb_strlen($text) > 2000) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "message_too_long"]);
    exit;
}

$senderRoleStmt = $pdo->prepare("SELECT role_id FROM users WHERE id = ? LIMIT 1");
$senderRoleStmt->execute([$senderId]);
$senderRoleId = (int)$senderRoleStmt->fetchColumn();

$receiverStmt = $pdo->prepare("SELECT id, role_id FROM users WHERE id = ? LIMIT 1");
$receiverStmt->execute([$receiverId]);
$receiverRow = $receiverStmt->fetch(PDO::FETCH_ASSOC);
if (!$receiverRow) {
    http_response_code(404);
    echo json_encode(["success" => false, "error" => "receiver_not_found"]);
    exit;
}

$receiverRoleId = (int)($receiverRow["role_id"] ?? 0);

// Admin(1) and Moderator(5) can message everyone.
// Workers(2), Agencies(3), Companies(4) can message only admin/moderator.
if ($senderRoleId !== 1 && $senderRoleId !== 5) {
    if (!in_array($receiverRoleId, [1, 5], true)) {
        http_response_code(403);
        echo json_encode(["success" => false, "error" => "support_only_admin_moderator"]);
        exit;
    }
}

if ($senderRoleId === 1 || $senderRoleId === 5) {
    $stmt = $pdo->prepare("
        INSERT INTO messages (sender_id, receiver_id, text, status, created_at)
        VALUES (?, ?, ?, 'unread', NOW())
    ");
    $stmt->execute([$senderId, $receiverId, $text]);

    $notificationText = "New message from user #" . $senderId;
    $notifStmt = $pdo->prepare("
        INSERT INTO notifications (sender_id, receiver_id, type, message, is_read, created_at)
        VALUES (?, ?, 'message', ?, 0, NOW())
    ");
    $notifStmt->execute([$senderId, $receiverId, $notificationText]);

    echo json_encode(["success" => true, "message_id" => (int)$pdo->lastInsertId()]);
    exit;
}

// Non-admin accounts: broadcast support message to all admins and moderators
$targetsStmt = $pdo->prepare("
    SELECT id
    FROM users
    WHERE role_id IN (1, 5) AND id <> ?
    ORDER BY id ASC
");
$targetsStmt->execute([$senderId]);
$targets = $targetsStmt->fetchAll(PDO::FETCH_COLUMN);

if (!$targets || count($targets) === 0) {
    http_response_code(422);
    echo json_encode(["success" => false, "error" => "no_admin_or_moderator_targets"]);
    exit;
}

$insMsg = $pdo->prepare("
    INSERT INTO messages (sender_id, receiver_id, text, status, created_at)
    VALUES (?, ?, ?, 'unread', NOW())
");
$insNotif = $pdo->prepare("
    INSERT INTO notifications (sender_id, receiver_id, type, message, is_read, created_at)
    VALUES (?, ?, 'message', ?, 0, NOW())
");

$lastMessageId = 0;
foreach ($targets as $targetId) {
    $targetId = (int)$targetId;
    if ($targetId <= 0) {
        continue;
    }
    $insMsg->execute([$senderId, $targetId, $text]);
    $lastMessageId = (int)$pdo->lastInsertId();

    $notificationText = "New support message from user #" . $senderId;
    $insNotif->execute([$senderId, $targetId, $notificationText]);
}

echo json_encode(["success" => true, "message_id" => $lastMessageId]);
?>
