<?php

namespace App\Models\Panel\Conversations;

use CodeIgniter\Model;

class Conversations extends Model
{
    protected $DBGroup          = 'default';
    protected $table            = 'panel_conversations';
    protected $primaryKey       = 'id';
    protected $useAutoIncrement = false;
    protected $insertID         = 0;
    protected $returnType       = 'array';
    protected $useSoftDeletes   = false;
    protected $protectFields    = true;
    protected $allowedFields    = [
        'id',
        'gc_id',
        'user_id',
        'message',
    ];

    // 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 add($gc_id, $user_id, $message)
    {
        $pc_id = $this->generateId();
        $pc_data = [
            'id' => $pc_id,
            'gc_id' => $gc_id,
            'user_id' => $user_id,
            'message' => $message,
            'created_at' => time(),
            'updated_at' => time(),
        ];
        $result = [
            'status' => false,
            'message' => 'Gagal Menambah',
        ];
        $this->db->transStart();
        $this->db->table($this->table)->insert($pc_data);
        if ($this->db->affectedRows() < 1) return $result;
        $this->db->table('group_conversations')->where('id', $gc_id)->set('updated_at', $pc_data['updated_at'])->update();
        $this->db->transComplete();
        if ($this->db->transStatus() === false) return $result;
        $result['status'] = true;
        $result['id'] =  $pc_id;
        $result['message'] = 'Berhasil Menambah';
        return $result;
    }
    public function getNewest($gc_id, $uid, $lastid, $limit = 5)
    {
        $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("$this->table pc");
        $builder->select(implode(',', $select));
        $builder->join('users u', "u.id=pc.user_id", 'left', false);
        $builder->where('pc.gc_id', $gc_id);
        $builder->where("pc.created_at >=", "(SELECT spc.created_at FROM $this->table spc WHERE spc.id='$lastid'LIMIT 1)", false);
        $builder->where('pc.id !=', $lastid);
        $builder->orderBy("pc.created_at", 'ASC', false);
        return $builder->get($limit, 0)->getResultArray();
    }
    public function getOldest($gc_id, $uid, $lastid, $limit = 10)
    {
        $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("$this->table pc");
        $builder->select(implode(',', $select));
        $builder->join('users u', "u.id=pc.user_id", 'left', false);
        $builder->where('pc.gc_id', $gc_id);
        $builder->where("pc.created_at <=", "(SELECT spc.created_at FROM $this->table spc WHERE spc.id='$lastid'LIMIT 1)", false);
        $builder->where('pc.id !=', $lastid);
        $builder->orderBy("pc.created_at", 'DESC', false);
        return $builder->get($limit, 0)->getResultArray();
    }
}
