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

class User extends CI_Controller {

    public function __construct() {
        parent::__construct();
        $this->load->model(['User_model', 'Ebook_model']);
        $this->_check_auth('user');
    }

    private function _check_auth($required_role = 'user') {
        if (!$this->session->userdata('user_id')) {
            redirect('login');
        }
        $role = $this->session->userdata('role');
        if ($required_role === 'user' && $role === 'admin') {
            // Admin can access user area too, no redirect needed
        }
        if ($required_role === 'admin' && $role !== 'admin') {
            redirect('user/dashboard');
        }
    }

    public function index() {
        $data['title']       = 'Dashboard';
        $data['user']        = $this->session->userdata();
        $data['total_ebook'] = $this->Ebook_model->count_all();
        $data['categories']  = $this->Ebook_model->get_categories();
        $data['recent']      = $this->Ebook_model->get_recent(6);
        $this->load->view('user/dashboard', $data);
    }

    public function ebooks() {
        $data['title']      = 'Koleksi E-Book';
        $data['user']       = $this->session->userdata();
        $data['categories'] = $this->Ebook_model->get_categories();
        $this->load->view('user/ebooks', $data);
    }
}
