<?php
define('IN_ECS', true);

require(dirname(__FILE__) . '/includes/init.php');
require_once(ROOT_PATH . '/' . ADMIN_PATH . '/includes/lib_homestay.php');
include_once(ROOT_PATH . '/includes/cls_image.php');
$image = new cls_image($_CFG['bgcolor']);
$exc = new exchange($ecs->table('hs_web'), $db, 'id', 'name');


if ($_REQUEST['act'] == 'edit') {
    include_once(ROOT_PATH . 'includes/fckeditor/fckeditor.php'); // 包含 html editor 類文件

    //    admin_priv('goods_manage'); // 檢查權限

    if (ini_get('safe_mode') == 1 && (!file_exists('../' . IMAGE_DIR . '/' . date('Ym')) || !is_dir('../' . IMAGE_DIR . '/' . date('Ym')))) {
        if (@!mkdir('../' . IMAGE_DIR . '/' . date('Ym'), 0777)) {
            $warning = sprintf($_LANG['safe_mode_warning'], '../' . IMAGE_DIR . '/' . date('Ym'));
            $smarty->assign('warning', $warning);
        }
    }

    /* 如果目錄存在但不可寫，提示用戶 */ elseif (file_exists('../' . IMAGE_DIR . '/' . date('Ym')) && file_mode_info('../' . IMAGE_DIR . '/' . date('Ym')) < 2) {
        $warning = sprintf($_LANG['not_writable_warning'], '../' . IMAGE_DIR . '/' . date('Ym'));
        $smarty->assign('warning', $warning);
    }

    /* 取得商品信息 */
    /* 商品信息 */
    $sql = "SELECT * FROM " . $ecs->table('hs_web') . " WHERE hs_id = '$_SESSION[user_id]'";
    $hs = $db->getRow($sql);

    if (empty($hs) === true) {
        /* 默認值 */
        $hs = array(
            'domain' => '',
            'cname' => ''
        );
    }


    /* 圖片列表 */
    $sql = "SELECT * FROM " . $ecs->table('hs_gallery') . " WHERE hs_id = '$_SESSION[user_id]'";
    $img_list = $db->getAll($sql);

    /* 格式化相冊圖片路徑 */
    if (isset($GLOBALS['shop_id']) && ($GLOBALS['shop_id'] > 0)) {
        foreach ($img_list as $key => $gallery_img) {
            $gallery_img[$key]['img_url'] = get_image_path($gallery_img['goods_id'], $gallery_img['img_original'], false, 'gallery');
            $gallery_img[$key]['thumb_url'] = get_image_path($gallery_img['goods_id'], $gallery_img['img_original'], true, 'gallery');
        }
    } else {
        foreach ($img_list as $key => $gallery_img) {
            $gallery_img[$key]['thumb_url'] = '../' . (empty($gallery_img['thumb_url']) ? $gallery_img['img_url'] : $gallery_img['thumb_url']);
        }
    }

    /* 模板賦值 */
    $smarty->assign('ur_here', '編輯內容');
    $smarty->assign('action_link', '');
    $smarty->assign('hs', $hs);
    $smarty->assign('fac_list', get_fac_list($hs['facility']));
    $smarty->assign('cfg', $_CFG);
    $smarty->assign('form_act', $is_add ? 'insert' : ($_REQUEST['act'] == 'edit' ? 'update' : 'insert'));
    $smarty->assign('img_list', $img_list);
    $smarty->assign('gd', gd_version());
    $smarty->assign('thumb_width', 200);
    $smarty->assign('thumb_height', 0);

    /* 顯示商品信息頁面 */
    assign_menu_info();
    assign_query_info();
    $smarty->display('hs_info.htm');
} elseif ($_REQUEST['act'] == 'update') {
    //    admin_priv('goods_manage'); // 檢查權限
    /* 檢查domain是否重複 */
    if ($_POST['domain']) {
        $sql = "SELECT COUNT(*) FROM " . $ecs->table('hs_web') .
            " WHERE domain = '$_POST[domain]' AND id <> '$_POST[id]'";

        if ($db->getOne($sql) > 0) {
            sys_msg('網域已存在', 1, array(), false);
        }
    }

    /* 檢查圖片：如果有錯誤，檢查尺寸是否超過最大值；否則，檢查文件類型 */
    if (isset($_FILES['index_banner']['error'])) // php 4.2 版本才支持 error
    {
        // 最大上傳文件大小
        $php_maxsize = ini_get('upload_max_filesize');
        $htm_maxsize = '20M';

        // 商品圖片
        if ($_FILES['index_banner']['error'] == 0) {
            if (!$image->check_img_type($_FILES['index_banner']['type'])) {
                sys_msg('圖片格式錯誤', 1, array(), false);
            }
        } elseif ($_FILES['index_banner']['error'] == 1) {
            sys_msg(sprintf($_LANG['goods_img_too_big'], $php_maxsize), 1, array(), false);
        } elseif ($_FILES['index_banner']['error'] == 2) {
            sys_msg(sprintf($_LANG['goods_img_too_big'], $htm_maxsize), 1, array(), false);
        }

        // 相冊圖片 - 功能保留
        foreach ($_FILES['img_url']['error'] as $key => $value) {
            if ($value == 0) {
                if (!$image->check_img_type($_FILES['img_url']['type'][$key])) {
                    sys_msg(sprintf($_LANG['invalid_img_url'], $key + 1), 1, array(), false);
                }
            } elseif ($value == 1) {
                sys_msg(sprintf($_LANG['img_url_too_big'], $key + 1, $php_maxsize), 1, array(), false);
            } elseif ($_FILES['img_url']['error'] == 2) {
                sys_msg(sprintf($_LANG['img_url_too_big'], $key + 1, $htm_maxsize), 1, array(), false);
            }
        }
    }
    /* 4.1版本 */ else {
        // 商品圖片
        if ($_FILES['index_banner']['tmp_name'] != 'none') {
            if (!$image->check_img_type($_FILES['index_banner']['type'])) {

                sys_msg($_LANG['invalid_goods_img'], 1, array(), false);
            }
        }

        // 相冊圖片
        foreach ($_FILES['img_url']['tmp_name'] as $key => $value) {
            if ($value != 'none') {
                if (!$image->check_img_type($_FILES['img_url']['type'][$key])) {
                    sys_msg(sprintf($_LANG['invalid_img_url'], $key + 1), 1, array(), false);
                }
            }
        }
    }

    /* 處理商品圖片 */
    $index_banner        = '';  // 初始化商品圖片
    $old_index_banner = '';  // 初始化原始圖片舊圖


    // 如果上傳了商品圖片，相應處理
    if (($_FILES['index_banner']['tmp_name'] != '' && $_FILES['index_banner']['tmp_name'] != 'none')) {
        if ($_REQUEST['id'] > 0) {
            /* 刪除原來的圖片文件 */
            $sql = "SELECT index_banner " .
                " FROM " . $ecs->table('hs_web') .
                " WHERE id = '$_REQUEST[id]'";
            $row = $db->getRow($sql);
            if ($row['index_banner'] != '' && is_file('../' . $row['index_banner'])) {
                @unlink('../' . $row['index_banner']);
            }
            if ($row['original_img'] != '' && is_file('../' . $row['original_img'])) {
                /* 先不處理，以防止程序中途出錯停止 */
                //$old_original_img = $row['original_img']; //記錄舊圖路徑
            }
            /* 清除原來商品圖片 */
            if ($proc_thumb === false) {
                //                get_image_path($_REQUEST[goods_id], $row['goods_img'], false, 'goods', true);
                //                get_image_path($_REQUEST[goods_id], $row['goods_thumb'], true, 'goods', true);
            }

            $original_img   = $image->upload_image($_FILES['index_banner']); // 原始圖片
            if ($original_img === false) {
                sys_msg($image->error_msg(), 1, array(), false);
            }
            $index_banner  = $original_img;   // 商品圖片

        }
    }

    if (isset($_FILES['logo']) && $_FILES['logo']['tmp_name'] != '') {
        $logo = $image->upload_image($_FILES['logo']);
        if ($slogo === false) {
            sys_msg($image->error_msg(), 1, array(), false);
        }
    }
    if (isset($_FILES['slogo']) && $_FILES['slogo']['tmp_name'] != '') {
        $slogo = $image->upload_image($_FILES['slogo']);
        if ($slogo === false) {
            sys_msg($image->error_msg(), 1, array(), false);
        }
    }
    if (isset($_FILES['inbanner']) && $_FILES['inbanner']['tmp_name'] != '') {
        $inbanner = $image->upload_image($_FILES['inbanner']);
        if ($inbanner === false) {
            sys_msg($image->error_msg(), 1, array(), false);
        }
    }
    if (isset($_FILES['about_image']) && $_FILES['about_image']['tmp_name'] != '') {
        $about_image = $image->upload_image($_FILES['about_image']);
        if ($about_image === false) {
            sys_msg($image->error_msg(), 1, array(), false);
        }
    }

    /* 處理數據 */
    $fac = '0';
    if (is_array($_POST['fac'])) {
        foreach ($_POST['fac'] as $val) {
            $fac .= ',' . $val;
        }
    }
    $cf = $db->getRow("SELECT domain,cf_iden FROM " . $ecs->table('hs_web') . "WHERE id=" . $_REQUEST['id']);
    if (strlen($cf['domain'])) {
        if ($cf['domain'] != $_POST['domain']) {
            /* 更新domain */
            if (strlen($_POST['domain'])) {
                if (strpos($_POST['domain'], $_CFG['cf_domain']) !== false) {
                    $sub_domain = str_replace($_CFG['cf_domain'], '', $_POST['domain']);
                    // sub_domain是為.結束,是的話就去掉
                    if (substr($sub_domain, -1) == '.') {
                        $sub_domain = substr($sub_domain, 0, -1);
                    }
                    include_once(ROOT_PATH . 'back/includes/cls_cloudflare.php');
                    $cf_obj = new cloudflare;
                    $ret = $cf_obj->update_domain($cf['cf_iden'], trim($sub_domain));
                    if (!$ret) {
                        sys_msg('網域自動修改失敗,請重新操作',1, array(), false);
                        // $cf_iden = 0;
                    } else {
                        $cf_iden = $ad_ret;
                    }
                }
            }
        }
    } else {
        if (strlen($_REQUEST['domain'])) {
            if (strpos($_REQUEST['domain'], $_CFG['cf_domain']) !== false) {
                $sub_domain = str_replace($_CFG['cf_domain'], '', $_REQUEST['domain']);
                // sub_domain是為.結束,是的話就去掉
                if (substr($sub_domain, -1) == '.') {
                    $sub_domain = substr($sub_domain, 0, -1);
                }
                include_once(ROOT_PATH . 'back/includes/cls_cloudflare.php');
                $cf_obj = new cloudflare;
                $ad_ret = $cf_obj->add_domain(trim($sub_domain));
                if (!$ad_ret) {
                    sys_msg('網域自動新增失敗,請重新操作',1, array(), false);			
                    // $cf_iden = 0;
                } else {
                    $cf_iden = $ad_ret;
                }
            }
        } else {
            exit;
        }
    }
    /* 入庫 */
    if ($is_insert) {
        $sql = "INSERT INTO " . $ecs->table('hs_web') . " (domain, cname, ename, " .
            "tel,email,address,facebook,line, banner_text,slogon,index_banner,index_ytb,vrmap,vrmap2,location_map, " .
            "location_desc,about_us,mdesc,mkeyword,image1,image2,image3,facility,rm_fac," .
            " cstamp, ustamp)" .
            "VALUES ('$_POST[domain]', '$_POST[cname]','$_POST[ename]', " .
            "'$_POST[tel]','$_POST[email]','$_POST[address]','$_POST[facebook]','$_POST[line]','$_POST[banner_text]','$_POST[slogon]','$_POST[index_banner]','$_POST[index_ytb]','$_POST[vrmap]','$_POST[vrmap2]','$_POST[location_map]'," .
            "'$_POST[location_desc]','$_POST[about_us]','$_POST[mdesc]','$_POST[mkeyword]','$_POST[image1]','$_POST[image2]','$_POST[image3]','$fac','$_POST[rm_fac]'," .
            " '" . gmtime() . "', '" . gmtime() . "')";
    } else {
        /* 如果有上傳圖片，刪除原來的商品圖 */
        //        $sql = "SELECT index_banner " .
        //                    " FROM " . $ecs->table('hs_web') .
        //                    " WHERE id = '$_REQUEST[id]'";
        //        $row = $db->getRow($sql);
        //        if ($row['index_banner'])
        //        {
        //            @unlink(ROOT_PATH . $row['index_banner']);
        //        }

        $sql = "UPDATE " . $ecs->table('hs_web') . " SET " .
            "cname = '$_POST[cname]', " .
            "ename = '$_POST[ename]', " .
            "domain = '$_POST[domain]', " .
            "tel = '$_POST[tel]', " .
            "email = '$_POST[email]', " .
            "address = '$_POST[address]', " .
            "facebook = '$_POST[facebook]', " .
            "line = '$_POST[line]', " .
            "slogon = '$_POST[slogon]', " .
            "index_ytb = '$_POST[index_ytb]', " .
            "vrmap = '$_POST[vrmap]', " .
            "vrmap2 = '$_POST[vrmap2]', " .
            "facebook = '$_POST[facebook]', " .
            "banner_text = '$_POST[banner_text]', " .
            "aboutus = '$_POST[aboutus]', " .
            "facility = '$fac', " .
            "location_desc = '$_POST[location_desc]', " .
            "location_map = '$_POST[location_map]', ";

        /* 如果有上傳圖片，需要更新數據庫 */
        if ($index_banner) {
            $sql .= "index_banner = '$index_banner', ";
        }
        if ($logo) {
            $sql .= "logo = '$logo', ";
        }
        if ($slogo) {
            $sql .= "slogo = '$slogo', ";
        }
        if ($inbanner) {
            $sql .= "inbanner = '$inbanner', ";
        }
        if ($about_image) {
            $sql .= "about_image = '$about_image', ";
        }
        if (strlen($cf_iden) > 0) {
            $sql .= "cf_iden = '$cf_iden', ";
        }
        $sql .= "mdesc = '$_POST[mdesc]', " .
            "mkeyword = '$_POST[mkeyword]', " .
            "ustamp = '" . gmtime() . "' " .
            "WHERE id = '$_REQUEST[id]' LIMIT 1";
    }
    $db->query($sql);

    /* 商品編號 */
    $id = $is_insert ? $db->insert_id() : $_REQUEST['id'];

    /* 記錄日誌 */
    if ($is_insert) {
        //admin_log($_POST['goods_name'], 'add', 'goods');
    } else {
        //admin_log($_POST['goods_name'], 'edit', 'goods');
    }

    handle_gallery_image($_SESSION['user_id'], $_FILES['img_url'], $_POST['img_desc']);

    if (!$is_insert && isset($_POST['old_img_desc'])) {
        foreach ($_POST['old_img_desc'] as $img_id => $img_desc) {
            $sql = "UPDATE " . $ecs->table('hs_gallery') . " SET img_desc = '$img_desc' WHERE img_id = '$img_id' LIMIT 1";
            $db->query($sql);
        }
    }

    /* 不保留商品原圖的時候刪除原圖 */
    //    if ($proc_thumb && !$_CFG['retain_original_img'] && !empty($original_img))
    //    {
    //        $db->query("UPDATE " . $ecs->table('goods') . " SET original_img='' WHERE `goods_id`='{$goods_id}'");
    //        $db->query("UPDATE " . $ecs->table('goods_gallery') . " SET img_original='' WHERE `goods_id`='{$goods_id}'");
    //        @unlink('../' . $original_img);
    //        @unlink('../' . $img);
    //    }

    /* 清空緩存 */
    clear_cache_files();

    if ($is_insert) {
        $link[0] = add_link();
    }
    $link[1] = list_link($is_insert);


    //$key_array = array_keys($link);
    for ($i = 0; $i < count($link); $i++) {
        $key_array[] = $i;
    }
    krsort($link);
    $link = array_combine($key_array, $link);


    if ($cf_iden > 0) {
        sys_msg('更新成功', 0, $link);
    } else {
        sys_msg('更新成功,但網域自動修改失敗,請手動至CF操作', 1, array(), false);
    }
}

