<?php

require_once 'globals.php';

$goodsModel = new Goods_Model();
$Sort_Model = new Sort_Model();
$User_Model = new User_Model();
$Media_Model = new Media_Model();
$MediaSort_Model = new MediaSort_Model();
$Template_Model = new Template_Model();


if (empty($action)) {

    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $perpage_num = Option::get('admin_article_perpage_num');
    $start_limit = !empty($page) ? ($page - 1) * $perpage_num : 0;
    $limit = "LIMIT $start_limit, " . $perpage_num;

    $db = Database::getInstance();



    $sorts = $CACHE->readCache('sort');
    $sorts[] = [
        'sortname' => '未分类',
        'sid' => -1
    ];
    $category_json = [];
    foreach($sorts as $val){
        $category_json[] = [
            'text' => $val['sortname'],
            'value' => $val['sid']
        ];
    }
    $category_json[] = [
        'text' => '未分类',
        'value' => -1
    ];
    $category_json = json_encode($category_json);


    $br = '<a href="./">控制台</a><a href="./goods.php">商品管理</a><a><cite>商品列表</cite></a>';



    include View::getAdmView(User::haveEditPermission() ? 'header' : 'uc_header');
    require_once View::getAdmView('goods');
    include View::getAdmView(User::haveEditPermission() ? 'footer' : 'uc_footer');
    View::output();
}

if($action == 'index'){
    $draft = isset($_GET['draft']) ? (int)$_GET['draft'] : 0;
    $sid = isset($_GET['sid']) ? (int)$_GET['sid'] : '';
    $uid = isset($_GET['uid']) ? (int)$_GET['uid'] : '';
    $keyword = isset($_GET['keyword']) ? addslashes(trim($_GET['keyword'])) : '';
    $category_id = isset($_GET['category_id']) ? addslashes(trim($_GET['category_id'])) : 0;
    $page = isset($_GET['page']) ? (int)$_GET['page'] : 1;
    $perpage_num = Input::getIntVar('limit', 10);
//    $perpage_num = Option::get('admin_article_perpage_num');
    $start_limit = !empty($page) ? ($page - 1) * $perpage_num : 0;
    $limit = "LIMIT $start_limit, " . $perpage_num;

    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;

    $where = "";

    if(!empty($keyword)){
        $where .= " and title like '%{$keyword}%' ";
    }else{

    }
    if($category_id != 0){
        $where .= " and sort_id={$category_id} ";
    }

    $order_by = "ORDER BY ";
    $order_field = Input::getStrVar('field');
    $order_type = Input::getStrVar('order');
    if($order_field && $order_type){
        $order_by .= "{$order_field} $order_type, ";
    }
    $order_by .= " id desc";

    $sql = "SELECT id, cover, create_time, delete_time, index_top, is_on_shelf, is_sku, sales, sort_id, sort_top, stock, title, type FROM {$db_prefix}goods where delete_time is null {$where} {$order_by} $limit;";

    $sorts = $CACHE->readCache('sort');

    $res = $db->query($sql);
    $goods = [];
    while ($row = $db->fetch_array($res)) {
        $row['timestamp'] = $row['create_time'];
        $row['create_time'] = date("Y-m-d H:i", $row['create_time']);
        $row['title'] = !empty($row['title']) ? htmlspecialchars($row['title']) : '无标题';
        $row['type_text'] = goodsTypeText($row['type']);
        $row['stock'] = number_format($row['stock']);

        $sortName = isset($sorts[$row['sort_id']]['sortname']) ? $sorts[$row['sort_id']]['sortname'] : '未知分类';
        $row['sort_name'] = $row['sort_id'] == -1 ? '未分类' : $sortName;

        $goods[] = $row;
    }

    $res = $db->once_fetch_array("SELECT COUNT(*) AS total FROM " . DB_PREFIX . "goods g where g.delete_time is null {$where}");

    output::data($goods, $res['total']);
}


if($action == 'shelf'){
    $goods_id = Input::postIntVar('goods_id');
    $is_on_shelf = Input::postIntVar('status');
    $goodsModel->updateProduct(['is_on_shelf' => $is_on_shelf], $goods_id);
    output::ok();
}


