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

class Librarian extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model('Librarian_model');
        $this->load->library('session');
        $this->load->helper(['url', 'form']);
        // Ensure user is logged in and has librarian role
        if (!$this->session->userdata('user_id') || $this->session->userdata('role') !== 'librarian') {
            redirect('login');
        }
    }

    // Dashboard overview
    public function index() {
        $data['total_books'] = $this->Librarian_model->count_books();
        $data['available_books'] = $this->Librarian_model->count_available_books();
        $data['borrowed_books'] = $this->Librarian_model->count_borrowed_books();
        $data['overdue_books'] = $this->Librarian_model->count_overdue_books();
        $data['today_borrowings'] = $this->Librarian_model->today_borrowings();
        $data['today_returns'] = $this->Librarian_model->today_returns();
        $this->load->view('librarian/dashboard', $data);
    }

    // Book management list
    public function books() {
        $data['books'] = $this->Librarian_model->get_all_books();
        $this->load->view('librarian/book_list', $data);
    }

    // Add / edit book form
    public function book_form($id = null) {
        $data['book'] = $id ? $this->Librarian_model->get_book($id) : null;
        $this->load->view('librarian/book_form', $data);
    }

    // Save book (create or update)
    public function save_book() {
        $this->Librarian_model->save_book($this->input->post());
        redirect('librarian/books');
    }

    // Delete book
    public function delete_book($id) {
        $this->Librarian_model->delete_book($id);
        redirect('librarian/books');
    }

    // Borrowing management
    public function borrowings() {
        $data['borrowings'] = $this->Librarian_model->get_all_borrowings();
        $this->load->view('librarian/borrowings', $data);
    }

    // Return processing
    public function return_book($id) {
        $this->Librarian_model->process_return($id);
        redirect('librarian/borrowings');
    }
}
?>