/*------------------------------------------------------ */
//-- 批量操作
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'batch') {
    $code = empty($_REQUEST['extension_code']) ? '' : trim($_REQUEST['extension_code']);

    /* 取得要操作的商品編號 */
    $goods_id = !empty($_POST['checkboxes']) ? join(',', $_POST['checkboxes']) : 0;

    if (isset($_POST['type'])) {
        /* 放入回收站 */
        if ($_POST['type'] == 'trash') {
            /* 檢查權限 */
            admin_priv('remove_back');

            update_goods($goods_id, 'is_delete', '1');

            /* 記錄日誌 */
            admin_log('', 'batch_trash', 'goods');
        }
        /* 上架 */ elseif ($_POST['type'] == 'on_sale') {
            /* 檢查權限 */
            admin_priv('goods_manage');
            update_goods($goods_id, 'is_on_sale', '1');
        }

        /* 下架 */ elseif ($_POST['type'] == 'not_on_sale') {
            /* 檢查權限 */
            admin_priv('goods_manage');
            update_goods($goods_id, 'is_on_sale', '0');
        }

        /* 設為精品 */ elseif ($_POST['type'] == 'best') {
            /* 檢查權限 */
            admin_priv('goods_manage');
            update_goods($goods_id, 'is_best', '1');
        }

        /* 取消精品 */ elseif ($_POST['type'] == 'not_best') {
            /* 檢查權限 */
            admin_priv('goods_manage');
            update_goods($goods_id, 'is_best', '0');
        }

        /* 設為新品 */ elseif ($_POST['type'] == 'new') {
            /* 檢查權限 */
            admin_priv('goods_manage');
            update_goods($goods_id, 'is_new', '1');
        }

        /* 取消新品 */ elseif ($_POST['type'] == 'not_new') {
            /* 檢查權限 */
            admin_priv('goods_manage');
            update_goods($goods_id, 'is_new', '0');
        }

        /* 設為熱銷 */ elseif ($_POST['type'] == 'hot') {
            /* 檢查權限 */
            admin_priv('goods_manage');
            update_goods($goods_id, 'is_hot', '1');
        }

        /* 取消熱銷 */ elseif ($_POST['type'] == 'not_hot') {
            /* 檢查權限 */
            admin_priv('goods_manage');
            update_goods($goods_id, 'is_hot', '0');
        }

        /* 轉移到分類 */ elseif ($_POST['type'] == 'move_to') {
            /* 檢查權限 */
            admin_priv('goods_manage');
            update_goods($goods_id, 'cat_id', $_POST['target_cat']);
        }

        /* 轉移到供貨商 */ elseif ($_POST['type'] == 'suppliers_move_to') {
            /* 檢查權限 */
            admin_priv('goods_manage');
            update_goods($goods_id, 'suppliers_id', $_POST['suppliers_id']);
        }

        /* 還原 */ elseif ($_POST['type'] == 'restore') {
            /* 檢查權限 */
            admin_priv('remove_back');

            update_goods($goods_id, 'is_delete', '0');

            /* 記錄日誌 */
            admin_log('', 'batch_restore', 'goods');
        }
        /* 刪除 */ elseif ($_POST['type'] == 'drop') {
            /* 檢查權限 */
            admin_priv('remove_back');

            delete_goods($goods_id);

            /* 記錄日誌 */
            admin_log('', 'batch_remove', 'goods');
        }
    }

    /* 清除緩存 */
    clear_cache_files();

    if ($_POST['type'] == 'drop' || $_POST['type'] == 'restore') {
        $link[] = array('href' => 'goods.php?act=trash', 'text' => $_LANG['11_goods_trash']);
    } else {
        $link[] = list_link(true, $code);
    }
    sys_msg($_LANG['batch_handle_ok'], 0, $link);
}

