<?php
namespace model;

use model\database;


class stock {
    
    public static function get_stock_by_id(int $sid) {
        return ((new database())->pdo_prepare(
            'select s.sid, b.bid, b.cid, b.name, b.isbn, b.author, b.publish, b.cover, b.lang, s.place, s.health, s.state'.
            ' from stock s left join books b on s.bid = b.bid where s.sid = :sid')->execute([':sid' => $sid])) ?? false;
    }
    
    public static function del_stock_by_id(int $sid) {
        return (new database())->table('stock')->where(['sid' => $sid])->delete();
    }
    
    public static function add_stock($bid, $place, $health, $state) {
        return (new database())->table('stock')->insert([
            'bid' => $bid,
            'place' => $place,
            'health' => $health,
            'state' => $state
        ]);
    }
    
    public static function update_stock(int $sid, $bid, $place, $health, $state) {
        return (new database())->table('stock')->where(['sid' => $sid])->update([
            'bid' => $bid,
            'place' => $place,
            'health' => $health,
            'state' => $state
        ]);
    }
    
    public static function update_stock_state(int $sid, $state) {
        return (new database())->table('stock')->where(['sid' => $sid])->update(['state' => $state]);
    }
    
    public static function count_stock() {
        return (new database())->table('stock')->count();
    }
    
    public static function count_in_stock() {
        return (new database())->table('stock')->where(['state' => 0])->count();
    }
    
    public static function count_out_stock() {
        return (new database())->table('stock')->where(['state' => 1])->count();
    }
    
    public static function count_stock_by_bid(int $bid) {
        return (new database())->table('stock')->where(['bid' => $bid])->count();
    }
    
    public static function count_in_stock_by_bid(int $bid) {
        return (new database())->table('stock')->where(['bid' => $bid, 'state' => 0])->count();
    }
    
    public static function list_stock(int $page = 1) {
        $stock = (new database())->pdo_query(
            'select s.sid, b.bid, b.cid, b.name, b.isbn, b.author, b.publish, b.cover, b.lang, s.place, s.health, s.state'.
            ' from stock s left join books b on s.bid = b.bid limit '.(($page-1)*20).', 20');
        return isset($stock[0]['sid']) ? $stock : [$stock];
    }
    
    public static function list_stock_by_bid(int $bid, int $page = 1) {
        $stock = (new database())->pdo_query(
            'select s.sid, b.bid, b.cid, b.name, b.isbn, b.author, b.publish, b.cover, b.lang, s.place, s.health, s.state'.
            ' from stock s left join books b on s.bid = b.bid where s.bid = '.$bid.' limit '.(($page-1)*20).', 20');
        return isset($stock[0]['sid']) ? $stock : [$stock];
    }
    
}
