<?php

namespace Hura8\Components\Order\Model;

use Hura8\Database\iConnectDB;

class OrderStatusModel
{

    /* @var  iConnectDB $db */
    protected $db;

    protected $tb_status         = 'tb_order_status';
    protected $tb_status_history = 'tb_order_status_history';

    public function __construct() {
        $this->db = get_db('', ENABLE_DB_DEBUG);
    }

    public function getStatusHistory($orderId){
        $query = $this->db->runQuery("
                                select * from ".$this->tb_status_history."
                                WHERE order_id = ?
                                order by id desc
                                limit 100
                            ", ['d'], [ $orderId ] ) ;

        return $this->db->fetchAll($query);
    }

    public function createHistory($order_id, $status_type = 'order', $system_status = '', $comment = '', array $data= [], array $other_info = []) {

        $info = $other_info;

        $info['order_id']       = $order_id;
        $info['status_type']    = $status_type;
        $info['system_status']  = $system_status;
        $info['data']           = \json_encode($data);
        $info['comment']        = substr($comment, 0, 150);
        $info['create_time']    = CURRENT_TIME;
        $info['create_by']      = (defined('ADMIN_NAME')) ? ADMIN_NAME : '';

        return $this->db->insert($this->tb_status_history, $info);
    }

    public function getCustomerCancelStatusId() {
        $info = $this->db->select($this->tb_status, ['id'], [
            "system_status" => ["=", "cancel"],
            'message' => 'Khách hàng hủy',
        ], '', 1);

        if($info) {
            return $info['id'];
        }

        // create and return
        return $this->create([
            'message' => 'Khách hàng hủy',
            'system_status' => "cancel",
            'create_time' => CURRENT_TIME,
            'create_by' => 'System',
        ]);
    }


    public function getInfo($status_id) {
        return $this->db->getItemInfo($this->tb_status, $status_id, 'id');
    }

    public function getAll() {
        $query = $this->db->runQuery(" select * from ".$this->tb_status." order by `id` desc ") ;
        $item_list = array();
        foreach ( $this->db->fetchAll($query) as $rs ) {
            if(!$rs['system_status']) $rs['system_status'] = 'new';
            //$rs['system_order_status'] = System::$ORDER_STATUS[$rs['system_status']];
            $item_list[] = $rs;
        }

        return $item_list;
    }

    public function delete($id) {
        return $this->db->runQuery("DELETE FROM ".$this->tb_status." WHERE `id` = ? limit 1 ", ['d'], [ $id ]) ;
    }

    public function update($id, array $info) {
        return $this->db->update($this->tb_status, $info, ['id' => $id]);
    }

    public function create(array $info) {
        return $this->db->insert($this->tb_status, $info);
    }

}
