<?php
class Chat_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    public function check_subscription($id_admin)
    {
        $this->db->where('id_admin', $id_admin);
        $this->db->where('status', 'active');
        $this->db->where('start_date <=', date('Y-m-d H:i:s'));
        $this->db->where('end_date >=', date('Y-m-d H:i:s'));
        return $this->db->get('admin_subscription')->row();
    }

    public function get_messages($id_penghuni, $id_admin, $last_message_id = null, $limit = 50)
    {
        $this->db->where('id_penghuni', $id_penghuni);
        $this->db->where('id_admin', $id_admin);
        $this->db->where('deleted_at IS NULL', null, false);

        if ($last_message_id) {
            $this->db->where('id_chat <', $last_message_id);
        }

        $this->db->order_by('created_at', 'DESC');
        $this->db->limit($limit);
        return $this->db->get('chat_message')->result();
    }

    public function get_all_messages($id_penghuni, $id_admin)
    {
        $this->db->where('id_penghuni', $id_penghuni);
        $this->db->where('id_admin', $id_admin);
        $this->db->where('deleted_at IS NULL', null, false);
        $this->db->order_by('created_at', 'ASC');
        return $this->db->get('chat_message')->result();
    }

    public function get_message_by_id($message_id)
    {
        return $this->db->get_where('chat_message', ['id_chat' => $message_id])->row();
    }

    public function send_message($data)
    {
        $data['created_at'] = date('Y-m-d H:i:s');

        $this->db->insert('chat_message', $data);
        $message_id = $this->db->insert_id();

        // Update atau buat session chat
        if (isset($data['id_admin']) && isset($data['id_penghuni'])) {
            $session = $this->db->get_where('chat_sessions', [
                'id_admin' => $data['id_admin'],
                'id_penghuni' => $data['id_penghuni']
            ])->row();

            if ($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
                ]);
            } else {
                $this->db->insert('chat_sessions', [
                    'id_admin' => $data['id_admin'],
                    'id_penghuni' => $data['id_penghuni'],
                    'last_message_at' => date('Y-m-d H:i:s'),
                    'is_active' => 1,
                    'created_at' => date('Y-m-d H:i:s')
                ]);
            }
        }

        return $message_id;
    }

    public function get_last_message($id_penghuni, $id_admin)
    {
        $this->db->where('id_penghuni', $id_penghuni);
        $this->db->where('id_admin', $id_admin);
        $this->db->where('deleted_at IS NULL', null, false);
        $this->db->order_by('created_at', 'DESC');
        $this->db->limit(1);
        return $this->db->get('chat_message')->row();
    }

    public function get_chat_sessions($id_admin)
    {
        $this->db->select('cs.*, p.nama_penghuni, p.email, p.kamar');
        $this->db->from('chat_sessions cs');
        $this->db->join('penghuni p', 'p.id_penghuni = cs.id_penghuni');
        $this->db->where('cs.id_admin', $id_admin);
        $this->db->where('cs.is_active', 1);
        $this->db->order_by('cs.last_message_at', 'DESC');
        return $this->db->get()->result();
    }

    public function get_unread_count_admin($id_penghuni, $id_admin)
    {
        $this->db->where('id_penghuni', $id_penghuni);
        $this->db->where('id_admin', $id_admin);
        $this->db->where('is_read_admin', 0);
        $this->db->where('sender', 'penghuni');
        $this->db->where('deleted_at IS NULL', null, false);
        return $this->db->count_all_results('chat_message');
    }

    public function get_total_unread_admin($id_admin)
    {
        $this->db->where('id_admin', $id_admin);
        $this->db->where('is_read_admin', 0);
        $this->db->where('sender', 'penghuni');
        $this->db->where('deleted_at IS NULL', null, false);
        return $this->db->count_all_results('chat_message');
    }

    public function mark_all_as_read_admin($id_penghuni, $id_admin)
    {
        $this->db->where('id_penghuni', $id_penghuni);
        $this->db->where('id_admin', $id_admin);
        $this->db->where('is_read_admin', 0);
        $this->db->where('sender', 'penghuni');

        $this->db->update('chat_message', [
            'is_read_admin' => 1
        ]);

        return $this->db->affected_rows() > 0;
    }

    public function mark_messages_as_read_admin($message_ids, $id_admin)
    {
        if (empty($message_ids)) return false;

        $this->db->where_in('id_chat', $message_ids);
        $this->db->where('id_admin', $id_admin);

        $this->db->update('chat_message', [
            'is_read_admin' => 1
        ]);

        return $this->db->affected_rows() > 0;
    }

    public function check_user_online($user_id, $user_type = 'penghuni')
    {
        // Versi sederhana: return false untuk saat ini
        return false;

        // Atau jika ingin implementasi sederhana:
        // $this->db->select('COUNT(*) as count');
        // $this->db->from('chat_message');
        // $this->db->where('id_penghuni', $user_id);
        // $this->db->where('created_at >=', date('Y-m-d H:i:s', strtotime('-10 minutes')));
        // $query = $this->db->get();
        // $result = $query->row();
        // return ($result && $result->count > 0);
    }

    public function get_online_status($user_id, $user_type = 'penghuni')
    {
        return $this->check_user_online($user_id, $user_type);
    }

    public function get_last_seen($user_id, $user_type = 'penghuni')
    {
        $this->db->select('MAX(created_at) as last_activity');
        $this->db->from('chat_message');

        if ($user_type == 'penghuni') {
            $this->db->where('id_penghuni', $user_id);
        } elseif ($user_type == 'admin') {
            $this->db->where('id_admin', $user_id);
        }

        $this->db->limit(1);
        $last_message = $this->db->get()->row();

        return $last_message ? $last_message->last_activity : null;
    }

    public function search_penghuni($id_admin, $search_term, $limit = 10)
    {
        $this->db->select('p.*');
        $this->db->from('penghuni p');
        $this->db->join('chat_sessions cs', 'cs.id_penghuni = p.id_penghuni AND cs.id_admin = ' . $id_admin, 'left');
        $this->db->group_start();
        $this->db->like('p.nama_penghuni', $search_term);
        $this->db->or_like('p.email', $search_term);
        $this->db->or_like('p.kamar', $search_term);
        $this->db->or_like('p.no_hp', $search_term);
        $this->db->group_end();
        $this->db->where('p.status_penghuni', 'aktif');
        $this->db->order_by('cs.last_message_at', 'DESC');
        $this->db->limit($limit);

        return $this->db->get()->result();
    }

    public function delete_message($message_id)
    {
        $this->db->where('id_chat', $message_id);
        return $this->db->update('chat_message', [
            'deleted_at' => date('Y-m-d H:i:s')
        ]);
    }

    public function clear_chat_history($id_penghuni, $id_admin)
    {
        $this->db->where('id_penghuni', $id_penghuni);
        $this->db->where('id_admin', $id_admin);
        return $this->db->update('chat_message', [
            'deleted_at' => date('Y-m-d H:i:s')
        ]);
    }

    public function count_total_chats($id_admin)
    {
        $this->db->where('id_admin', $id_admin);
        $this->db->where('deleted_at IS NULL', null, false);
        return $this->db->count_all_results('chat_message');
    }

    public function get_chat_statistics($id_admin, $time_range = 'today')
    {
        $date_filter = '';

        switch ($time_range) {
            case 'today':
                $date_filter = "DATE(created_at) = CURDATE()";
                break;
            case 'week':
                $date_filter = "created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)";
                break;
            case 'month':
                $date_filter = "created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)";
                break;
            default:
                $date_filter = "DATE(created_at) = CURDATE()";
        }

        $this->db->select("
            COUNT(*) as total_messages,
            SUM(CASE WHEN sender = 'admin' THEN 1 ELSE 0 END) as sent_by_admin,
            SUM(CASE WHEN sender = 'penghuni' THEN 1 ELSE 0 END) as sent_by_penghuni,
            COUNT(DISTINCT id_penghuni) as active_chats,
            SUM(CASE WHEN is_read_admin = 0 AND sender = 'penghuni' THEN 1 ELSE 0 END) as unread_messages
        ");
        $this->db->where('id_admin', $id_admin);
        $this->db->where('deleted_at IS NULL', null, false);
        $this->db->where($date_filter);

        return $this->db->get('chat_message')->row();
    }
    public function get_messages_by_penghuni($id_penghuni)
    {
        // Ambil data penghuni untuk mengetahui admin yang mengelolanya
        $penghuni = $this->db->where('id_penghuni', $id_penghuni)
            ->get('penghuni')
            ->row();

        // Jika penghuni tidak ditemukan atau tidak punya admin pengelola
        if (!$penghuni || empty($penghuni->id_admin)) {
            return [];
        }

        // Ambil id_admin dari penghuni
        $id_admin = $penghuni->id_admin;

        // Ambil semua pesan antara penghuni & admin pengelolanya
        $this->db->where('id_penghuni', $id_penghuni);
        $this->db->where('id_admin', $id_admin);
        $this->db->where('deleted_at IS NULL', null, false);
        $this->db->order_by('created_at', 'ASC');

        return $this->db->get('chat_message')->result();
    }
}
