<?php
class Chat_api_model extends CI_Model {
    
    public function get_user_info($userType, $userId) {
        if ($userType === 'admin') {
            $this->db->select('id, nama as name, email, status');
            $this->db->from('admin');
            $this->db->where('id', $userId);
            $this->db->where('status', 'aktif');
        } else {
            $this->db->select('id_penghuni as id, nama_penghuni as name, email, no_hp as phone, kamar');
            $this->db->from('penghuni');
            $this->db->where('id_penghuni', $userId);
        }
        
        $query = $this->db->get();
        return $query->row();
    }
    
    public function store_auth_token($token, $userType, $userId, $expires) {
        $data = [
            'token' => $token,
            'user_type' => $userType,
            'user_id' => $userId,
            'expires_at' => date('Y-m-d H:i:s', $expires),
            'created_at' => date('Y-m-d H:i:s')
        ];
        
        $this->db->insert('chat_auth_tokens', $data);
        return $this->db->insert_id();
    }
    
    public function get_messages($id_penghuni, $id_admin, $limit = 50, $offset = 0) {
        // PERBAIKAN: Cast limit dan offset ke integer
        $limit = (int)$limit;
        $offset = (int)$offset;
        
        $sql = "
            SELECT cm.*,
                CASE 
                    WHEN cm.sender = 'admin' THEN a.nama
                    WHEN cm.sender = 'penghuni' THEN p.nama_penghuni
                END as sender_name
            FROM chat_message cm
            LEFT JOIN admin a ON a.id = cm.id_admin
            LEFT JOIN penghuni p ON p.id_penghuni = cm.id_penghuni
            WHERE cm.id_penghuni = ?
            AND cm.id_admin = ?
            AND cm.deleted_at IS NULL
            ORDER BY cm.created_at DESC
            LIMIT {$limit} OFFSET {$offset}
        ";
        
        $query = $this->db->query($sql, [$id_penghuni, $id_admin]);
        return $query->result();
    }
    
    // ALTERNATIF: Solusi menggunakan Query Builder yang lebih aman
    public function get_messages_safe($id_penghuni, $id_admin, $limit = 50, $offset = 0) {
        // Pastikan limit dan offset integer
        $limit = (int)$limit;
        $offset = (int)$offset;
        
        // Query Builder dengan select manual
        $this->db->select("cm.*, 
            CASE 
                WHEN cm.sender = 'admin' THEN a.nama
                WHEN cm.sender = 'penghuni' THEN p.nama_penghuni
            END as sender_name", FALSE);
        $this->db->from('chat_message cm');
        $this->db->join('admin a', 'a.id = cm.id_admin', 'left');
        $this->db->join('penghuni p', 'p.id_penghuni = cm.id_penghuni', 'left');
        $this->db->where('cm.id_penghuni', $id_penghuni);
        $this->db->where('cm.id_admin', $id_admin);
        $this->db->where('cm.deleted_at IS NULL');
        $this->db->order_by('cm.created_at', 'DESC');
        
        if ($limit > 0) {
            $this->db->limit($limit, $offset);
        }
        
        $query = $this->db->get();
        return $query->result();
    }
    
    public function save_message($data) {
        $this->db->insert('chat_message', $data);
        return $this->db->insert_id();
    }
    
    public function mark_as_read($messageIds, $readerType, $readerId) {
        if (empty($messageIds)) {
            return 0;
        }
        
        $field = $readerType === 'admin' ? 'is_read_admin' : 'is_read_penghuni';
        
        $this->db->where_in('id_chat', $messageIds);
        $this->db->update('chat_message', [$field => 1, 'is_read' => 1]);
        
        return $this->db->affected_rows();
    }
    
    public function get_unread_count($userType, $userId) {
        if ($userType === 'admin') {
            $this->db->where('id_admin', $userId);
            $this->db->where('is_read_admin', 0);
            $this->db->where('sender', 'penghuni');
        } else {
            $this->db->where('id_penghuni', $userId);
            $this->db->where('is_read_penghuni', 0);
            $this->db->where('sender', 'admin');
        }
        
        $this->db->from('chat_message');
        return $this->db->count_all_results();
    }
    
    public function get_online_status($userType, $userId) {
        $this->db->select('is_online');
        $this->db->from('chat_connections');
        $this->db->where('user_type', $userType);
        $this->db->where('user_id', $userId);
        $this->db->order_by('last_seen', 'DESC');
        $this->db->limit(1);
        
        $query = $this->db->get();
        $result = $query->row();
        
        return $result ? (bool)$result->is_online : false;
    }
    
    public function update_unread_count($id_penghuni, $id_admin, $sender) {
        $field = $sender === 'admin' ? 'unread_count_penghuni' : 'unread_count_admin';
        
        // Check if session exists
        $this->db->where('id_penghuni', $id_penghuni);
        $this->db->where('id_admin', $id_admin);
        $query = $this->db->get('chat_sessions');
        
        if ($query->num_rows() > 0) {
            // Update existing
            $this->db->set($field, $field . '+1', false);
            $this->db->where('id_penghuni', $id_penghuni);
            $this->db->where('id_admin', $id_admin);
            $this->db->update('chat_sessions');
        } else {
            // Create new
            $data = [
                'id_penghuni' => $id_penghuni,
                'id_admin' => $id_admin,
                $field => 1,
                'last_message_at' => date('Y-m-d H:i:s')
            ];
            $this->db->insert('chat_sessions', $data);
        }
    }
    
    // SOLUSI TERBAIK: Query Builder dengan select biasa + pemrosesan manual
    public function get_chat_messages($id_penghuni, $id_admin, $limit = 100, $offset = 0) {
        // Query dasar
        $this->db->select('cm.*, a.nama as admin_nama, p.nama_penghuni as penghuni_nama');
        $this->db->from('chat_message cm');
        $this->db->join('admin a', 'a.id = cm.id_admin', 'left');
        $this->db->join('penghuni p', 'p.id_penghuni = cm.id_penghuni', 'left');
        $this->db->where('cm.id_penghuni', $id_penghuni);
        $this->db->where('cm.id_admin', $id_admin);
        $this->db->where('cm.deleted_at IS NULL');
        $this->db->order_by('cm.created_at', 'DESC');
        
        if ($limit > 0) {
            $this->db->limit($limit, $offset);
        }
        
        $query = $this->db->get();
        $messages = $query->result();
        
        // Proses untuk menambahkan sender_name
        foreach ($messages as $message) {
            if ($message->sender == 'admin') {
                $message->sender_name = $message->admin_nama;
            } else {
                $message->sender_name = $message->penghuni_nama;
            }
        }
        
        return $messages;
    }
}