<?php

use Carbon\Carbon;
use Mtc\Modules\Members\Classes\Auth;
use Mtc\Plugins\MembersMessaging\Classes\Message;
use Mtc\Plugins\MembersMessaging\Classes\Thread;

$path = '../../../';
require_once $path . 'core/includes/header.inc.php';

$url = filter_var($_REQUEST['thread'], FILTER_SANITIZE_STRING);

if (!Auth::isLoggedIn()) {
    $redirect = route('members-login', [
        'redirect' => urlencode($_SERVER['REQUEST_URI']),
    ]);
    header('Location:' . $redirect);
    exit();
}

/** @var Thread $thread */
$thread = Thread::whereUrl($url)->withTrashed()->first();
if ($thread === null) {
    //exit;
}

$thread->messages()
    ->whereNull('read_at')
    ->where('admin', 1)
    ->update([
        'read_at' => Carbon::now()
    ]);

if (filter_input(INPUT_POST, 'action') === 'satisfactory') {
    $message = (new Message())->find($_POST['message_id']);
    $message->satisfactory = $_POST['satisfactory'];
    $message->comment = $_POST['satisfactory'] === '3' ? $_POST['comment'] : '';
    $message->save();
    echo json_encode([
        'success' => 'Thank you for your feedback!',
        'message_id' => (int)$_POST['message_id'],
    ]);
    exit;
}


echo $twig->render('members/view_thread.twig', [
    'page_meta' => $page_meta,
    'messages' => $thread->public_messages(),
    'thread' => $thread,
    'url' => $thread->url,
    'satisfactory_options' => Message::$satisfactory_options,
]);