if($action == 'delete'){
    $ids = Input::postStrVar('ids');
    d($ids);die;
    $sql = "DELETE FROM " . DB_PREFIX . "goods WHERE id IN ({$ids})";

    $db = Database::getInstance();
    $db->query($sql);
    output::ok();
}

if($action == 'del'){
    $ids = Input::postStrVar('ids');
    $ids = explode(',', $ids);
    foreach($ids as $goods_id){
        $goodsModel->deleteProduct($goods_id);
        doAction('del_product', $goods_id);
    }
    output::ok();
}

if ($action == 'del') {
    $id = Input::getIntVar('id');
    $isRm = Input::getIntVar('rm');

    LoginAuth::checkToken();
    if ($isRm) {

    } else {
        $goodsModel->hideSwitch($id, 'y');
    }
    $CACHE->updateCache();
    emDirect("./goods.php?&active_del=1");
}

if ($action == 'operate_goods') {
    $operate = Input::requestStrVar('operate');
    $draft = Input::postIntVar('draft');
    $logs = Input::postIntArray('blog');
    $sort = Input::postIntVar('sort');
    $author = Input::postIntVar('author');
    $id = Input::requestNumVar('id');

    LoginAuth::checkToken();

    if (!$operate) {
        emDirect("./goods.php?draft=$draft&error_b=1");
    }
    if (empty($logs) && empty($id)) {
        emDirect("./goods.php?draft=$draft&error_a=1");
    }

    switch ($operate) {
        case 'del':
            foreach ($logs as $val) {
                doAction('before_del_product', $val);
                $goodsModel->deleteProduct($val);
                doAction('del_product', $val);
            }
            $CACHE->updateCache();
            emDirect("./goods.php?draft=1&active_del=1&draft=$draft");
            break;
        case 'top':
            foreach ($logs as $val) {
                $goodsModel->updateLog(array('top' => 'y'), $val);
            }
            emDirect("./goods.php?active_up=1&draft=$draft");
            break;
        case 'sortop':
            foreach ($logs as $val) {
                $goodsModel->updateLog(array('sortop' => 'y'), $val);
            }
            emDirect("./goods.php?active_up=1&draft=$draft");
            break;
        case 'notop':
            foreach ($logs as $val) {
                $goodsModel->updateLog(array('top' => 'n', 'sortop' => 'n'), $val);
            }
            emDirect("./goods.php?active_down=1&draft=$draft");
            break;
        case 'hide':
            foreach ($logs as $val) {
                $goodsModel->hideSwitch($val, 'y');
            }
            $CACHE->updateCache();
            emDirect("./goods.php?active_hide=1&draft=$draft");
            break;
        case 'pub':
            foreach ($logs as $val) {
                $goodsModel->hideSwitch($val, 'n');
                if (User::haveEditPermission()) {
                    $goodsModel->checkSwitch($val, 'y');
                }
            }
            $CACHE->updateCache();
            emDirect("./goods.php?draft=1&active_post=1&draft=$draft");
            break;
        case 'move':
            foreach ($logs as $val) {
                $goodsModel->checkEditable($val);
                $goodsModel->updateLog(array('sortid' => $sort), $val);
            }
            $CACHE->updateCache(array('sort', 'logsort'));
            emDirect("./goods.php?active_move=1&draft=$draft");
            break;
        case 'change_author':
            if (!User::haveEditPermission()) {
                emMsg('权限不足！', './');
            }
            foreach ($logs as $val) {
                $goodsModel->updateLog(array('author' => $author), $val);
            }
            $CACHE->updateCache('sta');
            emDirect("./goods.php?active_change_author=1&draft=$draft");
            break;
        case 'check':
            if (!User::haveEditPermission()) {
                emMsg('权限不足！', './');
            }
            if ($logs) {
                foreach ($logs as $id) {
                    $goodsModel->checkSwitch($id, 'y');
                }
            } else {
                $goodsModel->checkSwitch($id, 'y');
            }
            $CACHE->updateCache();
            emDirect("./goods.php?active_ck=1&draft=$draft");
            break;
        case 'uncheck':
            if (!User::haveEditPermission()) {
                emMsg('权限不足！', './');
            }
            if ($logs) {
                $feedback = '';
                foreach ($logs as $id) {
                    $goodsModel->unCheck($id, $feedback);
                }
            } else {
                $id = Input::postIntVar('id');
                $feedback = Input::postStrVar('feedback');
                $goodsModel->unCheck($id, $feedback);
            }
            $CACHE->updateCache();
            emDirect("./goods.php?active_unck=1&draft=$draft");
            break;
    }
}