/*------------------------------------------------------ */
//-- 顯示圖片
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'show_image') {

    //    $img_url = $_GET['img_url'];
    $img_url = '../' . $_GET['img_url'];
    $smarty->assign('img_url', $img_url);
    $smarty->display('show_image.htm');
}

/*------------------------------------------------------ */
//-- 修改商品名稱
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'edit_goods_name') {
    check_authz_json('goods_manage');

    $goods_id   = intval($_POST['id']);
    $goods_name = json_str_iconv(trim($_POST['val']));

    if ($exc->edit("goods_name = '$goods_name', last_update=" . gmtime(), $goods_id)) {
        clear_cache_files();
        make_json_result(stripslashes($goods_name));
    }
}

/*------------------------------------------------------ */
//-- 修改商品貨號
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'edit_goods_sn') {
    check_authz_json('goods_manage');

    $goods_id = intval($_POST['id']);
    $goods_sn = json_str_iconv(trim($_POST['val']));

    /* 檢查是否重複 */
    if (!$exc->is_only('goods_sn', $goods_sn, $goods_id)) {
        make_json_error($_LANG['goods_sn_exists']);
    }
    if ($exc->edit("goods_sn = '$goods_sn', last_update=" . gmtime(), $goods_id)) {
        clear_cache_files();
        make_json_result(stripslashes($goods_sn));
    }
} elseif ($_REQUEST['act'] == 'check_goods_sn') {
    check_authz_json('goods_manage');

    $goods_id = intval($_REQUEST['goods_id']);
    $goods_sn = htmlspecialchars(json_str_iconv(trim($_REQUEST['goods_sn'])));

    /* 檢查是否重複 */
    if (!$exc->is_only('goods_sn', $goods_sn, $goods_id)) {
        make_json_error($_LANG['goods_sn_exists']);
    }
    make_json_result('');
} elseif ($_REQUEST['act'] == 'check_products_goods_sn') {
    check_authz_json('goods_manage');

    $goods_id = intval($_REQUEST['goods_id']);
    $goods_sn = json_str_iconv(trim($_REQUEST['goods_sn']));
    $products_sn = explode('||', $goods_sn);
    if (!is_array($products_sn)) {
        make_json_result('');
    } else {
        foreach ($products_sn as $val) {
            if (empty($val)) {
                continue;
            }
            if (is_array($int_arry)) {
                if (in_array($val, $int_arry)) {
                    make_json_error($val . $_LANG['goods_sn_exists']);
                }
            }
            $int_arry[] = $val;
            if (!$exc->is_only('goods_sn', $val, '0')) {
                make_json_error($val . $_LANG['goods_sn_exists']);
            }
        }
    }
    /* 檢查是否重複 */
    make_json_result('');
}

