<?php

defined('BASEPATH') or exit('No direct script access allowed');

class Course_subcategory_model extends MY_Model
{
    use \app\libraries\Tenants;

    public $short = "ccs";
    public $table;
    public $tbl;
	public $fullTbl;
	public $fullTable;
//    public $database;

    public function __construct()
    {
        parent::__construct();
        $this->database = $this->session->userdata('tenant_no');
        $this->tbl = "course_category_sub";
        $this->table = $this->tbl . ' ' . $this->short;
		$this->fullTbl = $this->table_prefix . $this->tbl;
		$this->fullTable = $this->table_prefix . $this->table;
    }

    public function totalCount()
    {
        $db = $this->load->database($this->database, TRUE);
        $db->from($this->fullTable);
        if ($this->database == 'default') {
            $db->where(['tenant_no' => $this->session->userdata('tenant_no')]);
        }
        return $db->count_all_results();
    }

    public function filteredCount($param)
    {
        $fields = [$this->short . '.id', 'cc.name AS category', $this->short . '.name', $this->short . '.status', $this->short . '.create_time', $this->short . '.update_time'];
        $start = $param['start'];
        $length = $param['length'];
        $joins['course_category cc'] = "cc.id = " . $this->short . ".course_category_id";
        $db = $this->load->database($this->database, TRUE);
        $db->select(implode(', ', $fields));
        $db->from($this->fullTable);
        if ($this->database == 'default') {
            $db->where(['tenant_no' => $this->session->userdata('tenant_no')]);
        }
        foreach ($joins as $joinTbl => $condition) {
            $db->join($this->table_prefix . $joinTbl, $condition);
        }
        $search = [];
        foreach ($param['columns'] as $column) {
            if ($column['searchable'] === "true" && !empty($column['search']['value'])) {
                $colName = str_replace(array('category', 'subname', 'subcc.name'), array('cc.name', 'ccs.name', 'ccs.name'), $column['data']);
                $searchfield = ($colName === 'cc.name' || $colName === 'ccs.name' || $colName === 'subcc.name') ? $colName : $this->short . "." . $colName;
                $search[$searchfield] = $column['search']['value'];
            }
        }
        if (!empty($search)) {
            foreach ($search as $k => $v) {
                if ($v !== '') {
                    if ($k === 'name') {
                        $db->like($search);
                    }
                    $db->like($search, 'none');
                }
            }
        }
        return count($db->get()->result_array());
    }

    public function listing($param)
    {
        $fields = [$this->short . '.id', 'cc.name AS category','cc.status As categorystatus', $this->short . '.name', $this->short . '.status', $this->short . '.create_time', $this->short . '.update_time'];
        $orders = [];
        foreach ($param['order'] as $order) {
            $colIdx = $order['column'];
            $colName = str_replace('category', 'cc.name', $param['columns'][$colIdx]['data']);
            $dir = strtoupper($order['dir']);
            $orders[] = ($colName === 'cc.name') ? $colName . ' ' . $dir : $this->short . "." . $colName . ' ' . $dir;
        }
        $start = $param['start'];
        $length = $param['length'];
        $joins[$this->table_prefix . 'course_category cc'] = "cc.id = " . $this->short . ".course_category_id";
        $search = [];
        foreach ($param['columns'] as $column) {
            if ($column['searchable'] === "true" && !empty($column['search']['value'])) {
                $colName = str_replace(array('category', 'subname', 'subcc.name'), array('cc.name', 'ccs.name', 'ccs.name'), $column['data']);
                $searchfield = ($colName === 'cc.name' || $colName === 'ccs.name' || $colName === 'subcc.name') ? $colName : $this->short . "." . $colName;
                $search[$searchfield] = $column['search']['value'];
            }
        }
        $this->load->model('Course_model');
        $courses = $this->Course_model->all('','',[$this->Course_model->short.'.course_category_sub_id']);
        $subcatIds = [];
        foreach($courses as $v){
            $subcatIds[]=$v['course_category_sub_id'];
        }
        $result = $this->getFromDBFilter($this->database, $this->table, $fields, $start, $length, $orders, $search, $joins, 'cc.name');
        $data = [];
        foreach ($result as $row) {
            $disabled=in_array($row['id'],$subcatIds)?' disabled':'';
            $data[] = [
                'id' => $row['id'],
                'category' => $row['categorystatus']==0?'<span class="notinuse">'.$row['category'].'</span>':$row['category'],
                'name' => $row['name'],
                'create_time' => date("Y-m-d H:i:s", $row['create_time']),
                'update_time' => date("Y-m-d H:i:s", $row['update_time']),
                'details' => '<button id="details-' . $row['id'] . '">詳情</button>',
                'status' => is_null($row['status']) ? '' : $this->status[$row['status']],
                'delete' => '<input id="' . $row['id'] . '" type="checkbox" class="checkbox-delete"'.$disabled.' />',
            ];
        }
        return $data;
    }

