<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Pengaduan_model extends CI_Model {

    public function generate_kode_tiket() {
        $prefix = 'TKT';
        $date = date('Ymd');
        $this->db->like('kode_tiket', $prefix.$date, 'after');
        $count = $this->db->count_all_results('pengaduan');
        return $prefix . $date . str_pad($count + 1, 3, '0', STR_PAD_LEFT);
    }

    public function get_all($status = null, $user_id = null) {
        $this->db->select('pengaduan.*, u1.nama_lengkap as pengirim, u2.nama_lengkap as penjawab');
        $this->db->join('users u1', 'u1.id = pengaduan.user_id', 'left');
        $this->db->join('users u2', 'u2.id = pengaduan.dibalas_oleh', 'left');
        
        if($status) $this->db->where('pengaduan.status', $status);
        if($user_id) $this->db->where('pengaduan.user_id', $user_id);
        
        $this->db->order_by('created_at', 'DESC');
        return $this->db->get('pengaduan')->result();
    }

    public function get_by_id($id) {
        $this->db->select('pengaduan.*, u1.nama_lengkap as pengirim, u2.nama_lengkap as penjawab');
        $this->db->join('users u1', 'u1.id = pengaduan.user_id', 'left');
        $this->db->join('users u2', 'u2.id = pengaduan.dibalas_oleh', 'left');
        return $this->db->get_where('pengaduan', ['pengaduan.id' => $id])->row();
    }

    public function insert($data) {
        return $this->db->insert('pengaduan', $data);
    }

    public function balas($id, $data) {
        $this->db->where('id', $id);
        return $this->db->update('pengaduan', $data);
    }

    public function delete($id) {
        $this->db->where('id', $id);
        return $this->db->delete('pengaduan');
    }

    public function count_unread() {
        return $this->db->where('status', 'baru')->count_all_results('pengaduan');
    }
}