/*------------------------------------------------------ */
//-- 修改商品價格
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'edit_goods_price') {
    check_authz_json('goods_manage');

    $goods_id       = intval($_POST['id']);
    $goods_price    = floatval($_POST['val']);

    if ($goods_price < 0 || $goods_price == 0 && $_POST['val'] != "$goods_price") {
        make_json_error($_LANG['shop_price_invalid']);
    } else {
        if ($exc->edit("shop_price = '$goods_price', last_update=" . gmtime(), $goods_id)) {
            clear_cache_files();
            make_json_result(number_format($goods_price, 0, '.', ''));
        }
    }
}

/*------------------------------------------------------ */
//-- 修改商品庫存數量
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'edit_goods_number') {
    check_authz_json('goods_manage');

    $goods_id   = intval($_POST['id']);
    $goods_num  = intval($_POST['val']);

    if ($goods_num < 0 || $goods_num == 0 && $_POST['val'] != "$goods_num") {
        make_json_error($_LANG['goods_number_error']);
    }

    if (check_goods_product_exist($goods_id) == 1) {
        make_json_error($_LANG['sys']['wrong'] . $_LANG['cannot_goods_number']);
    }

    if ($exc->edit("goods_number = '$goods_num', last_update=" . gmtime(), $goods_id)) {
        clear_cache_files();
        make_json_result($goods_num);
    }
}

