<?php

namespace App\Models\Panel\User;

use App\Models\Panel\UserModel;

class AdministratorModel extends UserModel
{
    protected $DBGroup              = 'default';
    protected $table                = 'users';
    protected $primaryKey           = 'id';
    protected $useAutoIncrement     = true;
    protected $insertID             = 0;
    protected $returnType           = 'array';
    protected $useSoftDeletes       = false;
    protected $protectFields        = true;
    protected $allowedFields        = ['username', 'fullname', 'phone', 'password_hash', 'status'];

    // Dates
    protected $useTimestamps        = true;
    protected $dateFormat           = 'datetime';
    protected $createdField         = 'created_at';
    protected $updatedField         = 'updated_at';
    protected $deletedField         = 'deleted_at';

    // Validation
    protected $validationRules      = [];
    protected $validationMessages   = [];
    protected $skipValidation       = false;
    protected $cleanValidationRules = true;

    // Callbacks
    protected $allowCallbacks       = true;
    protected $beforeInsert         = [];
    protected $afterInsert          = [];
    protected $beforeUpdate         = [];
    protected $afterUpdate          = [];
    protected $beforeFind           = [];
    protected $afterFind            = [];
    protected $beforeDelete         = [];
    protected $afterDelete          = [];

    public function findId($id)
    {
        $builder = $this->db->table($this->table);
        $builder->select('users.*,roles.name role');
        $builder->join('users_roles ur', 'ur.user_id=users.id', 'left');
        $builder->join('roles', 'roles.id=ur.role_id', 'left');
        $builder->where(['users.id' => $id, 'roles.name' => 'admin']);
        $result = $builder->get()->getRowArray();
        if (!$result) return null;
        $user = new \App\Entities\Panel\User();
        $result['role'] = explode(',', $result['role'] ?? '');
        $user->fill($result);
        if (!$user->hasRole('admin')) return null;
        return  $user;
    }

    public function countAdmin()
    {
        $builder = $this->db->table($this->table);
        $builder->select('users.*');
        $builder->join('users_roles ur', 'ur.user_id=users.id', 'left');
        $builder->join('roles', 'roles.id=ur.role_id', 'left');
        $builder->where('roles.id', 1);
        $builder->groupBy('ur.user_id');
        return $builder->countAllResults();
    }
    public function deleteId($id)
    {
        $this->db->query("DELETE users FROM users LEFT JOIN users_roles ur ON ur.user_id=users.id LEFT JOIN roles ON roles.id=ur.role_id WHERE roles.name='admin' AND users.id=?", [$id]);
        return $this->db->affectedRows() > 0;
    }

    public function getAll()
    {
        $bu = base_url(config('app')->imgPath . "/users");
        $builder = $this->db->table($this->table);
        $builder->select("users.id,CONCAT('$bu/',users.cover) cover,CONCAT('$bu/',users.photo) photo,users.username,users.fullname,users.status,roles.name role");
        $builder->join('users_roles ur', 'ur.user_id=users.id', 'left');
        $builder->join('roles', 'roles.id=ur.role_id', 'left');
        $builder->where('users.deleted_at', null);
        $users = [];
        foreach ($builder->get()->getResultArray() as $user) {
            $u = new \App\Entities\Panel\User();
            $user['role'] = explode(',', $user['role'] ?? '');
            $u->fill($user);
            if (!$u->hasRole('admin')) continue;
            $users[] = $u;
        }
        return $users;
    }
}
