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

class Ai_chat_model extends CI_Model
{
    const TABLE_SESSION = 'tb_ai_chat_session';
    const TABLE_MESSAGE = 'tb_ai_chat_message';

    public function list_sessions($id_user)
    {
        return $this->db
            ->select('id_session, judul, last_message_at, created_at, updated_at')
            ->from(self::TABLE_SESSION)
            ->where('id_user', (int) $id_user)
            ->order_by('last_message_at', 'DESC')
            ->order_by('updated_at', 'DESC')
            ->get()
            ->result();
    }

    public function create_session($id_user, $judul = '')
    {
        $judul = trim((string) $judul);
        if ($judul === '') {
            $judul = 'Sesi ' . date('d/m H:i');
        }

        $now = date('Y-m-d H:i:s');
        $this->db->insert(self::TABLE_SESSION, [
            'id_user' => (int) $id_user,
            'judul' => $judul,
            'last_message_at' => $now,
            'created_at' => $now,
            'updated_at' => $now,
        ]);

        return (int) $this->db->insert_id();
    }

    public function get_session($id_session, $id_user)
    {
        return $this->db
            ->where('id_session', (int) $id_session)
            ->where('id_user', (int) $id_user)
            ->get(self::TABLE_SESSION)
            ->row();
    }

    public function delete_session($id_session, $id_user)
    {
        $session = $this->get_session($id_session, $id_user);
        if (!$session) {
            return false;
        }

        $this->db->where('id_session', (int) $id_session)->delete(self::TABLE_MESSAGE);
        $this->db->where('id_session', (int) $id_session)->where('id_user', (int) $id_user)->delete(self::TABLE_SESSION);
        return true;
    }

    public function get_messages($id_session, $id_user, $limit = 100)
    {
        return $this->get_messages_page($id_session, $id_user, 1, $limit);
    }

    public function count_messages($id_session, $id_user)
    {
        $session = $this->get_session($id_session, $id_user);
        if (!$session) {
            return 0;
        }

        return (int) $this->db
            ->from(self::TABLE_MESSAGE)
            ->where('id_session', (int) $id_session)
            ->where('id_user', (int) $id_user)
            ->count_all_results();
    }

    public function get_messages_page($id_session, $id_user, $page = 1, $per_page = 30)
    {
        $session = $this->get_session($id_session, $id_user);
        if (!$session) {
            return [];
        }

        $page = max(1, (int) $page);
        $per_page = max(1, min(100, (int) $per_page));
        $offset = ($page - 1) * $per_page;

        $rows = $this->db
            ->select('id_message, role, message_text, created_at')
            ->from(self::TABLE_MESSAGE)
            ->where('id_session', (int) $id_session)
            ->where('id_user', (int) $id_user)
            ->order_by('id_message', 'DESC')
            ->limit($per_page, $offset)
            ->get()
            ->result();

        return array_reverse($rows);
    }

    public function get_context_messages($id_session, $id_user, $limit = 12)
    {
        $session = $this->get_session($id_session, $id_user);
        if (!$session) {
            return [];
        }

        $rows = $this->db
            ->select('role, message_text')
            ->from(self::TABLE_MESSAGE)
            ->where('id_session', (int) $id_session)
            ->where('id_user', (int) $id_user)
            ->where_in('role', ['user', 'assistant'])
            ->order_by('id_message', 'DESC')
            ->limit((int) $limit)
            ->get()
            ->result();

        return array_reverse($rows);
    }

    public function add_message($id_session, $id_user, $role, $message_text)
    {
        $session = $this->get_session($id_session, $id_user);
        if (!$session) {
            return 0;
        }

        $now = date('Y-m-d H:i:s');
        $this->db->insert(self::TABLE_MESSAGE, [
            'id_session' => (int) $id_session,
            'id_user' => (int) $id_user,
            'role' => (string) $role,
            'message_text' => (string) $message_text,
            'created_at' => $now,
        ]);

        $this->db
            ->where('id_session', (int) $id_session)
            ->where('id_user', (int) $id_user)
            ->update(self::TABLE_SESSION, [
                'last_message_at' => $now,
                'updated_at' => $now,
            ]);

        return (int) $this->db->insert_id();
    }

    public function trim_session_messages($id_session, $id_user, $max_messages = 400)
    {
        $session = $this->get_session($id_session, $id_user);
        if (!$session) {
            return 0;
        }

        $max_messages = max(50, (int) $max_messages);
        $total = $this->count_messages($id_session, $id_user);
        if ($total <= $max_messages) {
            return 0;
        }

        $to_delete = $total - $max_messages;
        $rows = $this->db
            ->select('id_message')
            ->from(self::TABLE_MESSAGE)
            ->where('id_session', (int) $id_session)
            ->where('id_user', (int) $id_user)
            ->order_by('id_message', 'ASC')
            ->limit($to_delete)
            ->get()
            ->result();

        if (!$rows) {
            return 0;
        }

        $ids = [];
        foreach ($rows as $row) {
            $ids[] = (int) $row->id_message;
        }

        if (!$ids) {
            return 0;
        }

        $this->db
            ->where('id_session', (int) $id_session)
            ->where('id_user', (int) $id_user)
            ->where_in('id_message', $ids)
            ->delete(self::TABLE_MESSAGE);

        return count($ids);
    }
}