/*------------------------------------------------------ */
//-- 修改上架狀態
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'toggle_on_sale') {
    check_authz_json('goods_manage');

    $goods_id       = intval($_POST['id']);
    $on_sale        = intval($_POST['val']);

    if ($exc->edit("is_on_sale = '$on_sale', last_update=" . gmtime(), $goods_id)) {
        clear_cache_files();
        make_json_result($on_sale);
    }
}

/*------------------------------------------------------ */
//-- 修改精品推薦狀態
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'toggle_best') {
    check_authz_json('goods_manage');

    $goods_id       = intval($_POST['id']);
    $is_best        = intval($_POST['val']);

    if ($exc->edit("is_best = '$is_best', last_update=" . gmtime(), $goods_id)) {
        clear_cache_files();
        make_json_result($is_best);
    }
}

/*------------------------------------------------------ */
//-- 修改新品推薦狀態
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'toggle_new') {
    check_authz_json('goods_manage');

    $goods_id       = intval($_POST['id']);
    $is_new         = intval($_POST['val']);

    if ($exc->edit("is_new = '$is_new', last_update=" . gmtime(), $goods_id)) {
        clear_cache_files();
        make_json_result($is_new);
    }
}

/*------------------------------------------------------ */
//-- 修改熱銷推薦狀態
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'toggle_hot') {
    check_authz_json('goods_manage');

    $goods_id       = intval($_POST['id']);
    $is_hot         = intval($_POST['val']);

    if ($exc->edit("is_hot = '$is_hot', last_update=" . gmtime(), $goods_id)) {
        clear_cache_files();
        make_json_result($is_hot);
    }
}

/*------------------------------------------------------ */
//-- 修改商品排序
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'edit_sort_order') {
    check_authz_json('goods_manage');

    $goods_id       = intval($_POST['id']);
    $sort_order     = intval($_POST['val']);

    if ($exc->edit("sort_order = '$sort_order', last_update=" . gmtime(), $goods_id)) {
        clear_cache_files();
        make_json_result($sort_order);
    }
}

/*------------------------------------------------------ */
//-- 排序、分頁、查詢
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'query') {
    $is_delete = empty($_REQUEST['is_delete']) ? 0 : intval($_REQUEST['is_delete']);
    $code = empty($_REQUEST['extension_code']) ? '' : trim($_REQUEST['extension_code']);
    $goods_list = goods_list($is_delete, ($code == '') ? 1 : 0);


    $smarty->assign('code',         $code);
    $smarty->assign('goods_list',   $goods_list['goods']);
    $smarty->assign('filter',       $goods_list['filter']);
    $smarty->assign('record_count', $goods_list['record_count']);
    $smarty->assign('page_count',   $goods_list['page_count']);
    $smarty->assign('list_type',    $is_delete ? 'trash' : 'goods');
    $smarty->assign('use_storage',  empty($_CFG['use_storage']) ? 0 : 1);

    /* 排序標記 */
    $sort_flag  = sort_flag($goods_list['filter']);
    $smarty->assign($sort_flag['tag'], $sort_flag['img']);

    /* 獲取商品類型存在規格的類型 */

    $tpl = $is_delete ? 'goods_trash.htm' : 'goods_list.htm';

    make_json_result(
        $smarty->fetch($tpl),
        '',
        array('filter' => $goods_list['filter'], 'page_count' => $goods_list['page_count'])
    );
}

