<?php

namespace Mnv\Models;

use Mnv\Core\Collections\Collection;
use Mnv\Core\Feedback;
use Mnv\Core\Model;
use Mnv\Http\Request;

/**
 * Class Feedbacks
 * @package Mnv\Models
 */
class Feedbacks extends Model
{

    const STATE_CREATED                  = 1;
    const STATE_READ                     = 2;
    const STATE_STARRED                  = 3;
    const STATE_SENT                     = 4;
    const STATE_IMPORTANT                = 5;
    const STATE_SPAM                     = 6;
    const STATE_DELETED                  = 7;
    const STATE_SHARE                    = 8;

    /** @var string */
    protected string $table = 'feedback';
    /** @var string  */
    protected string $primaryKey = 'id';

    protected string $orderBy = 'id DESC';

    /** @var Feedback  */
    public Feedback $mail;
    /** @var array|string[]  */
    public array $colours = array( "#45b0e6", "#b8c1d9", "#006098", "#56bf68", "#8f98b3", "#9161f3", "#e673bf", "#ffcc33", "#47ccc1", "#3d88f2", "#f39718", "#e64545" );


    /** Feedbacks constructor. */
    public function __construct(Request $request)
    {
        $this->id       = $request->get('id');                 // getRequestVar('id'),
        $this->data     = $request->get('mail', '');    // getRequestVar('mail', '',  true),
        $this->status   = $request->get('status', '');  // getRequestVar('status')

        $this->mail = new Feedback();
    }


    private function sorting()
    {
        if (!empty($this->filter['query'])) {
            connect()->grouped(function($q) {
                $q->like('email', "%" . $this->filter['query'] . "%")->orLike('fullName', "%" . $this->filter['query'] . "%")->orLike('phone',"%" . $this->filter['query'] . "%");
            });
        }
        if (!empty($this->filter['status'])) connect()->where('status', $this->filter['status']);

        if (!empty($this->filter['dateStart']) && !empty($this->filter['dateEnd'])) {
           connect()->between('created', $this->filter['dateStart'], $this->filter['dateEnd']);
        }

    }
    /**
     * Получение всех писем
     */
    public function all($limit, $page)
    {
        $this->sorting();
        return parent::all($limit, $page);

    }

    /** получение кол-во */
    public function total() : void
    {
        $this->sorting();

        parent::total();
    }

    public function prepare(array $data, int $managerId): bool
    {
        return $this->update($data);

    }


    public function status(): bool
    {
        if (!empty($this->id) && connect()->table($this->table)->where($this->primaryKey, $this->id)->update(['status' => $this->status])) {
            return true;
        }

        return false;

    }



    /**
     * @return array|null
     */
    public function read_feedback()
    {
        if ($feedback = connect()->table($this->table)->where($this->primaryKey, $this->id)->get('array')) {
            $feedback['created'] = langDate(adjustTime($feedback['created'], false, 'F j, Y H:i'));
            $feedback['user_lt'] = mb_strtoupper(mb_substr(preg_replace('![^\w\d\s]*!u','',$feedback['user_name']), 0, 2));
            $feedback['bgcolor'] = $this->colours[array_rand($this->colours)];

            if ($feedback['state'] !== self::STATE_SENT) $this->update_feedback_state($this->id, self::STATE_READ);

            return $feedback;
        }

        return null;
    }

    /**
     * @param $id
     * @param $reply
     */
    public function reply_to_feedback($id, $reply)
    {

        if ($feedback = connect()->table($this->table)->where($this->primaryKey,  $id)->get()) {
            if (!empty($feedback->email)) {
                connect()->table($this->table)->where('id',  $feedback->id)->update(['reply' => $reply, 'state' => 3]);
                //$recipient, $companyName, ?string  $user_email, ?string $user_name, $subject, $htmlBody, $attachment = null
                $this->mail->send($feedback->email, "", $feedback->subject, "", "");
            }
        }
    }

    /**
     * @param $feedback
     * @param $file
     * @return bool
     */
    public function compose_feedback($feedback, $file = null)
    {
        $feedback->state   = self::STATE_SENT;
        $feedback->created = gmdate('Y-m-d H:i:s');
        $this->mail->send($feedback->to, "", $feedback->subject, "", "");
        $feedback = (array) $feedback;

        unset($feedback['to']);

        if ($this->id = connect()->table($this->table)->insert($feedback)) return true;

        return false;
    }

    /**
     * @param $id
     * @param $state
     */
    public function update_feedback_state($id, $state)
    {
        if (is_array($id)) {
            connect()->where($this->primaryKey, $id, 'IN');
        } else {
            connect()->where($this->primaryKey, $id);
        }
        connect()->table($this->table)->update($state);

    }


//    public function share_feedback($id)
//    {
//        if ($feedback = connect()->where('id', $id)->objectBuilder()->DB_ARRAY('feedback')) {
//            if (!empty($feedback->email)) {
//                $this->send_message($feedback->email, $feedback->subject, $feedback->message);
//            }
//        }
//    }

//    public function delete_feedback($Ids)
//    {
//        if (is_array($Ids)) {
//            connect()->in('id', $Ids);
//        } else {
//            connect()->where('id', $Ids);
//        }
//        connect()->table('feedback')->delete();
//
//    }


    /**
     * Получить кол-во новых
     * @return int|mixed
     */
    public function get_new_feedback()
    {

        if ($feedbackCount = connect()->table($this->table)->where('state', self::STATE_CREATED)->count('*')->getValue()) {
            return $feedbackCount;
        }

        return 0;
    }

    /**
     * Получить кол-во помеченных
     * @return int|mixed
     */
    public function get_starred_feedback()
    {
        if ($feedbackCount = connect()->table($this->table)->where('state',  self::STATE_STARRED)->count('*')->getValue()) {
            return $feedbackCount;
        }

        return 0;
    }


    /**
     * Получить кол-во в spam
     * @return int|mixed
     */
    public function get_spam_feedback()
    {

        if ($feedbackCount = connect()->table($this->table)->where('state',  self::STATE_SPAM)->count('*')->getValue()) {
            return $feedbackCount;
        }

        return 0;
    }

    /**
     * Получить кол-во удаленных
     * @return int|mixed
     */
    public function get_deleted_feedback()
    {

        if ($feedbackCount = connect()->table($this->table)->where('state', self::STATE_DELETED)->count('*')->getValue()) {
            return $feedbackCount;
        }

        return 0;
    }


    public function checkFileName(?string $fileName)
    {
        // TODO: Implement checkFileName() method.
    }

}