<?php

use app\libraries\Tenants;

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

class Product_model extends MY_Model {

    use Tenants;

    public $short = "p";
    public $table;
    public $tbl;
//    public $database;

    public function __construct() {
        parent::__construct();
        $this->database = $this->getTenantNo();
        $this->tbl = 'product';
        $this->table = $this->tbl . ' ' . $this->short;
    }

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

        return $this->db->from('mas_product')->where('id', $id)->where('delete_time IS NULL', null, false)->get()->row_array();
    }

    public function detail_product($productId) {
        $this->tenant();
        $data = $this->db->from('mas_product p')
                ->select('p.id as pid,p.name,p.status,p.remark,p.product_category_id,format(pp.original_price,2) as original_price,format(pp.selling_price,2) as selling_price,pp.id as ppid')
                ->join('mas_product_price pp', 'p.id = pp.product_id')
                ->where('p.id', $productId)
                ->get()
                ->row_array();
//        foreach($data as $k=>$v){           
//            if($k==='original_price' || $k==='selling_price'){
//                $data[$k]=number_format($v,2,'.',',');
//                echo("data[$k]:". $data[$k].'<br>');
//            }
//        }
        return $data;
    }

    public function totalCount() {
        $db = $this->load->database($this->database, TRUE);
        $db->from($this->table_prefix . $this->table);
        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', $this->short . '.name', $this->short . '.status', 'pp.original_price', 'pp.selling_price', $this->short . '.create_time', $this->short . '.update_time', 'pc.name as category'];        
        $joins = [$this->table_prefix . 'product_price pp' => $this->short . '.id=pp.product_id', $this->table_prefix . 'product_category pc' => $this->short . '.product_category_id=pc.id'];
        $db = $this->load->database($this->database, TRUE);
        $db->select(implode(', ', $fields));
        $db->from($this->table_prefix . $this->table);
        if ($this->database == 'default') {
            $db->where(['tenant_no' => $this->session->userdata('tenant_no')]);
        }
        if (count($joins) > 0) {
            foreach ($joins as $joinTbl => $condition) {
                $db->join($joinTbl, $condition);
            }
        }
        $search = [];
        foreach ($param['columns'] as $column) {
            if ($column['searchable'] === "true" && !empty($column['search']['value'])) {
                $colName = str_replace(array('category'), array('pc.name'), $column['data']);
                $searchfield = ($colName === 'pc.name') ? $colName : $this->short . "." . $colName;
                $search[$searchfield] = $column['search']['value'];
            }
        }
        if (!empty($search)) {
            foreach ($search as $k => $v) {
                if ($v !== '') {                   
                    $db->like($search, 'none');
                }
            }
        }
        return count($db->get()->result_array());
    }

    public function listing($param) {
        $fields = [$this->short . '.id', $this->short . '.name', $this->short . '.status', 'pp.original_price', 'pp.selling_price', $this->short . '.create_time', $this->short . '.update_time', 'pc.name as category', 'pc.status as pcstatus'];
        $orders = [];
        foreach ($param['order'] as $order) {
            $colIdx = $order['column'];
            $colName = str_replace(array('category', 'original_price', 'selling_price'), array('pc.name', 'pp.original_price', 'pp.selling_price'), $param['columns'][$colIdx]['data']);
//            log_message('debug','colname:'.$colName);
            $dir = strtoupper($order['dir']);
            $orders[] = ($colName === 'pc.name' || $colName === 'pp.original_price' || $colName === 'pp.selling_price') ? $colName . ' ' . $dir : $this->short . "." . $colName . ' ' . $dir;
        }
//        log_message('debug',implode(',',$orders));
        $start = $param['start'];
        $length = $param['length'];
        $joins = [
            $this->table_prefix . 'product_price pp' => $this->short . '.id = pp.product_id',
            $this->table_prefix . 'product_category pc' => $this->short . '.product_category_id = pc.id'
        ];
        $search = [];
        foreach ($param['columns'] as $column) {
            if ($column['searchable'] === "true" && !empty($column['search']['value'])) {
                $colName = str_replace(array('category'), array('pc.name'), $column['data']);
                $searchfield = ($colName === 'pc.name') ? $colName : $this->short . "." . $colName;
                $search[$searchfield] = $column['search']['value'];
            }
        }
        $result = $this->getFromDBFilter($this->database, $this->table, $fields, $start, $length, $orders, $search, $joins, $this->short . '.name');
        $data = [];
        foreach ($result as $row) {
            $data[] = [
                'id' => trim($row['id']),
                'name' => trim($row['name']),
                'category' => $row['pcstatus']==0?'<span class="notinuse">'.$row['category'].'</span>': trim($row['category']),
                'original_price' => $this->asDollars(trim($row['original_price'])),
                'selling_price' => $this->asDollars(trim($row['selling_price'])),
                'create_time' => date("Y-m-d H:i:s", trim($row['create_time'])),
                'update_time' => date("Y-m-d H:i:s", trim($row['update_time'])),
                'status' => $this->status[$row['status']],
                'details' => '<button id="details-' . trim($row['id']) . '">詳情</button>',
                'delete' => '<input type="checkbox" class="checkbox-delete" id="' . trim($row['id']) . '" />',
            ];
        }
        return $data;
    }

    private function asDollars($value) {
        if ($value < 0)
            return "-" . asDollars(-$value);
        return 'HK$' . number_format($value, 2);
    }

    public function insert($param_p, $param_pp) {
        $tables = array($this->tbl, 'product_price');
        return $this->insertMultiDB($this->database, $tables, $param_p, $param_pp);
    }

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

    public function one($product_id) {
        $fields = [$this->short . '.id', $this->short . '.name', $this->short . '.status', $this->short . '.remark'];
        return $this->getOne($this->database, $this->table, $fields, $product_id);
    }

    public function save($params, $ids) {
        $this->saveDB($this->database, $this->tbl, $params[0], $ids[0]);
        $this->saveDB($this->database, 'product_price', $params[1], $ids[1]);
    }

    public function deleteMultiple($ids) {
        $this->deleteRelatedDB($this->database, array('product_price', $this->tbl), array('product_id', 'id'), $ids);
    }

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

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

    public function getCategories() {
        $this->load->model('Product_category_model');
        return $this->Product_category_model->all([$this->Product_category_model->short.'.status'=>1]);
    }

}
