<?php

namespace Mtc\Modules\MembersMessaging\Classes;

use Mtc\Core\Admin\User;
use Mtc\Plugins\MembersMessaging\Classes\Thread;
use Mtc\Plugins\MembersMessaging\Classes\ViewFixer;

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

init_request_values([
    'thread_url',
    'act',
    'page',
    'startnumber',
    'assigned',
]);

$page_meta['title'] = 'All messages';

$thread_url = strip_tags((string) $_REQUEST['thread_url']);
$action = strip_tags((string) $_REQUEST['act']);

$rowsPerPage = 25;
$pageNum = $_REQUEST['page'] ?: 1;
$append = '';

if (request()->has('assign_user')) {
    $thread = Thread::query()->where('url', $thread_url)->first();
    $thread_user = User::query()->find(request()->input('user_id'));
    $thread->assignAdmin($thread_user);

    header('Refresh: 0');
    exit;
}

if (is_numeric($_REQUEST['startnumber'])) {
    $startnumber = $_REQUEST['startnumber'];
} else {
    $startnumber = 0;
}

$threads = Thread::query()
    ->with(['participants.adminUser'])
    ->whereHas('messages', function ($query) {
        $query->where('admin', '=', '0')->orWhere('private', 1);
    })
    ->orderBy('updated_at', 'desc');

if (isset($_REQUEST['assigned'])) {
    if ($_REQUEST['assigned'] !== '') {
        $threads = $threads->where('assigned', '=', $_REQUEST['assigned']);
    }
} else {
    $threads = $threads->where('assigned', '=', '0');
}
$append .= '&assigned=' . $_REQUEST['assigned'];

$totalnumrows = $threads->count();

$threads = $threads->offset($rowsPerPage * ($pageNum - 1))->take($rowsPerPage)->get();

require_once $path . 'core/admin/templates/adminheader.html.php';
?>
    <ul class="breadcrumbs el">
        <li><a href="/admin/">Home</a> /</li>
        <li class="end">Member messages</li>
    </ul>

    <h1>Member messages</h1>

    <?php
require __DIR__ . '/tabnav.php';
?>
    <form action="" method="GET" class="style">
        <fieldset class="show">
            <h1><a class="show el">Assigned <i class="fa fa-caret-right"></i></a></h1>
            <div class="row">
                <label for="assigned">Status</label>
                <select name="assigned" id="assigned">
                    <option value="">All</option>
                    <option value="1" <?= $_REQUEST['assigned'] === '1' ? 'selected' : ''; ?>>Assigned</option>
                    <option value="0" <?= $_REQUEST['assigned'] === '0' || !isset($_REQUEST['assigned']) ? 'selected' : ''; ?>>
                        Unassigned
                    </option>
                </select>
            </div>

            <div class="search-button">
                <input type="hidden" name="action" value="search"/>
                <input type="submit" value="Search" class="BUTTON"/>
            </div>
        </fieldset>
    </form>


    <?php
if ($totalnumrows > 0) {
    ?>
    <table class="manage-items">
        <tr>
            <th class="center">ID</th>
            <th>Last response</th>
            <th>Member</th>
            <th>Assigned to</th>
            <th>Category</th>
            <th>Message</th>
            <th>Date sent</th>
            <th>Assignee</th>
            <th></th>
        </tr>
        <tbody class="tabular">
        <?php
        foreach ($threads as $thread) {
            $first_message = $thread->messages()->where('admin', '0')->orderBy('created_at', 'desc')->first();
            $admin_participants = $thread->participants->where('admin', '1');
            ?>
            <tr id="rorder-<?= $thread->id ?>" <?= ($thread->hasUnreadMessagesFromCustomer()) ? 'class="hasUnreadAdmin"' : ''; ?>>
                <td>
                    <?= clean_page($thread->id) ?>
                </td>
                <td>
                    <?= clean_page($thread->lastMessageFrom()) ?>
                </td>
                <td>
                    <?= clean_page(!empty($first_message->user) ? $first_message->user->getFullnameAttribute() : '- internal message -'); ?>
                </td>
                <td>
                    <?= $thread->assigned_participant ? clean_page($thread->assigned_participant->adminUser->name) : '-' ?>
                </td>
                <td>
                    <?= Thread::MESSAGE_CATEGORIES[$thread->category]; ?>
                </td>
                <td>
                    <?= $first_message ? clean_page(strip_tags($first_message->text)) : ''; ?>
                </td>
                <td>
                    <?= $first_message ? clean_page($first_message->created_at) : ''; ?>
                </td>
                <td>
                    <?php
                    if ($action !== 'my_messages') {
                        $thread_url = $thread->url;
                        $thread_assigned_user_id = $thread->getAssignedUserId();
                        include 'widgets/assign_thread.php';
                    }
                    ?>
                </td>
                <td>
                    <a class="view-message" href="view_member_thread.php?url=<?= $thread->url; ?>">
                        <i class="fa fa-eye"></i> View thread
                    </a>
                    <a class="delete-message alert"
                       title="Are you sure you want to remove this thread?"
                       href="my_messages.php?act=delete&id=<?= $thread->id; ?>&return=<?= $_SERVER['SCRIPT_NAME']; ?>">
                        <i class="fa fa-remove"></i> Delete thread
                    </a>

                </td>
            </tr>
            <?php
        }
        ?>
        </tbody>
    </table>
    <?php
} else {
    ?>
    <p>There are no messages</p>
    <?php
}

require $path . 'core/admin/templates/pagination.php';

require_once $path . 'core/admin/templates/adminfooter.html.php';