/*------------------------------------------------------ */
//-- 放入回收站
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'remove') {
    $goods_id = intval($_REQUEST['id']);

    /* 檢查權限 */
    check_authz_json('remove_back');

    if ($exc->edit("is_delete = 1", $goods_id)) {
        clear_cache_files();
        $goods_name = $exc->get_name($goods_id);

        admin_log(addslashes($goods_name), 'trash', 'goods'); // 記錄日誌

        $url = 'goods.php?act=query&' . str_replace('act=remove', '', $_SERVER['QUERY_STRING']);

        ecs_header("Location: $url\n");
        exit;
    }
}

/*------------------------------------------------------ */
//-- 還原回收站中的商品
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'restore_goods') {
    $goods_id = intval($_REQUEST['id']);

    check_authz_json('remove_back'); // 檢查權限

    $exc->edit("is_delete = 0, add_time = '" . gmtime() . "'", $goods_id);
    clear_cache_files();

    $goods_name = $exc->get_name($goods_id);

    admin_log(addslashes($goods_name), 'restore', 'goods'); // 記錄日誌

    $url = 'goods.php?act=query&' . str_replace('act=restore_goods', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");
    exit;
}

/*------------------------------------------------------ */
//-- 徹底刪除商品
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'drop_goods') {
    // 檢查權限
    check_authz_json('remove_back');

    // 取得參數
    $goods_id = intval($_REQUEST['id']);
    if ($goods_id <= 0) {
        make_json_error('invalid params');
    }

    /* 取得商品信息 */
    $sql = "SELECT goods_id, goods_name, is_delete, is_real, goods_thumb, " .
        "goods_img, original_img " .
        "FROM " . $ecs->table('goods') .
        " WHERE goods_id = '$goods_id'";
    $goods = $db->getRow($sql);
    if (empty($goods)) {
        make_json_error($_LANG['goods_not_exist']);
    }

    if ($goods['is_delete'] != 1) {
        make_json_error($_LANG['goods_not_in_recycle_bin']);
    }

    /* 刪除商品圖片和輪播圖片 */
    if (!empty($goods['goods_thumb'])) {
        @unlink('../' . $goods['goods_thumb']);
    }
    if (!empty($goods['goods_img'])) {
        @unlink('../' . $goods['goods_img']);
    }
    if (!empty($goods['original_img'])) {
        @unlink('../' . $goods['original_img']);
    }
    /* 刪除商品 */
    $exc->drop($goods_id);


    /* 記錄日誌 */
    admin_log(addslashes($goods['goods_name']), 'remove', 'goods');

    /* 刪除商品相冊 */
    $sql = "SELECT img_url, thumb_url, img_original " .
        "FROM " . $ecs->table('goods_gallery') .
        " WHERE goods_id = '$goods_id'";
    $res = $db->query($sql);
    while ($row = $db->fetchRow($res)) {
        if (!empty($row['img_url'])) {
            @unlink('../' . $row['img_url']);
        }
        if (!empty($row['thumb_url'])) {
            @unlink('../' . $row['thumb_url']);
        }
        if (!empty($row['img_original'])) {
            @unlink('../' . $row['img_original']);
        }
    }

    $sql = "DELETE FROM " . $ecs->table('goods_gallery') . " WHERE goods_id = '$goods_id'";
    $db->query($sql);

    /* 刪除相關表記錄 */
    $sql = "DELETE FROM " . $ecs->table('collect_goods') . " WHERE goods_id = '$goods_id'";
    $db->query($sql);
    $sql = "DELETE FROM " . $ecs->table('goods_article') . " WHERE goods_id = '$goods_id'";
    $db->query($sql);
    $sql = "DELETE FROM " . $ecs->table('goods_attr') . " WHERE goods_id = '$goods_id'";
    $db->query($sql);
    $sql = "DELETE FROM " . $ecs->table('goods_cat') . " WHERE goods_id = '$goods_id'";
    $db->query($sql);
    $sql = "DELETE FROM " . $ecs->table('member_price') . " WHERE goods_id = '$goods_id'";
    $db->query($sql);
    $sql = "DELETE FROM " . $ecs->table('group_goods') . " WHERE parent_id = '$goods_id'";
    $db->query($sql);
    $sql = "DELETE FROM " . $ecs->table('group_goods') . " WHERE goods_id = '$goods_id'";
    $db->query($sql);
    $sql = "DELETE FROM " . $ecs->table('link_goods') . " WHERE goods_id = '$goods_id'";
    $db->query($sql);
    $sql = "DELETE FROM " . $ecs->table('link_goods') . " WHERE link_goods_id = '$goods_id'";
    $db->query($sql);
    $sql = "DELETE FROM " . $ecs->table('tag') . " WHERE goods_id = '$goods_id'";
    $db->query($sql);
    $sql = "DELETE FROM " . $ecs->table('comment') . " WHERE comment_type = 0 AND id_value = '$goods_id'";
    $db->query($sql);
    $sql = "DELETE FROM " . $ecs->table('collect_goods') . " WHERE goods_id = '$goods_id'";
    $db->query($sql);
    $sql = "DELETE FROM " . $ecs->table('booking_goods') . " WHERE goods_id = '$goods_id'";
    $db->query($sql);
    $sql = "DELETE FROM " . $ecs->table('goods_activity') . " WHERE goods_id = '$goods_id'";
    $db->query($sql);

    /* 如果不是實體商品，刪除相應虛擬商品記錄 */
    if ($goods['is_real'] != 1) {
        $sql = "DELETE FROM " . $ecs->table('virtual_card') . " WHERE goods_id = '$goods_id'";
        if (!$db->query($sql, 'SILENT') && $db->errno() != 1146) {
            die($db->error());
        }
    }

    clear_cache_files();
    $url = 'goods.php?act=query&' . str_replace('act=drop_goods', '', $_SERVER['QUERY_STRING']);

    ecs_header("Location: $url\n");

    exit;
}

