<?php

require_once __DIR__ . '/../../../config/database.php';
require_once __DIR__ . '/../../../config/helpers.php';
require_once __DIR__ . '/../../../middleware/admin.php';
require_once __DIR__ . '/MailboxRepository.php';

requireAdmin();

if (getMethod() !== 'POST') {
    jsonResponse(false, 'method.not_allowed', null, 405);
}

$route = getApiRouteSegments();
$mailboxId = isset($route[2]) && ctype_digit((string) $route[2]) ? (int) $route[2] : 0;
$messageId = isset($route[4]) && ctype_digit((string) $route[4]) ? (int) $route[4] : 0;

global $pdo;
$repo = new MailboxRepository($pdo);

$mailbox = $repo->findById($mailboxId, true);
$message = $repo->getMessageById($mailboxId, $messageId);

if (!$mailbox || !$message) {
    jsonResponse(false, 'mailboxes.message_not_found', null, 404);
}

$stmt = $pdo->prepare(
    'UPDATE mailbox_messages
     SET is_read = 1, updated_at = NOW()
     WHERE mailbox_id = :mailbox_id AND id = :id'
);

$stmt->execute([
    'mailbox_id' => $mailboxId,
    'id' => $messageId,
]);

jsonResponse(true, 'mailboxes.message_marked_unread', [
    'mailbox_id' => $mailboxId,
    'message_id' => $messageId,
    'is_read' => 1,
]);