<?php

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

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

if (!Auth::isLoggedIn()) {
    header("Location: " . route('members-login'));
    exit();
}

$action = filter_var($_REQUEST['act'], FILTER_SANITIZE_STRING);

if ($action === 'create') {
    if (!empty($member->id)) {
        $category = filter_var($_REQUEST['category'], FILTER_SANITIZE_NUMBER_INT);
        $thread = Thread::query()
            ->create([
                'url' => str_replace('.', '-', uniqid('cp_', true)),
                'category' => $category,
            ]);

        $text = filter_var($_REQUEST['text'], FILTER_SANITIZE_STRING);
        $message = Message::query()
            ->create([
                'thread_id' => $thread->id,
                'member_id' => $member->id,
                'text' => nl2br($text),
            ]);

        // add participants if needed
        $thread->addParticipant($member);

        // update updated_at
        $thread->touch();
    }
    header('Location: /members/messages/');
}

if ($action === 'send') {
    $errors = [];

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

    $thread = Thread::whereUrl($url)->withTrashed()->first();

    $is_participant = $thread->hasParticipant($member->id);
    if ($is_participant === false) {
        $errors["user"] = "Not a participant of the thread";
    }

    if (empty($text)) {
        $errors["text"] = "Text field cannot be left empty";
    }

    if ($is_participant && empty($errors)) {
        $message = new Message();
        $message->fill([
            'member_id' => $member->id,
            'text' => nl2br($text),
        ]);

        $thread->messages()->save($message);
        $thread->touch();

        $thread_manager = $thread->participants()->where('admin', '=', 1)->first();
        if ($thread_manager) {
            $email_body = template('emails/new_message.twig', [
                'member' => $thread_manager->adminUser,
                'message_text' => $message->text,
                'thread_url' => SITE_URL . '/plugins/MembersMessaging/admin/view_member_thread.php?url=' . $thread->url,
            ]);
            email($thread_manager->adminUser->email, "You've received a new message on " . config('app.name'), $email_body, ['dev_copy' => DEV_MODE]);
        }
    }

    header('Location: /members/messages/view_thread.php?thread=' . $url);
}

if ($action === 'threads') {
    echo Thread::scopeForUser($member->id)->toJson();
}

if ($action === 'messages') {
    $url = filter_var($_REQUEST['url'], FILTER_SANITIZE_STRING);
    $last_id = filter_var($_REQUEST['last'], FILTER_SANITIZE_NUMBER_INT);

    $thread = Thread::where('url', $url)->first();

    if (!empty($url) && $thread->hasParticipant($member->id) === true) {
        echo $thread->getMessages($last_id);
    }
}