/*------------------------------------------------------ */
//-- 切換商品類型
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'get_attr') {
    check_authz_json('goods_manage');

    $goods_id   = empty($_GET['goods_id']) ? 0 : intval($_GET['goods_id']);
    $goods_type = empty($_GET['goods_type']) ? 0 : intval($_GET['goods_type']);

    $content    = build_attr_html($goods_type, $goods_id);

    make_json_result($content);
}

/*------------------------------------------------------ */
//-- 刪除圖片
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'drop_image') {
    //    check_authz_json('goods_manage');

    $img_id = empty($_REQUEST['img_id']) ? 0 : intval($_REQUEST['img_id']);

    /* 刪除圖片文件 */
    $sql = "SELECT img_url, thumb_url, img_original " .
        " FROM " . $GLOBALS['ecs']->table('hs_gallery') .
        " WHERE img_id = '$img_id'";
    $row = $GLOBALS['db']->getRow($sql);

    if ($row['img_url'] != '' && is_file('../' . $row['img_url'])) {
        @unlink('../' . $row['img_url']);
    }
    if ($row['thumb_url'] != '' && is_file('../' . $row['thumb_url'])) {
        @unlink('../' . $row['thumb_url']);
    }
    if ($row['img_original'] != '' && is_file('../' . $row['img_original'])) {
        @unlink('../' . $row['img_original']);
    }

    /* 刪除數據 */
    $sql = "DELETE FROM " . $GLOBALS['ecs']->table('hs_gallery') . " WHERE img_id = '$img_id' LIMIT 1";
    $GLOBALS['db']->query($sql);

    clear_cache_files();
    make_json_result($img_id);
}

/*------------------------------------------------------ */
//-- 搜索商品，僅返回名稱及ID
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'get_goods_list') {
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    $filters = $json->decode($_GET['JSON']);

    $arr = get_goods_list($filters);
    $opt = array();

    foreach ($arr as $key => $val) {
        $opt[] = array(
            'value' => $val['goods_id'],
            'text' => $val['goods_name'],
            'data' => $val['shop_price']
        );
    }

    make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 把商品加入關聯
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'add_link_goods') {
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    check_authz_json('goods_manage');

    $linked_array   = $json->decode($_GET['add_ids']);
    $linked_goods   = $json->decode($_GET['JSON']);
    $goods_id       = $linked_goods[0];
    $is_double      = $linked_goods[1] == true ? 0 : 1;

    foreach ($linked_array as $val) {
        if ($is_double) {
            /* 雙向關聯 */
            $sql = "INSERT INTO " . $ecs->table('link_goods') . " (goods_id, link_goods_id, is_double, admin_id) " .
                "VALUES ('$val', '$goods_id', '$is_double', '$_SESSION[admin_id]')";
            $db->query($sql, 'SILENT');
        }

        $sql = "INSERT INTO " . $ecs->table('link_goods') . " (goods_id, link_goods_id, is_double, admin_id) " .
            "VALUES ('$goods_id', '$val', '$is_double', '$_SESSION[admin_id]')";
        $db->query($sql, 'SILENT');
    }

    $linked_goods   = get_linked_goods($goods_id);
    $options        = array();

    foreach ($linked_goods as $val) {
        $options[] = array(
            'value'  => $val['goods_id'],
            'text'      => $val['goods_name'],
            'data'      => ''
        );
    }

    clear_cache_files();
    make_json_result($options);
}

/*------------------------------------------------------ */
//-- 刪除關聯商品
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'drop_link_goods') {
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    check_authz_json('goods_manage');

    $drop_goods     = $json->decode($_GET['drop_ids']);
    $drop_goods_ids = db_create_in($drop_goods);
    $linked_goods   = $json->decode($_GET['JSON']);
    $goods_id       = $linked_goods[0];
    $is_signle      = $linked_goods[1];

    if (!$is_signle) {
        $sql = "DELETE FROM " . $ecs->table('link_goods') .
            " WHERE link_goods_id = '$goods_id' AND goods_id " . $drop_goods_ids;
    } else {
        $sql = "UPDATE " . $ecs->table('link_goods') . " SET is_double = 0 " .
            " WHERE link_goods_id = '$goods_id' AND goods_id " . $drop_goods_ids;
    }
    if ($goods_id == 0) {
        $sql .= " AND admin_id = '$_SESSION[admin_id]'";
    }
    $db->query($sql);

    $sql = "DELETE FROM " . $ecs->table('link_goods') .
        " WHERE goods_id = '$goods_id' AND link_goods_id " . $drop_goods_ids;
    if ($goods_id == 0) {
        $sql .= " AND admin_id = '$_SESSION[admin_id]'";
    }
    $db->query($sql);

    $linked_goods = get_linked_goods($goods_id);
    $options      = array();

    foreach ($linked_goods as $val) {
        $options[] = array(
            'value' => $val['goods_id'],
            'text'  => $val['goods_name'],
            'data'  => ''
        );
    }

    clear_cache_files();
    make_json_result($options);
}

