<?php

class PodbbangModel extends MY_Model
{

    private $currentPage = 1;
    private $perPage = 100;


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

    private function getParam($key) {
        return isset($this->config[$key]) ? $this->config[$key] : '';
    }

    public function getTable($config)
    {
        $this->config = $config;
        // $this->dateRange = [strtotime($this->getParam('dateRange')[0]), strtotime($this->getParam('dateRange')[1])];
        $this->perPage = $this->getParam('limit');
        if ($this->getParam('offset')) {
            $this->currentPage = $this->getParam('offset') / $this->perPage + 1;
        }
        $preBookingResult = $this->getTableResult();
        $preBookingResultsCount = $this->getTableResultsCount();
        return array('total' => $preBookingResultsCount, 'rows' => ($preBookingResultsCount ? $preBookingResult : []));
    }

    private function getTableResult()
    {
        $this->getTableClause();
        $this->db->offset(($this->currentPage - 1) * $this->perPage);
        $this->db->limit($this->perPage);
        $this->db->order_by('updatedAt', 'desc');
        return $this->db->get('cm_station')->result();
    }

    private function getTableClause()
    {
        if ($this->getParam('keyword')) {
            $this->db->like('Title', $this->getParam('keyword'), 'both');
        }

        if ($this->getParam('category') !== "") {
            $this->db->where('Category', $this->getParam('category'));
        }
        $this->db->group_start();
        $this->db->where('Category < ', 127);
        $this->db->or_where('Category', 0);
        $this->db->group_end();
    }

    private function getTableResultsCount()
    {
        $this->getTableClause();
        $this->db->from('cm_station');
        return $this->db->count_all_results();
    }

    public function updateCategory($id, $category) {
        $this->db->where('Id', $id)->update('cm_station', array(
            'Category' => $category
        ));
    }
}
