<?php

namespace Mnv\Models\Users;

use Mnv\Core\Collections\Collection;

/**
 * Class ClientsUser
 * @package Mnv\Models\Users
 */
class ClientsUser extends AbstractUser
{
    /**
     * Таблица, связанная с моделью.
     *
     * @var string
     */
    protected string $table = 'project_clients';


    protected function clientSorting()
    {
        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']);
    }

    /**
     * Получение всех пользователей
     *
     * @param string|null $orderBy
     * @param int $limit
     * @param int $page
     * @return Collection
     */
    public function all(?string $orderBy, int $limit, int $page)
    {
        /** Фильтровать пользователей */
        $this->clientSorting();

        return connect()->table($this->table)->select('*')->pagination($limit, $page)->orderBy($orderBy)->getAll('array');
    }

    /**
     * получение кол-во пользователей
     */
    public function total() : void
    {
        /** Фильтровать пользователей */
        $this->clientSorting();
        $this->total = (int)connect()->table($this->table)->count('*', 'count')->getValue();
    }


    /**
     * Получить пользователя
     */
    public function get(?string $userType = null): void
    {
        $this->user = connect()->table($this->table)->where($this->primaryKey, $this->userId)->get('array');
    }

    public function edit(?string $userType = null)
    {
        !empty($this->userId) && $this->get($userType);
    }

    /**
     * Проверить на существование
     * @param string $field по какому полю проверять (`email` или `phone`)
     * @param string $param приходящий параметр для сравнения
     * @return bool
     */
    public function existSubscribe(string $field, string $param): bool
    {
        if (connect()->table($this->table)->count('*')->where($field, $param)->getValue()) return true;

        return false;
    }

    /**
     * Проверка на совпадение email
     * @param string $email
     * @return string|null
     */
    public function checkEmailUser(string $email): ?string
    {
        if (!empty($this->userId)) connect()->where('userId','<>', $this->userId);
        if ($email = connect()->table($this->table)->select('email')->where('email', $email)->getValue()) {
            return $email;
        }

        return null;
    }

    public function prepare(array $data, int $managerId): bool
    {
        $projectId = 0;

        $data['modifiedBy']   = $managerId;
        $data['modifiedOn']   = gmdate('Y-m-d H:i:s');

        if (isset($data['projectId'])) {
            $projectId = $data['projectId'];
            unset($data['projectId']);
        }

        if (empty($this->userId)) {
            $data['addedBy'] = $managerId;
            $data['addedOn'] = gmdate('Y-m-d H:i:s');

            if ($this->insert($data)) {
                if (connect('project_client_tracking')->insert(['userId' => $this->userId, 'projectId' => $projectId])) return true;

                $this->get();
                return true;
            }

        } else {
            return $this->update($data);
        }
    }


    public function tracking($projectId): bool
    {
        if (connect('project_client_tracking')->where('userId', $this->userId)->where('projectId', $projectId)->get()){
            return false;
        }
        $data = [
            'userId' => $this->userId,
            'projectId' => $projectId
        ];

        connect('project_client_tracking')->replace($data);

        $this->get();

        return true;

    }

    public function removeTracking($projectId): bool
    {
        if (connect('project_client_tracking')->where('userId', $this->userId)->where('projectId', $projectId)->delete()){
            return true;
        }

        return false;
    }


    /**
     * Удаление пользователя
     */
    public function remove(?string $userType = null): bool
    {
        if ( !empty($this->userId) ) {
            $this->get($userType);
            if (!empty($this->user)) {
                connect()->table($this->table)->where($this->primaryKey,  $this->userId)->delete();
                return true;
            }
        }
        return false;
    }

    /**
     * Обновление статуса
     */
    public function approve() { }


    public static function getClients($projectId, $fields = null): ?array
    {
        if (!empty($fields)) connect()->select($fields);
        return connect('project_client_tracking')->usingJoin('project_clients', 'userId')->where('projectId', $projectId)->getAll('array');
    }

}