<?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([
    'act',
    'return',
    'startnumber',
    'id',
]);

if (isset($page_title)) {
    $page_meta['title'] = $page_title;
} else {
    $page_meta['title'] = 'My messages';
}

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

if($action === 'delete' && !empty($id)) {
    Thread::find($id)->delete();
    if(!empty($return)) {
        header('Location: ' . $return);
        exit;
    }
}

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

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

if (!empty($_POST['main_submit'])) {
    $bulk_threads = $_REQUEST['bulk_threads'];
    if (!empty($bulk_threads)) {

        foreach ($bulk_threads as $thread_id => $thread_value) {
            if ($action == 'delete') {
                Thread::find($thread_id)->delete();
            }
        }
        header('Refresh: 0');
        exit;
    }
}

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

// load admin eloquent user and its allowed categories
$admin = \Mtc\Core\Admin\User::query()
    ->find($adminuser->user['id']);

if (! isset($user_id)) $user_id = $admin->id;
if (! isset($is_admin_user)) $is_admin_user = true;


$query = Thread::query()
    ->decorated()
    ->where('p.member_id', $user_id)
    ->where('p.admin', (int)$is_admin_user)
    ->orderBy('unread_flag', 'desc')
;

(new ViewFixer())->resolvePaginationDependencies($twig);

$threads = $query->paginate(25);

$threads->appends($_GET);

$totalnumrows = $threads->total();

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

    <h1><?= $page_meta['title'] ?></h1>
    <?php if (! $is_admin_user) { ?>
        <h5>Member ID: <a href="/modules/Members/admin/manage_member.php?id=<?= $user_id ?>"><?= $user_id ?></a></h5>
    <?php } ?>

    <?php
require __DIR__ . '/tabnav.php';
if ($totalnumrows > 0) {
    ?>
    <form action="" method="post">
        <table class="manage-items">
            <tr>
                <th>Thread ID</th>
                <th>Member</th>
                <th>Category</th>
                <th>Message</th>
                <th>Assigned to</th>
                <th>Date sent</th>
                <th></th>
                <th></th>
            </tr>
            <tbody class="tabular">
            <?php
            foreach ($threads as $thread) {
                ?>
                <tr id="rorder-<?= $thread->id ?>" <?= ($thread->getAssignedUserId() == $admin->id) && $thread->hasUnreadMessagesFromCustomer() ? 'class="hasUnreadAdmin"' : ''; ?>>
                    <td>
                        <?= clean_page($thread->id) ?>
                    </td>
                    <td>
                        <?php

                        if (!empty($thread->latestMessage)) {

                            if ($thread->latestMessage->admin) {
                                echo clean_page($thread->latestMessage->admin_user->name);
                            } else {
                                echo clean_page($thread->latestMessage->user->getFullnameAttribute());
                            }
                        } else {
                            echo '-';
                        }
                        ?>
                    </td>
                    <td>
                        <?= Thread::MESSAGE_CATEGORIES[$thread->category]; ?>
                    </td>
                    <td>
                        <?= clean_page(strip_tags($thread->latestMessage->text)); ?>
                    </td>
                    <td>
                        <?php
                            $thread_url = $thread->url;
                            $thread_assigned_user_id = $thread->getAssignedUserId();
                            include 'widgets/assign_thread.php';
                        ?>
                    </td>
                    <td>
                        <?= clean_page($thread->latestMessage->created_at); ?>
                    </td>
                    <td>
                        <a class="view-message" href="view_member_thread.php?url=<?= $thread->url; ?>">
                            <i class="fa fa-eye"></i> View thread
                        </a>
                    </td>
                    <td>
                        <input type="checkbox" name="bulk_threads[<?= $thread->id; ?>]" value="1">
                    </td>
                </tr>
                <?php
            }
            ?>
            </tbody>
        </table>

        <hr />

        <div class="row">
            <select name="act" id="actions">
                <option value="">Choose Action</option>
                <option value="delete">Delete threads</option>
            </select>
        </div>

        <input type="submit" name="main_submit" class="btn" value="Submit"/>
    </form>

    <?php
} else {
    ?>
    <p>There are no messages</p>
    <?php
}

echo $threads->render();

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