<?php

namespace App\Models\Panel;

use CodeIgniter\Model;
use Predis\Client;

class UserModel extends Model
{
    protected $DBGroup              = 'default';
    protected $table                = 'users';
    protected $primaryKey           = 'id';
    protected $useAutoIncrement     = true;
    protected $insertID             = 0;
    // protected $returnType           = 'array';
    protected $returnType           = \App\Entities\Panel\User::class;
    protected $useSoftDeletes       = false;
    protected $protectFields        = true;
    protected $allowedFields        = ['nomor_induk', 'attendance_solution_id', 'rfid', 'phone', 'username', 'fullname', 'password_hash', 'status', 'photo', 'cover', 'kelas_id', 'about_me'];

    // Dates
    protected $useTimestamps        = true;
    protected $dateFormat           = 'int';
    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)
    {
        $predis = null;

        $user = new \App\Entities\Panel\User();
        if (redison()) {
            try {
                $redis  = json_decode(options('redis-config'), true);
                $predis = new Client([
                    'scheme' => 'tcp',
                    'host'   => $redis['host'],
                    'port'   => $redis['port'],
                    'password' => $redis['password'],
                    'database' => $redis['database'],
                ]);

                $predis->connect();
                $result = $predis->get("panel-user-account-$id");
                if ($result) {
                    $user->fill(json_decode($result, true));
                    return $user;
                }
            } catch (\Throwable $th) {
                $predis = null;
            }
        }
        $bu = base_url(config('app')->imgPath . "/users");
        $builder = $this->db->table($this->table);
        $builder->select("users.*,CONCAT('$bu/',cover) cover,CONCAT('$bu/',photo) photo,about_me,mk.nama nama_kelas,mk.kode kode_kelas,mt.kode kode_tingkat,mj.nama nama_jurusan,mj.kode kode_jurusan,GROUP_CONCAT( roles.name) role");
        $builder->join('users_roles ur', 'ur.user_id=users.id', 'left');
        $builder->join('m_kelas mk', 'mk.id=users.kelas_id', 'left');
        $builder->join('kelas_data kd', 'kd.kelas_id=mk.id', 'left');
        $builder->join('m_tingkat mt', 'mt.id=kd.tingkat_id', 'left');
        $builder->join('m_jurusan mj', 'mj.id=kd.jurusan_id', 'left');
        $builder->join('roles', 'roles.id=ur.role_id', 'left');
        $builder->where(['users.id' => $id]);
        $builder->groupBy('ur.user_id');
        $result = $builder->get()->getRowArray();
        if ($predis && $result) $predis->set("panel-user-account-$id", json_encode($result), 'EX', 60 * 20);
        $result['role'] = explode(',', $result['role'] ?? '');
        $user->fill($result);
        return $user;
    }
    public function ubah($user)
    {
        try {
            $user = $user->toArray();
        } catch (\Throwable $th) {
            //throw $th;
        }
        $dumpuser = [];
        foreach ($this->allowedFields as $key => $value) {
            if (!isset($user[$value])) continue;
            $dumpuser[$value] = $user[$value];
        }
        $userkey = isset($user['id']) ? ['id' => $user['id']] : ['username' => $user['username']];
        $dumpuser['updated_at'] = time();
        $this->db->transStart();
        $this->db->table($this->table)->update($dumpuser, $userkey);
        if (isset($user['role'])) {
            $this->db->table('users_roles')->delete(['user_id' => $user['id']]);
            if (is_string($user['role']) || is_int($user['role'])) $user['role'] = [$user['role']];
            foreach ($user['role'] as $role) {
                if (filter_var($role, FILTER_VALIDATE_INT)) {
                    $this->db->table('users_roles')->insert(['user_id' => $user['id'], 'role_id' => $role]);
                } else {
                    $this->db->query("INSERT INTO users_roles SET user_id=$user[id], role_id=(SELECT id FROM roles WHERE name = '$role' LIMIT 1)");
                }
            }
        }
        $this->db->transComplete();
        $result =  !($this->db->transStatus() === FALSE);
        if ($result) {
            if (redison()) {
                try {
                    $redis  = json_decode(options('redis-config'), true);
                    $predis = new Client([
                        'scheme' => 'tcp',
                        'host'   => $redis['host'],
                        'port'   => $redis['port'],
                        'password' => $redis['password'],
                        'database' => $redis['database'],
                    ]);

                    $predis->connect();
                    $predis->del("panel-user-account-$user[id]");
                } catch (\Throwable $th) {
                }
            }
        }
        return $result;
    }
    public function tambah($user)
    {
        try {
            $user = $user->toArray();
        } catch (\Throwable $th) {
            //throw $th;
        }
        $dumpuser = [];
        foreach ($this->allowedFields as $key => $value) {
            if (!isset($user[$value])) continue;
            $dumpuser[$value] = $user[$value];
        }
        $dumpuser['created_at'] = time();
        $dumpuser['updated_at'] = time();
        $this->db->transStart();
        $this->db->table($this->table)->insert($dumpuser);
        $uid = $this->db->insertID();
        if (isset($user['role'])) {
            if (is_string($user['role']) || is_int($user['role'])) $user['role'] = [$user['role']];
            foreach ($user['role'] as $role) {
                if (filter_var($role, FILTER_VALIDATE_INT)) {
                    $this->db->query("INSERT INTO users_roles SET user_id=$uid, role_id=$role");
                } else {
                    $this->db->query("INSERT INTO users_roles SET user_id=$uid, role_id=(SELECT id FROM roles WHERE name = '$role' LIMIT 1)");
                }
            }
        }
        $this->db->transComplete();
        return  !($this->db->transStatus() === FALSE);
    }
}