/*------------------------------------------------------ */
//-- 增加一個配件
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'add_group_goods') {
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    check_authz_json('goods_manage');

    $fittings   = $json->decode($_GET['add_ids']);
    $arguments  = $json->decode($_GET['JSON']);
    $goods_id   = $arguments[0];
    $price      = $arguments[1];

    foreach ($fittings as $val) {
        $sql = "INSERT INTO " . $ecs->table('group_goods') . " (parent_id, goods_id, goods_price, admin_id) " .
            "VALUES ('$goods_id', '$val', '$price', '$_SESSION[admin_id]')";
        $db->query($sql, 'SILENT');
    }

    $arr = get_group_goods($goods_id);
    $opt = array();

    foreach ($arr as $val) {
        $opt[] = array(
            'value'      => $val['goods_id'],
            'text'      => $val['goods_name'],
            'data'      => ''
        );
    }

    clear_cache_files();
    make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 刪除一個配件
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'drop_group_goods') {
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    check_authz_json('goods_manage');

    $fittings   = $json->decode($_GET['drop_ids']);
    $arguments  = $json->decode($_GET['JSON']);
    $goods_id   = $arguments[0];
    $price      = $arguments[1];

    $sql = "DELETE FROM " . $ecs->table('group_goods') .
        " WHERE parent_id='$goods_id' AND " . db_create_in($fittings, 'goods_id');
    if ($goods_id == 0) {
        $sql .= " AND admin_id = '$_SESSION[admin_id]'";
    }
    $db->query($sql);

    $arr = get_group_goods($goods_id);
    $opt = array();

    foreach ($arr as $val) {
        $opt[] = array(
            'value'      => $val['goods_id'],
            'text'      => $val['goods_name'],
            'data'      => ''
        );
    }

    clear_cache_files();
    make_json_result($opt);
}

/*------------------------------------------------------ */
//-- 搜索文章
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'get_article_list') {
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON;

    $filters = (array) $json->decode(json_str_iconv($_GET['JSON']));

    $where = " WHERE cat_id > 0 ";
    if (!empty($filters['title'])) {
        $keyword  = trim($filters['title']);
        $where   .=  " AND title LIKE '%" . mysql_like_quote($keyword) . "%' ";
    }

    $sql        = 'SELECT article_id, title FROM ' . $ecs->table('article') . $where .
        'ORDER BY article_id DESC LIMIT 50';
    $res        = $db->query($sql);
    $arr        = array();

    while ($row = $db->fetchRow($res)) {
        $arr[]  = array('value' => $row['article_id'], 'text' => $row['title'], 'data' => '');
    }

    make_json_result($arr);
}


/*------------------------------------------------------ */
//-- 貨品刪除
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'product_remove') {
    /* 檢查權限 */
    check_authz_json('remove_back');

    /* 是否存在商品id */
    if (empty($_REQUEST['id'])) {
        make_json_error($_LANG['product_id_null']);
    } else {
        $product_id = intval($_REQUEST['id']);
    }

    /* 貨品庫存 */
    $product = get_product_info($product_id, 'product_number, goods_id');

    /* 刪除貨品 */
    $sql = "DELETE FROM " . $ecs->table('products') . " WHERE product_id = '$product_id'";
    $result = $db->query($sql);
    if ($result) {
        /* 修改商品庫存 */
        if (update_goods_stock($product['goods_id'], $product_number - $product['product_number'])) {
            //記錄日誌
            admin_log('', 'update', 'goods');
        }

        //記錄日誌
        admin_log('', 'trash', 'products');

        $url = 'goods.php?act=product_query&' . str_replace('act=product_remove', '', $_SERVER['QUERY_STRING']);

        ecs_header("Location: $url\n");
        exit;
    }
}

/*------------------------------------------------------ */
//-- 修改貨品價格
/*------------------------------------------------------ */ elseif ($_REQUEST['act'] == 'edit_product_sn') {
    check_authz_json('goods_manage');

    $product_id       = intval($_POST['id']);
    $product_sn       = json_str_iconv(trim($_POST['val']));
    $product_sn       = ($_LANG['n_a'] == $product_sn) ? '' : $product_sn;

    if (check_product_sn_exist($product_sn, $product_id)) {
        make_json_error($_LANG['sys']['wrong'] . $_LANG['exist_same_product_sn']);
    }

    /* 修改 */
    $sql = "UPDATE " . $ecs->table('products') . " SET product_sn = '$product_sn' WHERE product_id = '$product_id'";
    $result = $db->query($sql);
    if ($result) {
        clear_cache_files();
        make_json_result($product_sn);
    }
}

/**
 * 列表鏈接
 * @param   bool    $is_add         是否添加（插入）
 * @param   string  $extension_code 虛擬商品擴展代碼，實體商品為空
 * @return  array('href' => $href, 'text' => $text)
 */
function list_link()
{
    $href = 'homestay.php?act=edit';
    $text = '網站內容';

    return array('href' => $href, 'text' => $text);
}

/**
 * 添加鏈接
 * @param   string  $extension_code 虛擬商品擴展代碼，實體商品為空
 * @return  array('href' => $href, 'text' => $text)
 */
function add_link()
{
    $href = 'homestay.php?act=edit';
    $text = '網站內容';

    return array('href' => $href, 'text' => $text);
}

/**
 * 檢查圖片網址是否合法
 *
 * @param string $url 網址
 *
 * @return boolean
 */
function goods_parse_url($url)
{
    $parse_url = @parse_url($url);
    return (!empty($parse_url['scheme']) && !empty($parse_url['host']));
}

function get_fac_list($myfac = '')
{
    $arr_fac = explode(",", $myfac);

    $sql = "SELECT * FROM " . $GLOBALS['ecs']->table('facility') .
        "WHERE is_show = 1 order by sort_order,id";
    $result = $GLOBALS['db']->getAll($sql);
    $count = count($result);
    for ($i = 0; $i < $count; $i++) {
        if (in_array($result[$i]['id'], $arr_fac)) {
            $result[$i]['selected'] = 1;
        } else {
            $result[$i]['selected'] = 0;
        }
    }

    return $result;
}
