<?php
class Chat_system_model extends CI_Model {
    
    public function __construct() {
        parent::__construct();
    }
    
    // Get user information
    public function get_user_info($user_type, $user_id) {
        if ($user_type === 'admin') {
            $this->db->select('id, nama as name, email');
            $this->db->from('admin');
            $this->db->where('id', $user_id);
        } else {
            $this->db->select('id_penghuni as id, nama_penghuni as name, email, kamar, no_hp, alamat');
            $this->db->from('penghuni');
            $this->db->where('id_penghuni', $user_id);
        }
        
        return $this->db->get()->row();
    }
    
    // Get chat conversations for admin (left panel)
    public function get_admin_conversations($admin_id) {
        $this->db->select('
            p.id_penghuni,
            p.nama_penghuni,
            p.kamar,
            p.email,
            p.no_hp,
            MAX(cm.created_at) as last_message_time,
            (SELECT message FROM chat_message 
             WHERE id_penghuni = p.id_penghuni 
             AND id_admin = '.$admin_id.' 
             AND deleted_at IS NULL
             ORDER BY created_at DESC LIMIT 1) as last_message,
            (SELECT sender FROM chat_message 
             WHERE id_penghuni = p.id_penghuni 
             AND id_admin = '.$admin_id.' 
             AND deleted_at IS NULL
             ORDER BY created_at DESC LIMIT 1) as last_message_sender,
            COUNT(CASE WHEN cm.is_read_admin = 0 AND cm.sender = "penghuni" AND cm.deleted_at IS NULL THEN 1 END) as unread_count,
            cs.is_online,
            cs.last_seen
        ', FALSE);
        $this->db->from('penghuni p');
        $this->db->join('chat_message cm', 'cm.id_penghuni = p.id_penghuni AND cm.id_admin = '.$admin_id, 'left');
        $this->db->join('chat_sessions cs', 'cs.id_penghuni = p.id_penghuni AND cs.id_admin = '.$admin_id, 'left');
        $this->db->where('p.id_admin', $admin_id);
        $this->db->group_by('p.id_penghuni');
        $this->db->order_by('last_message_time', 'DESC');
        
        return $this->db->get()->result();
    }
    
    // Get messages between two users
    public function get_conversation($admin_id, $penghuni_id, $limit = 100, $offset = 0) {
        $this->db->select('*');
        $this->db->from('chat_message');
        $this->db->where('id_admin', $admin_id);
        $this->db->where('id_penghuni', $penghuni_id);
        $this->db->where('deleted_at IS NULL');
        $this->db->order_by('created_at', 'ASC'); // ASC untuk tampilan chat (oldest first)
        $this->db->limit($limit, $offset);
        
        return $this->db->get()->result();
    }
    
    // Send message
    public function send_message($data) {
        // Set default values
        if (!isset($data['created_at'])) {
            $data['created_at'] = date('Y-m-d H:i:s');
        }
        if (!isset($data['message_type'])) {
            $data['message_type'] = 'text';
        }
        if (!isset($data['is_delivered'])) {
            $data['is_delivered'] = 1;
        }
        
        // Insert message
        $this->db->insert('chat_message', $data);
        $message_id = $this->db->insert_id();
        
        // Update chat session
        $this->update_chat_session($data['id_admin'], $data['id_penghuni']);
        
        return $message_id;
    }
    
    // Update chat session
    public function update_chat_session($admin_id, $penghuni_id) {
        // Check if session exists
        $this->db->where('id_admin', $admin_id);
        $this->db->where('id_penghuni', $penghuni_id);
        $session = $this->db->get('chat_sessions')->row();
        
        if ($session) {
            // Update existing session
            $this->db->where('id_session', $session->id_session);
            $this->db->update('chat_sessions', [
                'last_message_at' => date('Y-m-d H:i:s'),
                'is_active' => 1,
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        } else {
            // Create new session
            $this->db->insert('chat_sessions', [
                'id_admin' => $admin_id,
                'id_penghuni' => $penghuni_id,
                'last_message_at' => date('Y-m-d H:i:s'),
                'is_active' => 1,
                'is_online' => 0,
                'unread_count_admin' => 0,
                'unread_count_penghuni' => 0,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s')
            ]);
        }
    }
    
    // Mark messages as read
    public function mark_as_read($admin_id, $penghuni_id, $reader_type) {
        $this->db->where('id_admin', $admin_id);
        $this->db->where('id_penghuni', $penghuni_id);
        $this->db->where('deleted_at IS NULL');
        
        if ($reader_type === 'admin') {
            // Admin reading penghuni's messages
            $this->db->where('sender', 'penghuni');
            $this->db->where('is_read_admin', 0);
            
            $this->db->update('chat_message', [
                'is_read_admin' => 1,
                'read_at_admin' => date('Y-m-d H:i:s'),
                'is_read' => 1 // Update general is_read flag too
            ]);
            
            // Reset unread count in session
            $this->db->where('id_admin', $admin_id);
            $this->db->where('id_penghuni', $penghuni_id);
            $this->db->update('chat_sessions', [
                'unread_count_admin' => 0
            ]);
            
        } else {
            // Penghuni reading admin's messages
            $this->db->where('sender', 'admin');
            $this->db->where('is_read_penghuni', 0);
            
            $this->db->update('chat_message', [
                'is_read_penghuni' => 1,
                'read_at_penghuni' => date('Y-m-d H:i:s'),
                'is_read' => 1 // Update general is_read flag too
            ]);
            
            // Reset unread count in session
            $this->db->where('id_admin', $admin_id);
            $this->db->where('id_penghuni', $penghuni_id);
            $this->db->update('chat_sessions', [
                'unread_count_penghuni' => 0
            ]);
        }
        
        return $this->db->affected_rows();
    }
    
    // Get unread count for admin
    public function get_admin_unread_count($admin_id) {
        $this->db->select('cm.id_penghuni, COUNT(cm.id_chat) as unread_count');
        $this->db->from('chat_message cm');
        $this->db->join('penghuni p', 'p.id_penghuni = cm.id_penghuni');
        $this->db->where('cm.id_admin', $admin_id);
        $this->db->where('cm.sender', 'penghuni');
        $this->db->where('cm.is_read_admin', 0);
        $this->db->where('cm.deleted_at IS NULL');
        $this->db->group_by('cm.id_penghuni');
        
        return $this->db->get()->result();
    }
    
    // Get unread count for penghuni
    public function get_penghuni_unread_count($penghuni_id) {
        $this->db->select('COUNT(*) as unread_count');
        $this->db->from('chat_message');
        $this->db->where('id_penghuni', $penghuni_id);
        $this->db->where('sender', 'admin');
        $this->db->where('is_read_penghuni', 0);
        $this->db->where('deleted_at IS NULL');
        
        $result = $this->db->get()->row();
        return $result ? $result->unread_count : 0;
    }
    
    // Update user online status
    public function update_online_status($user_type, $user_id, $is_online = true) {
        // This updates all sessions for the user
        $where_field = ($user_type === 'admin') ? 'id_admin' : 'id_penghuni';
        
        $this->db->where($where_field, $user_id);
        $this->db->update('chat_sessions', [
            'is_online' => $is_online ? 1 : 0,
            'last_seen' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        
        return $this->db->affected_rows();
    }
    
    // Get online status for specific chat pair
    public function get_online_status($penghuni_id, $admin_id) {
        $this->db->select('is_online, last_seen');
        $this->db->from('chat_sessions');
        $this->db->where('id_penghuni', $penghuni_id);
        $this->db->where('id_admin', $admin_id);
        $this->db->limit(1);
        
        $result = $this->db->get()->row();
        
        if ($result) {
            return [
                'is_online' => $result->is_online == 1,
                'last_seen' => $result->last_seen
            ];
        }
        
        return [
            'is_online' => false,
            'last_seen' => null
        ];
    }
    
    // Delete message (soft delete)
    public function delete_message($message_id, $user_type, $user_id) {
        $this->db->where('id_chat', $message_id);
        
        // Verify ownership
        if ($user_type === 'admin') {
            $this->db->where('id_admin', $user_id);
        } else {
            $this->db->where('id_penghuni', $user_id);
        }
        
        $this->db->update('chat_message', [
            'deleted_at' => date('Y-m-d H:i:s')
        ]);
        
        return $this->db->affected_rows() > 0;
    }
    
    // Get chat statistics for admin
    public function get_admin_chat_stats($admin_id) {
        // Total conversations
        $this->db->where('id_admin', $admin_id);
        $total_conversations = $this->db->count_all_results('chat_sessions');
        
        // Total unread messages
        $this->db->where('id_admin', $admin_id);
        $this->db->where('sender', 'penghuni');
        $this->db->where('is_read_admin', 0);
        $this->db->where('deleted_at IS NULL');
        $total_unread = $this->db->count_all_results('chat_message');
        
        // Active conversations (with messages in last 24 hours)
        $this->db->where('id_admin', $admin_id);
        $this->db->where('last_message_at >=', date('Y-m-d H:i:s', strtotime('-24 hours')));
        $active_conversations = $this->db->count_all_results('chat_sessions');
        
        return [
            'total_conversations' => $total_conversations,
            'total_unread' => $total_unread,
            'active_conversations' => $active_conversations
        ];
    }
}