<?php

use Illuminate\Database\Eloquent\Collection;
use Mtc\Core\Admin\User;
use Mtc\Core\Permissions;
use Mtc\Modules\Members\Models\Member;
use Mtc\Plugins\MembersMessaging\Classes\Message;
use Mtc\Plugins\MembersMessaging\Classes\Thread;

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

init_request_values([
    'act',
    'url',
    'order_id',
    'private',
]);

$url = strip_tags((string) $_REQUEST['url']);
$action = strip_tags((string) $_REQUEST['act']);
$order_id = filter_var($_REQUEST['order_id'], FILTER_SANITIZE_NUMBER_INT);
$member_id = request()->input('member_id');

$admin = User::find($adminuser->user['id']);

$redirect_back_to_main = false;

$thread = null;

if (request()->has('assign_user')) {
    $thread_url = strip_tags((string) $_REQUEST['thread_url']);
    $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 ($action === 'create') {

    if (!empty($member_id)) {
        $member = Member::query()
            ->find($member_id);
    } else {
        $order = new Order();
        $order = $order->getById($order_id);

        $member = Member::query()
            ->find($order->member);
    }

    $thread = Thread::query()
        ->create([
            'url' => str_replace('.', '-', uniqid('cp_', true)),
            'order_id' => $order_id ?: 0,
            'member_id' => $member->id,
        ]);

    $message = Message::query()
        ->create([
            'thread_id' => $thread->id,
            'member_id' => $admin->id,
            'text' => $_REQUEST['text'],
            'private' => (int)$_REQUEST['private'],
            'admin' => true
        ]);
    // add participants if needed
    $thread->addParticipant($member);
    $thread->assignAdmin(User::getAdminUser());

    // update updated_at
    $thread->touch();

    if (!empty($order)) {
        $order->updateMessageId($thread->id);
    }

    if (empty($_REQUEST['private'])) {
        $email_body = $twig->render('emails/new_message.twig', [
            'member' => $member,
            'message_text' => $message->text,
            'thread_url' => SITE_URL . '/members/messages/view_thread.php?thread=' . $thread->url,
        ]);
        email($member->email, "You've received a new message on " . config('app.name'), $email_body, ['dev_copy' => DEV_MODE]);
    }


    if (!empty($order)) {
        // Only update order status if it's still in processing tab.
        if (empty($_REQUEST['private']) && in_array($order->status, \Mtc\Shop\Order::$order_types['processing'])) {
            $order->updateStatus(\Mtc\Shop\Order::STATUS_WAITING_FOR_RESPONSE);
        }
    }

    header('Location: view_member_thread.php?url=' . $thread->url);
    exit();
}

if ($action !== 'request_info') {
    if ($thread = Thread::whereUrl($url)->withTrashed()->first()) {
        $thread->markRead();
        $adminId = $thread->participants->where('admin', '=', 1)->first();
        $member_id = $thread->participants->where('admin', '0')->first()->member_id;
    }
} elseif (!empty(request()->input('member_id'))) {
    $member_id = request()->input('member_id');
} elseif (!empty($order_id)) {
    $member_id = \Mtc\Shop\Order::query()->find($order_id)->member;
}

$member_orders = [];
if (!empty($member_id)) {
    $member_orders = \Mtc\Shop\Order::query()
        ->where('member', $member_id)
        ->where('paid', '1')
        ->orderBy('date', 'desc')
        ->get();
}

if (!empty($_POST['main_submit'])) {
    if (!empty($_REQUEST['text']) && !empty($adminId)) {
        $message = new Message();
        $message->fill([
            'member_id' => $admin->id,
            'text' => $_REQUEST['text'],
            'admin' => true,
            'private' => (int)$_REQUEST['private'],
        ]);

        if (empty($_REQUEST['private'])) {
            $member = $thread->participants()->where('admin', 0)->first();
            $email_body = $twig->render('emails/new_message.twig', [
                'member' => $member->user,
                'message_text' => $message->text,
                'thread_url' => SITE_URL . '/members/messages/view_thread.php?thread=' . $thread->url,
            ]);
            email($member->user->email, "You've received a new message on " . config('app.name'), $email_body, ['dev_copy' => DEV_MODE]);
        }

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

if ($action === 'close') {
    Thread::whereUrl($url)->delete();
    $redirect_back_to_main = true;
}

if (!empty($redirect_back_to_main)) {
    header('Location: my_messages.php');
    exit;
}

$messageBubbleHtml = function (Message $message) {
    $class = ($message->admin) ? 'right' : 'left';
    $class .= $message->private ? ' private' : '';
    if ($message->admin) {
        $author = $message->admin_user->name;
    } else {
        $author = $message->user->getFullnameAttribute();
    }
    $output = "<li class='bubble {$class}'>";
    $output .= '<p><strong>' . clean_page($author) . '</strong> says: </p>';
    $output .= '<div class="messageText">' . $message->text . '</div>';
    $output .= '<p><em>' . date_convert_db_to_dmy($message->created_at, true) . '</em></p>';
    $output .= '</li>';

    return $output;
};

$myName = function (Collection $participants, $owner = false) {
    $participant = $participants->reject(function ($participant) use ($owner) {
        return $owner === true;
    });
    if (!empty($participant->first()->user)) {
        return $participant->first()->user->getFullnameAttribute();
    }
};

$templates = \Mtc\Plugins\MembersMessaging\Classes\Templates::query()
    ->where('category', 'customer')
    ->where(function ($query) use ($admin) {
        $query->where('role', $admin->role)
            ->orWhere('role', 0);
    })
    ->get();
$template_texts = array_merge([""], $templates->pluck('text')->toArray());




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


?>

    <ul class="breadcrumbs el">
        <li><a href="/admin/">Admin</a> /</li>
        <li class="end">Member messages</li>
    </ul>

    <h1>Member messages</h1>
<?php
require 'tabnav.php';

if (!empty($errors)) {
    showerrors($errors);
}

$messages = [];

if ($action !== 'request_info') {
    $messages = $thread->messages;
}
?>

    <script>
        window.onload = function () {
            var objDiv = document.getElementById("admin-chat-log");
            objDiv.scrollTop = objDiv.scrollHeight;
        }
    </script>

    <div class="admin-chat-log-container">
        <?php
        $historical_threads = Thread::query()
            ->whereHas('participants', function ($query) use ($member_id) {
                $query->where('admin', '=', '0')
                    ->where('member_id', '=', $member_id);
            })
            ->orderBy('created_at')
            ->get();

        if ($historical_threads->count()) {
            ?>
            <h2>Member Messaging History (Threads)</h2>
            <ul>
                <?php
                foreach ($historical_threads as $historical_thread) {
                    $bold = $historical_thread->url === $_REQUEST['url'];
                    echo '<li>';
                    echo '<a href="/plugins/MembersMessaging/admin/view_member_thread.php?url=' . $historical_thread->url . '">' . ($bold ? '<strong>' : '') . (new \Carbon\Carbon($historical_thread->created_at))->format('d/m/Y') . ($historical_thread->order_id ? ' | Order ID:' . $historical_thread->order_id : '')  . ($bold ? '</strong>' : ''). '</a>';
                    echo '</li>';
                }
                ?>
            </ul>
            <?php
        }
        ?>

        <?php if ($thread) { ?>
            <hr />
            <h3>Thread participants</h3>
            <ul data-thread-id="<?= $thread->id ?>">
                <?php foreach ($thread->participants as $participant) { ?>
                    <?php if ($participant->admin) { ?>
                        <?php if ($participant->id == $thread->assigned_participant_id) { ?>
                            <li><strong><?= clean_page($participant->adminUser->name) ?></strong> [<?= clean_page($participant->adminUser->email) ?>]</li>
                        <?php } elseif (!empty($participant->adminUser)) { ?>
                            <li><?= clean_page($participant->adminUser->name) ?> [<?= clean_page($participant->adminUser->email) ?>]</li>
                        <?php } ?>
                    <?php } else { ?>
                        <li><?= clean_page($participant->user->getFullnameAttribute()) ?> [<?= clean_page($participant->user->email) ?>]</li>
                    <?php } ?>
                <?php } ?>
            </ul>
        <?php } ?>

        <hr />
        <h2>Thread Messages</h2>
        <ul id="admin-chat-log" class="admin-chat-log">
            <?php
            if(empty($messages)) {
                $messages = [];
            }
            foreach ($messages as $message) {
                echo $messageBubbleHtml($message);
            }
            ?>
        </ul>
        <div class="reply-bar">
            <?php
            if (empty($adminId) && $action !== 'request_info') {

                echo showmsg('Please assign message to a user', 'error', $path);

                $thread_url = $thread->url;
                $thread_assigned_user_id = null;
                include 'widgets/assign_thread.php';

                ?>

                <?php

            } else {

                ?>
                <script>
                    var templates = <?= json_encode($template_texts, JSON_UNESCAPED_SLASHES) ?>;

                    $('body').on('change', 'select[name="template"]', function () {
                        $('#message_reply').val(templates[$(this).val()]);
                    });
                </script>
                <form action="view_member_thread.php" method="post">
                    <div class="row">
                        <textarea class="tinymce" id="message_reply" name="text"></textarea>
                    </div>
                    <div class="row checkboxRow">
                        <input type="checkbox" value="1" name="private" id="private" />
                        <label for="private">A note (Private message invisible to customer)</label>
                    </div>
                    <div class="row">
                        <select name="template">
                            <option value="0">No Template</option>
                            <?php foreach ($templates as $k => $template) {
                                ?>
                                <option value="<?= $k + 1; ?>"><?= $template->name; ?></option>
                                <?php
                            }
                            ?>
                        </select>
                    </div>

                    <?php if ($action === 'request_info') { ?>
                        <input type="hidden" name="act" value="create" />
                    <?php } ?>


                    <?php if ($action === 'request_info') { ?>
                        <input type="hidden" value="<?= $order_id; ?>" name="order_id"/>
                    <?php } else { ?>
                        <input type="hidden" value="<?= $url; ?>" name="url"/>
                    <?php } ?>

                    <input type="submit" name="main_submit" class="btn" value="Submit"/>
                    <input type="hidden" name="order_id" value="<?= $_REQUEST['order_id']; ?>"/>
                    <input type="hidden" name="member_id" value="<?= request()->input('member_id'); ?>"/>
                </form>


                <?php
                if ($thread) {
                    $thread_url = $thread->url;
                    $thread_assigned_user_id = $thread->getAssignedUserId();
                    include 'widgets/assign_thread.php';
                }
                ?>

                <?php

            }
            ?>
        </div>
        <?php
        if ($action !== 'request_info') {
            ?>
            <div class="member">
                <strong><?php echo $myName($thread->participants, true); ?></strong>
            </div>
            <?php
        }
        ?>
    </div>

    <div class="messagesOrderHistory">
        <h2>Member Order History</h2>
        <table class="manage-items">
            <tr>
                <th>Order ID</th>
                <th>Date</th>
                <th>Items</th>
                <th>View</th>
            </tr>
            <tbody class="tabular">
            <?php
            if (!empty($member_orders) && $member_orders->isNotEmpty()) {
                foreach ($member_orders as $member_order) {
                    ?>
                    <tr>
                        <td><?= clean_page($member_order->id); ?></td>
                        <td><?= clean_page(date_convert_db_to_dmy($member_order->date)); ?></td>
                        <td>
                            <div class="listOfItems">
                                <table>
                                    <?php
                                    $order = new Order($member_order->id);
                                    foreach ($order->getItems() as $order_item_id => $line) {
                                        $item = new Item();
                                        $item->Get_Item($line['item_id']);
                                        ?>
                                        <tr<?= $line['PLU'] === 'private_prescription' ? ' class="privatePrescriptionItemRow"' : ''; ?>>
                                            <td>
                                                <?= $line['quantity'] ?>x
                                            </td>
                                            <td colspan="2">
                                                <a href="<?= $item->url; ?>" target="_blank">
                                                    <?= clean_page($line['item_name']); ?>
                                                    <?= $line['PLU'] === 'private_prescription' ? ' <strong>(PP)</strong>' : ''; ?>
                                                </a>

                                            </td>
                                            <td><?= strip_tags(urldecode($line['size']), '<br>'); ?></td>
                                            <td>
                                                <?php
                                                // If approved, always show green check
                                                if ((int)$line['approved'] === 1) {
                                                    ?>
                                                    <i class="fa fa-check green"></i>
                                                    <?php
                                                    // Only show the red block if the order is not in status 'Pending review'
                                                    // and the item is not approved
                                                } elseif ((int)$line['approved'] === 2) {
                                                    ?>
                                                    <i class="fa fa-ban red"></i>
                                                    <?php
                                                }
                                                ?>
                                            </td>
                                        </tr>
                                        <?php
                                    }
                                    ?>
                                </table>
                            </div>
                        </td>
                        <td>
                            <?php
                            if (Permissions::can(Permissions::DOCTOR_ORDER_VIEW)) {
                                ?>
                                <a href="/shop/admin/orders/manage.order.doctor.php?id=<?= clean_page($member_order->id); ?>"
                                   class="actionsIcon mtcOverlay">
                                    <i class="fa fa-eye"></i>
                                </a>
                                <?php
                            } else {
                                ?>
                                <a href="/shop/admin/orders/manage.order.php?id=<?= clean_page($member_order->id); ?>"
                                   target="_blank"
                                >
                                    <i class="fa fa-pencil"></i>
                                </a>
                                <?php
                            }
                            ?>
                        </td>
                    </tr>
                    <?php
                }
            } else {
                ?>
                <tr>
                    <td colspan="4">The member has no orders</td>
                </tr>
                <?php
            }
            ?>
            </tbody>
        </table>
    </div>
<?php
require $path . 'core/admin/templates/adminfooter.html.php';
