<?php
/*
Plugin Name: 商品类型【独立卡密】
Version: 1.0.4
Plugin URL:
Description: 创建一次性卡密类型的商品，并管理与发货相关卡密库存。适合用于有效性为一次性的单条卡密商品
Author: 驳手
Author URL:
Ui: Layui
*/

defined('EM_ROOT') || exit('access denied!');

// 添加商品类型
function plugin_goods_once_type($goods, &$result){
    $goods['goods_type_all'][] = ['name' => '独立卡密（新）', 'value' => 'once'];
    $result = $goods;
}

// 展示商品列表的商品类型徽章
function plugin_goods_list_type_once($type){
    echo <<<html
{{#  if(d.type == 'once'){ }}
<span class="layui-badge layui-bg-green">新独立卡密</span>
{{#  } }}
html;
}

// 发货
function plugin_goods_once_deliver($db, $db_prefix, $goods, $order, $order_child){
    if($goods['type'] == 'once'){
        $kami_order = Option::get('kami_order');
        $kami_order = empty($kami_order) ? 'asc' : $kami_order;
//d($order_child);die;
        $timestamp = time();
        $sku = empty($order_child['sku']) ? '0' : $order_child['sku'];
        // 构建查询排序条件
        switch($kami_order) {
            case 'asc':
                $orderSql = 'ORDER BY id asc';
                break;
            case 'desc':
                $orderSql = 'ORDER BY id desc';
                break;
            default:
                $orderSql = 'ORDER BY RAND()';
        }

        $db->query("
UPDATE {$db_prefix}goods_once 
SET 
    sale_time = {$timestamp}, order_list_id = {$order_child['id']} 
WHERE 
    goods_id = {$order_child['goods_id']} AND sku = '{$sku}' and sale_time is null 
    
    {$orderSql} LIMIT {$order_child['quantity']} 

");
        // 更新订单状态
        $db->query("UPDATE {$db_prefix}order SET status = 2 WHERE id = '{$order['id']}'");
    }
}

// 未售库存页面
function plugin_goods_once_stock_ws($goods, &$result){
    if($goods['type'] == 'once'){
        $goods['stock_page'] = "../../content/plugins/goods_once/goods_once_show";
        $result = $goods;
    }

}
// 未售库存页面
function plugin_goods_once_stock_ys($goods, &$result){
    if($goods['type'] == 'once'){
        $goods['stock_page'] = "../../content/plugins/goods_once/goods_once_show";
        $result = $goods;
    }

}

// 订单列表按钮
function plugin_goods_once_user_order_list_btn($order, $child_order){
    if($child_order['type'] == 'once'){
        if(!empty($order['pay_time'])){
            echo <<<html
<a href="?action=sdk&out_trade_no={$order['out_trade_no']}" class="btn btn-sm btn-primary">
    <i class="fas fa-key mr-1"></i> 查看卡密信息
</a>
<a href="{$child_order['goods_url']}" class="btn btn-sm btn-outline-secondary ml-2">再次购买</a>
html;

        }
    }
}

function adm_download_deliver_content_once($db, $db_prefix, $order_list_id){
    $kami = $db->fetch_all("select * from {$db_prefix}goods_once where order_list_id = {$order_list_id} order by id asc");

    $content = "";

    foreach($kami as $val){
        $content .= $val['content'] . "\r\n";
    }
    $date = date('YmdHis');
    $filename = '卡密-' . $date . '.txt';
    // 设置HTTP头
    header('Content-Type: text/plain');
    header('Content-Disposition: attachment; filename="' . $filename . '"');
    header('Content-Length: ' . strlen($content));
    // 输出内容
    echo $content;
    exit;
}

// 显示订单详情页
function plugin_goods_once_view_order_detail($db, $db_prefix, $goods, $order, $child_order){

    if($goods['type'] == 'once'){
        $cmd = Input::getStrVar('cmd');
        $kami = $db->fetch_all("select * from {$db_prefix}goods_once where order_list_id = {$child_order['id']} order by id asc");

        if($cmd == 'download'){
            $content = "";

            foreach($kami as $val){
                $content .= $val['content'] . "\r\n";
            }
            $date = date('YmdHis');
            $filename = '卡密-' . $date . '.txt';
            // 设置HTTP头
            header('Content-Type: text/plain');
            header('Content-Disposition: attachment; filename="' . $filename . '"');
            header('Content-Length: ' . strlen($content));
            // 输出内容
            echo $content;
            exit;
        }

        $kami = $db->fetch_all("select * from {$db_prefix}goods_once where order_list_id = {$child_order['id']} limit 500");

        $res = $db->once_fetch_array("select count(id) total from {$db_prefix}goods_once where order_list_id = {$child_order['id']}");
        $total = empty($res) ? 0 : $res['total'];

        include View::getUserView('header');
        include EM_ROOT . "/content/plugins/goods_once/order_detail.php";
        include View::getUserView('footer');
        View::output();
    }
}


// 获取发货内容
function plugin_goods_once_adm_order_detail($db, $db_prefix, $goods, $child_order){

    if($goods['type'] == 'once'){
        $sale = $db->fetch_all("select * from {$db_prefix}goods_once where order_list_id = {$child_order['id']} limit 5");
        $str = "";
        if(!empty($sale)){
            foreach($sale as $val){
                $str .= $val['content'] . "<hr />";
            }
        }
        return $str;
    }
}

function plugin_goods_once_home_goods_list($goods, &$result){
    foreach($goods as $key => $val){
        if($val['type'] == 'once'){
            $goods[$key]['type_text_badge'] = '<span class="badge badge-success">自动发货</span>';
        }
    }
    $result = $goods;
}

function plugin_goods_once_goods_content_echo($goods, &$result){
    if($goods['type'] == 'once'){
        $goods['type_text_badge'] = '<span class="badge badge-success">自动发货</span>';
    }
    $result = $goods;
}

// 获取发货内容
function getDeliverContentonce($db, $db_prefix, $order_id){

    $order_list = $db->once_fetch_array("select * from {$db_prefix}order_list where order_id = {$order_id}");

    $list = $db->fetch_all("select * from {$db_prefix}goods_once where order_list_id = {$order_list['id']} order by id asc limit 10");

    $content = "";
    foreach($list as $val){
        $content .= $val['content'] . "<br />";
    }

    return $content;
}

addAction('adm_add_goods_goodsinfo', 'plugin_goods_once_type');
addAction('adm_goods_list_type', 'plugin_goods_list_type_once');
addAction('adm_stock_page_ws', 'plugin_goods_once_stock_ws');
addAction('adm_stock_page_ys', 'plugin_goods_once_stock_ys');
addAction('deliver', 'plugin_goods_once_deliver');
addAction('user_order_list_btn', 'plugin_goods_once_user_order_list_btn');
addAction('view_order_detail', 'plugin_goods_once_view_order_detail');
addAction('home_goods_list', 'plugin_goods_once_home_goods_list');
addAction('goods_content_echo', 'plugin_goods_once_goods_content_echo');