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

class Ebook_model extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    public function get_all($search = '', $offset = 0, $limit = 12, $kategori = '') {
        if ($search) {
            $this->db->group_start();
            $this->db->like('judul', $search);
            $this->db->or_like('penulis', $search);
            $this->db->or_like('kategori', $search);
            $this->db->group_end();
        }
        if ($kategori) {
            $this->db->where('kategori', $kategori);
        }
        $this->db->order_by('created_at', 'DESC');
        $this->db->limit($limit, $offset);
        return $this->db->get('ebooks')->result();
    }

    public function count_all($search = '', $kategori = '') {
        if ($search) {
            $this->db->group_start();
            $this->db->like('judul', $search);
            $this->db->or_like('penulis', $search);
            $this->db->or_like('kategori', $search);
            $this->db->group_end();
        }
        if ($kategori) {
            $this->db->where('kategori', $kategori);
        }
        return $this->db->count_all_results('ebooks');
    }

    public function get_by_id($id) {
        return $this->db->get_where('ebooks', ['id' => $id])->row();
    }

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

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

    public function delete($id) {
        return $this->db->delete('ebooks', ['id' => $id]);
    }

    public function get_categories() {
        $this->db->select('kategori');
        $this->db->distinct();
        $this->db->order_by('kategori', 'ASC');
        return $this->db->get('ebooks')->result();
    }

    public function count_by_category() {
        $this->db->select('kategori, COUNT(*) as total');
        $this->db->group_by('kategori');
        return $this->db->get('ebooks')->result();
    }

    public function get_recent($limit = 5) {
        $this->db->order_by('created_at', 'DESC');
        $this->db->limit($limit);
        return $this->db->get('ebooks')->result();
    }
}
