<?php

namespace App\Models\Messages;

use Cmgmyr\Messenger\Models\Message;
use Cmgmyr\Messenger\Models\Models;
use Cmgmyr\Messenger\Models\Participant;
use Cmgmyr\Messenger\Models\Thread;
use Illuminate\Database\Eloquent\Model;
use App\Models\Messages\ExtendedMessage;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Illuminate\Support\Carbon;
use App\Models\Auth\User;

class ExtendedThread extends Thread
{
    protected $fillable = ['subject', 'uuid', 'notification', 'invite_id'];

    protected $attributes = [
        'subject' => '',
    ];

    /**
     * Messages relationship.
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     *
     * @codeCoverageIgnore
     */
    public function extendedmessages()
    {
        return $this->hasMany('App\Models\Messages\ExtendedMessage', 'thread_id', 'id');
    }

    public function scopeNotifications($query)
    {
        // dd($query);
        return $query->whereNotNull('notification');
    }

//    public static function scopePersonalMessages($query)
//    {
//        return static::whereIsNull('notification')->get();
//    }

    public function GetCreatorNameAttribute()
    {
        $firstMessage = $this->extendedmessages()->withTrashed()->oldest()->first();
        if (isset($firstMessage->from_name)) {
            return ($firstMessage->from_name);
        } else {
            try{
//                dd($firstMessage->user);
                return $firstMessage->user->name;
            }catch (\Exception $e){
                return 'Unknown user';
            }

        }

    }

    public function hascreator()
    {
      return (!$firstMessage = $this->messages()->withTrashed()->oldest()->first()->from_name);
    }

    protected $creatorCache;

    public function creator()
    {
        if ($this->creatorCache === null) {
            $firstMessage = $this->extendedmessages()->withTrashed()->oldest()->first();
            $this->creatorCache = $firstMessage ? $firstMessage->user : Models::user();
        }

        return $this->creatorCache;
    }

    /**
     * @param $subject
     * @param $message
     * @param array $actions
     * @param array $to_ids
     * @param $from_id
     * @param $from_name
     * @throws \Exception
     */
    public function makeNotification($subject, $message, $actions, $to_ids, $from_id, $from_name = null)
    {

        $this->subject = $subject;
        $this->notification = '1';
        $this->save();
        // build the message body
        $messageBody = $message . '<br/>';
        // build actions
        //dd($actions);
        foreach ($actions as $action) {

            $messageBody .= "<a href='{$action['route']}' class='btn {$action['buttonclass']}'>{$action['text']}</a>";
        }

        // Message
        ExtendedMessage::create([
            'thread_id' => $this->id,
            'user_id' => $from_id,
            'from_name' => (isset($from_name)?$from_name: null),
            'body' => $messageBody,
        ]);

        // Sender
        Participant::create([
            'thread_id' => $this->id,
            'user_id' => $from_id,
            'last_read' => new \Carbon\Carbon,
        ]);

        // Recipients

        foreach ($to_ids as $to_id) {
            $this->addParticipant($to_id);
        }


//        try {
//            $participant = $this->getParticipantFromUser($userId);
//            $participant->last_read = new Carbon();
//            $participant->save();
//        } catch (ModelNotFoundException $e) { // @codeCoverageIgnore
//            // do nothing
//        }
    }
}
