<?php

namespace App\Models\Panel\Conversations;

use CodeIgniter\Model;

class GroupConversations extends Model
{
    protected $DBGroup          = 'default';
    protected $table            = 'group_conversations';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = false;
    protected $insertID         = 0;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'id',
        'group_type',
        'group_name',
    ];

    // Dates
    protected $useTimestamps = true;
    protected $dateFormat    = 'int';
    protected $createdField  = 'created_at';
    protected $updatedField  = 'updated_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    = [];
    static public function generateId()
    {
        return time() . uniqid('-');
    }
    public function getInitConvesations($gc_id, $limit = 10)
    {
        $uid = user()->id;
        $jumlah = $this->db->table('panel_conversations')->where('gc_id', $gc_id)->countAllResults();
        $select = ["u.nomor_induk,u.fullname,(CASE WHEN u.id = $uid THEN 1 ELSE 0 END) is_me"];
        $select[] = "pc.id,pc.gc_id,pc.user_id,pc.message,pc.created_at,pc.updated_at";
        $builder = $this->db->table("panel_conversations pc");
        $builder->select(implode(',', $select));
        $builder->join('users u', "u.id=pc.user_id");
        $builder->where('pc.gc_id', $gc_id);
        $builder->orderBy("pc.created_at", 'ASC', false);
        return $builder->get($limit, $jumlah > $limit ? $jumlah - $limit : 0)->getResultArray();
    }

    public function isMember($uid, $gcid)
    {
        $gc = $this->db->table("group_conversations gc");
        $gc->join('group_conversations_member gcm', 'gcm.gc_id=gc.id');
        $gc->where('gcm.user_id', $uid);
        $gc->where('gc.id', $gcid);
        return $gc->get()->getRowArray();
    }

    public function out($gc_id, $uid)
    {
        $this->db->transStart();
        $this->db->table('group_conversations_member')->where('gc_id', $gc_id)->where('user_id', $uid)->delete();
        if ($this->db->affectedRows() < 1) {
            $this->db->transRollback();
            return false;
        }
        $gc = $this->db->table("group_conversations gc");
        $gc->select("COUNT(gcm.id) members", false);
        $gc->join('group_conversations_member gcm', 'gcm.gc_id=gc.id', 'left');
        $gc->where('gc.id', $gc_id);
        $gc = $gc->get()->getRowArray();
        if ($gc['members'] < 2) $this->db->table('group_conversations')->where('id', $gc_id)->delete();
        $this->db->transCommit();
        return !($this->db->transStatus() === false);
    }
    // public function getOldest($jadwal_id, $lastid, $limit = 10)
    // {
    //     $select = ["jd.id,IFNULL(u.fullname,ms.nama) nama,(CASE WHEN u.id IS NULL THEN 0 ELSE 1 END) is_me"];
    //     $select[] = "jd.conversation,IFNULL(u.nomor_induk,ms.nomor_induk) nomor_induk,jd.created_at,jd.updated_at";
    //     $builder = $this->db->table("$this->table jd");
    //     $builder->select(implode(',', $select));
    //     $builder->join('m_siswa ms', "ms.id=jd.user_id AND jd.user_type='mobile'", 'left', false);
    //     $builder->join('users u', "u.id=jd.user_id AND jd.user_type='staff'", 'left', false);
    //     $builder->where('jd.jadwal_id', $jadwal_id);
    //     $builder->where("SUBSTRING_INDEX(jd.id,' - ',1) <=", "SUBSTRING_INDEX('$lastid','-',1)", false);
    //     $builder->where('jd.id !=', $lastid);
    //     $builder->orderBy("SUBSTRING_INDEX(jd.id,'-',1)", 'DESC', false);
    //     return $builder->get($limit, 0)->getResultArray();
    // }
    // public function getNewest($jadwal_id, $lastid, $limit = 5)
    // {
    //     $select = ["jd.id,IFNULL(u.fullname,ms.nama) nama,(CASE WHEN u.id IS NULL THEN 0 ELSE 1 END) is_me"];
    //     $select[] = "jd.conversation,IFNULL(u.nomor_induk,ms.nomor_induk) nomor_induk,jd.created_at,jd.updated_at";
    //     $builder = $this->db->table("$this->table jd");
    //     $builder->select(implode(',', $select));
    //     $builder->join('m_siswa ms', "ms.id=jd.user_id AND jd.user_type='mobile'", 'left', false);
    //     $builder->join('users u', "u.id=jd.user_id AND jd.user_type='staff'", 'left', false);
    //     $builder->where('jd.jadwal_id', $jadwal_id);
    //     $builder->where("SUBSTRING_INDEX(jd.id,' - ',1) >=", "SUBSTRING_INDEX('$lastid','-',1)", false);
    //     $builder->where('jd.id !=', $lastid);
    //     $builder->orderBy("SUBSTRING_INDEX(jd.id,'-',1)", 'ASC', false);
    //     return $builder->get($limit, 0)->getResultArray();
    // }
}
