<?php
use model\books;
use model\stock;
use model\records;
use model\template;
use model\categories;

class default_controller {
    
    public function index() {
        $page = $_GET['page'] ?? 1;
        $count = records::count_hot_records();
        $books = records::list_hot_records($page);
        $categories = categories::get_categories();
        $records = isset($_SESSION['user']) ? records::get_in_records_by_uid($_SESSION['user']['uid']) : null;
        $records_count = isset($_SESSION['user']) ? records::count_in_records_by_uid($_SESSION['user']['uid']) : 0;
        $this->template('首页', 'index', ['books' => $books, 'page' => $page, 'count' => $count, 'categories' => $categories, 'records' => $records, 'records_count' => $records_count]);
    }
    
    public function lists() {
        $page = $_GET['page'] ?? 1;
        $count = books::count_books();
        $books = books::list_books($page);
        $categories = categories::get_categories();
        $records = isset($_SESSION['user']) ? records::get_in_records_by_uid($_SESSION['user']['uid']) : null;
        $records_count = isset($_SESSION['user']) ? records::count_in_records_by_uid($_SESSION['user']['uid']) : 0;
        $this->template('书籍列表', 'lists', ['books' => $books, 'page' => $page, 'count' => $count, 'categories' => $categories, 'records' => $records, 'records_count' => $records_count]);
    }
    
    public function search() {
        $page = $_GET['page'] ?? 1;
        if (isset($_GET['s']) && !empty($_GET['s'])) {
            $word = $_GET['s'] ?? '';
            $books = books::find_books($word, $page);
            $count = books::count_find_books($word);
            $categories = categories::get_categories();
        } else $word = $books = $count = $categories = null;
        $records = isset($_SESSION['user']) ? records::get_in_records_by_uid($_SESSION['user']['uid']) : null;
        $records_count = isset($_SESSION['user']) ? records::count_in_records_by_uid($_SESSION['user']['uid']) : 0;
        $this->template('书籍检索', 'search', ['books' => $books, 'page' => $page, 'count' => $count, 'categories' => $categories, 'records' => $records, 'records_count' => $records_count]);
    }
    
    public function book($bid) {
        $page = $_GET['page'] ?? 1;
        $count = stock::count_stock_by_bid($bid);
        $stock = stock::count_in_stock_by_bid($bid);
        $books = stock::list_stock_by_bid($bid, $page);
        $this->template('库存查询', 'book', ['books' => $books, 'page' => $page, 'count' => $count, 'stock' => $stock]);
    }
    
    private function template($title, $name, $parameters = []) {
        template::render('defaults', $name, array_merge(['title' => $title], $parameters));
    }
    
}