<?php

namespace App;

use Mtc\Modules\Members\Models\Member;
use Mtc\Plugins\MembersMessaging\Classes\Message;
use Mtc\Plugins\MembersMessaging\Classes\Thread;
use Mtc\Plugins\SMS\Classes\SMS;
use Mtc\Shop\Order;

class DoctorApprovalNotifications
{
    /**
     * @var $admin
     */
    private $admin;

    /**
     * @var Order
     */
    protected $order;

    /**
     * @var Order\Item
     */
    protected $order_item;

    /**
     * @param $order_item_id
     * @return $this
     */
    public function setOrderItem($order_item_id)
    {
        $this->order_item = Order\Item::query()->find($order_item_id);
        $this->order = $this->order_item->order;

        return $this;
    }

    /**
     * Set admin user
     *
     * @param $admin
     * @return $this
     */
    public function setAdmin($admin)
    {
        $this->admin = $admin;

        return $this;
    }

    /**
     * Send message to customer in messaging centre
     *
     * @param $message
     * @return $this
     * @throws \Exception
     */
    public function sendMessage($message)
    {
        $thread = Thread::query()
            ->create([
                'url' => str_replace('.', '-', uniqid('cp_', true)),
                'assigned' => 1,
                'category' => 1, // Doctor query
            ]);

        $member = Member::whereEmail($this->order->info['email'])->first();

        $message = Message::query()
            ->create([
                'thread_id' => $thread->id,
                'member_id' => $this->admin->id,
                'text' => $message,
                'private' => 0,
                'admin' => true,
            ]);
        // add participants if needed
        $thread->addParticipant($member);
        $thread->addParticipant($this->admin, 1);

        $member = $thread->participants()->where('admin', 0)->first();
        $email_body = template('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,
        ]);

        return $this;
    }

    /**
     * Send SMS to customer about approved item
     *
     * @param $message
     * @return $this
     */
    public function sendSMS($message)
    {
        SMS::sendMessage($this->order->info['contact_no'], $message);

        return $this;
    }
}