    public function listing_by_course_category($courseCategoryId)
    {
        $this->tenant();

        return $this->db->from($this->fullTbl)
            ->where('course_category_id', $courseCategoryId)
            ->get()
            ->result_array();
    }

    public function listing_selection()
    {
        $this->tenant();

        return $this->db->from($this->fullTbl)
            ->get()
            ->result_array();
    }

    public function detail($id)
    {
        $this->tenant();

        return $this->db->from($this->fullTbl)
            ->where('id', $id)
            ->get()
            ->row_array();
    }

    public function insert($param)
    {
        $this->insertDB($this->database, $this->tbl, $param);
    }
    
    public function allforfilter(){
        $_fields = [$this->short . '.id', $this->short . '.name'];
        $where = [$this->short.'.status'=>1];
        if($this->database==='main'){
            return $this->getAll($this->database, $this->table, $_fields, $where);
        }        
        else{
            $data = array_merge($this->getAll($this->database, $this->table, $_fields, $where),$this->getAll('main', $this->table, $_fields, $where));
            return $data;
        }
    }

	public function allfortenants($course_category_id)
	{
		$mode = $this->input->get('mode');
		$_fields = [$this->short . '.id', $this->short . '.name'];
		$where = [$this->short.'.status'=>1];
		$_where = array_merge([$this->short . '.course_category_id' => $course_category_id],$where);
		if ($mode === 'add') {
			$data = $this->getAll($this->database, $this->table, $_fields, $_where);
		}else{
			return $this->getAll($this->input->get('tenantno'), $this->table, $_fields, [$this->short . '.status' => 1]);
		}
		return $data;
	}

    public function all($course_category_id = '',$fields=[])
    {
        $_fields =empty($fields)? [$this->short . '.id', $this->short . '.name']:$fields;
        $where = [$this->short.'.status'=>1];
        $_where = empty($course_category_id) ? $where : array_merge([$this->short . '.course_category_id' => $course_category_id],$where);
        $data = $this->getAll($this->database, $this->table, $_fields, $_where);
        return $data;
    }

    public function one($course_subcategory_id)
    {
        $fields = [$this->short . '.id', $this->short . '.course_category_id', $this->short . '.name', $this->short . '.status', $this->short . '.remark',"(Select Count(id) From ".$this->database_prefix.$this->database.'.'.$this->table_prefix."course where course_category_sub_id=$course_subcategory_id)  as inuse"];
        return $this->getOne($this->database, $this->table, $fields, $course_subcategory_id);
    }

    public function save($param, $id)
    {
        $this->saveDB($this->database, $this->tbl, $param, $id);
    }

    public function deleteMultiple($ids)
    {
        $this->deleteDB($this->database, $this->tbl, $ids, true);
    }

    public function deleteAll()
    {
        $this->deleteAllDB($this->database, $this->tbl);
    }

    public function getAllIds()
    {
        $ids = [];
        $all = $this->all();
        foreach ($all as $k => $v) {
            $ids[] = $v['id'];
        }
        return $ids;
    }
}