if ($action === 'release') {
    $goods = [
        'attr_id' => 0,
        'type' => 'duli',
        'is_sku' => 'n',
        'id'    => 0,
        'title'    => '',
        'content'  => '',
        'pay_content'  => '',
        'excerpt'  => '',
        'alias'    => '',
        'sort_id'   => -1,
        'password' => '',
        'hide'     => '',
        'author'   => UID,
        'cover'    => '',
        'link'     => '',
        'template' => '',
        'attach_user' => null,
        'is_on_shelf' => 1,
        'post_url' => '',
        'post_params' => '',
        'sales' => 0,
        'desc' => '',
        'index_top' => 'n',
        'sort_top' => 'n',
        'des' => '',
        'sort_num' => '',
        'goods_type_all' => [
//            ['name' => '一次性卡密（版本废弃）', 'value' => 'duli'],
//            ['name' => '固定通用卡密', 'value' => 'guding'],
//            ['name' => '虚拟服务类型', 'value' => 'xuni'],
//            ['name' => '自定义接口URL/POST', 'value' => 'post'],
        ]
    ];

    doMultiAction('adm_add_goods_goodsinfo', $goods, $goods);

    $sorts = $CACHE->readCache('sort');


    $memberModel = new Member_Model();
    $members = $memberModel->getMembersAll();


    $br = '<a href="./">控制台</a><a href="./goods.php">商品管理</a><a><cite>添加商品</cite></a>';

    include View::getAdmView('header');
    require_once(View::getAdmView('goods_release'));
    include View::getAdmView('footer');
    View::output();
}

if ($action === 'edit') {
    $goods_id = Input::getIntVar('id');

    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;

    $goodsModel->checkEditable($goods_id);
    $goods = $goodsModel->getOneGoodsForAdmin($goods_id);

    $goods['goods_type_all'] = [];
    doMultiAction('adm_add_goods_goodsinfo', $goods, $goods);


    $sql = "SELECT * FROM `{$db_prefix}discount` WHERE `goods_id` = {$goods['id']}";
    $discount = $db->fetch_all($sql);


    $sorts = $CACHE->readCache('sort');
    $mediaSorts = $MediaSort_Model->getSorts();

    $memberModel = new Member_Model();
    $members = $memberModel->getMembersAll();


    $br = '<a href="./">控制台</a><a href="./goods.php">商品管理</a><a><cite>编辑商品</cite></a>';

    include View::getAdmView(User::haveEditPermission() ? 'header' : 'uc_header');
    require_once(View::getAdmView('goods_release'));
    include View::getAdmView(User::haveEditPermission() ? 'footer' : 'uc_footer');
    View::output();
}

if ($action == 'upload_cover') {
    $ret = uploadCropImg();
    $Media_Model->addMedia($ret['file_info']);
    Output::ok($ret['file_info']['file_path']);
}


if($action == 'sku_data'){
    $goods_id = Input::getIntVar('goods_id', -1);
    if($goods_id < 0){
        die(json_encode(['code' => 200, 'data' => [], 'msg' => 'ok']));
    }
    $skus = $goodsModel->getGoodsSkusForAdmin($goods_id);
    die(json_encode(['code' => 200, 'data' => $skus, 'msg' => 'ok']));
    print_r($data);

}

/**
 * 获取商品类型
 */
if($action == 'goods_type_data'){

    $db = Database::getInstance();
    $db_prefix = DB_PREFIX;

    $sql = "SELECT id, name as title FROM `{$db_prefix}goods_type` where hide = 'n' and delete_time is null ORDER BY id DESC";

    $result = $db->query($sql);

    $data = [];

    while ($row = $db->fetch_array($result)) {
        $row['title'] = htmlspecialchars($row['title']);
        $data[] = $row;
    }

    die(json_encode(['code' => 200, 'data' => $data, 'msg' => 'ok']));
}

if($action == 'attr_spec_data'){


    $goods_type_id = Input::getIntVar('goods_type_id');

    $goods_id = Input::getIntVar('goods_id', -1);

    $db = Database::getInstance();
    $sql = "SELECT id, title FROM `" . DB_PREFIX . "sku_attr` where type_id='{$goods_type_id}' and delete_time is null ORDER BY id ASC";
    $result = $db->query($sql);
    $specification = [];

    while ($row = $db->fetch_array($result)) {
        $row['title'] = htmlspecialchars($row['title']);
        $specification[] = $row;
    }

    $sql = "SELECT * FROM `" . DB_PREFIX . "skus` where goods_id={$goods_id}";
    $result = $db->query($sql);
    $product_specification = [];
    while ($row = $db->fetch_array($result)) {
        $product_specification[] = $row;
    }

    if(!empty($specification)){
        $specification_ids = array_column($specification, 'id');
        $sql = "SELECT * FROM `" . DB_PREFIX . "sku_value` where attr_id in(" . implode(',', $specification_ids) . ") and delete_time is null ORDER BY id ASC";
        $result = $db->query($sql);
        $specification_value = [];
        while ($row = $db->fetch_array($result)) {
            $row['title'] = htmlspecialchars($row['name']);
            $specification_value[] = $row;
        }

        foreach($specification as $key => $val){
            $specification[$key]['options'] = [];
            $specification[$key]['value'] = [];
            foreach($specification_value as $v){
                foreach($product_specification as $vs){
                    $spec = explode('-', $vs['sku']);
                    if(in_array($v['id'], $spec)){
                        $specification[$key]['value'][] = $v['id'];
                    }
                }
                if($val['id'] == $v['attr_id']){
                    $specification[$key]['options'][] = [
                        'id' => $v['id'],
                        'title' => $v['title']
                    ];
                }
            }
        }
    }



    die(json_encode(['code' => 200, 'data' => [
        'attribute' => $specification,
        'spec' => $specification
    ], 'msg' => 'ok']));

}

/**
 * 创建规格
 */
if($action == 'create_spec'){

    $specification = Input::getStrVar('title');
    $goods_type_id = Input::getIntVar('goods_type_id');

    $kItem = ['type_id', 'title'];
    $dItem = [$goods_type_id, $specification];
    $field = implode(',', $kItem);
    $values = "'" . implode("','", $dItem) . "'";

    $db = Database::getInstance();

    $sql = "select COUNT(*) AS total from " . DB_PREFIX . "sku_attr where type_id='{$goods_type_id}' and title='{$specification}'";
    $is = $db->once_fetch_array($sql);
    if($is['total'] > 0){
        die(json_encode(['code' => 400, 'msg' => '规格已存在', 'data' => []]));
    }

    $sql = "INSERT INTO " . DB_PREFIX . "sku_attr ($field) VALUES ($values)";
    $db->query($sql);
    $specification_id = $db->insert_id();

    die(json_encode(['code' => 200, 'data' => [
        'id' => $specification_id
    ], 'msg' => 'ok']));


}

if($action == 'create_spec_value'){
    $name = Input::postStrVar('title');
    $specification_id = Input::getIntVar('spec_id');

    $kItem = ['specification_id', 'name'];
    $dItem = [$specification_id, $name];
    $field = implode(',', $kItem);
    $values = "'" . implode("','", $dItem) . "'";

    $db = Database::getInstance();

    $sql = "select COUNT(*) AS total from " . DB_PREFIX . "sku_value where attr_id='{$specification_id}' and name='{$name}'";
    $is = $db->once_fetch_array($sql);
    if($is['total'] > 0){
        die(json_encode(['code' => 400, 'msg' => '规格值已存在', 'data' => []]));
    }

    $sql = "INSERT INTO " . DB_PREFIX . "sku_value ($field) VALUES ($values)";
    $db->query($sql);
    $specification_value_id = $db->insert_id();

    die(json_encode(['code' => 200, 'data' => [
        'id' => $specification_value_id
    ], 'msg' => 'ok']));
}