<?php
/**
 * 芋头CMS
 * ============================================================================
 * 版权所有 2016-2028 沅陵县乌托邦网络服务有限公司，并保留所有权利。
 * 网站地址: http://www.yutoucms.cn
 * ----------------------------------------------------------------------------
 * 如果商业用途务必到官方购买正版授权, 以免引起不必要的法律纠纷.
 * ============================================================================
 * Author: 芋头 <mxgsf@qq.com>
 * Date: 2026-5-20
 */
if (!defined('ROOT_PATH')) {
    define('ROOT_PATH', dirname(__DIR__, 2) . '/');
}

require_once ROOT_PATH . 'core/lib/license.php';
require_once ROOT_PATH . 'core/lib/license_guard.php';
require_once ROOT_PATH . 'core/db/db.php';

$licenseObj = new \Core\Lib\License();
$readonlyMode = !\Core\Lib\LicenseGuard::canUseOrder($licenseObj);

$db = isset($db) && $db instanceof \Core\Db\DB ? $db : \Core\Db\DB::getInstance();
if (!function_exists('ytShippingReadonlyBanner')) {
    function ytShippingReadonlyBanner()
    {
        echo '<div style="margin-bottom:20px;padding:18px 20px;border:1px solid #fdba74;background:linear-gradient(135deg,#fff7ed 0%,#ffffff 100%);border-radius:14px;display:flex;align-items:center;justify-content:space-between;gap:16px;flex-wrap:wrap;">';
        echo '<div><div style="font-size:16px;font-weight:700;color:#9a3412;">发货管理当前为只读模式</div><div style="margin-top:6px;font-size:13px;color:#7c2d12;line-height:1.8;">免费版可查看订单物流信息，填写发货、保存物流单号需升级专业版授权后使用。</div></div>';
        echo '<a href="?act=auth" style="display:inline-flex;align-items:center;justify-content:center;padding:11px 18px;border-radius:10px;background:linear-gradient(135deg,#ea580c 0%,#dc2626 100%);color:#fff;text-decoration:none;font-weight:700;white-space:nowrap;">升级授权</a>';
        echo '</div>';
    }
}

function ytShippingColumns($db)
{
    static $columns = null;
    if ($columns !== null) {
        return $columns;
    }

    $columns = [];
    foreach ($db->fetchAll('SHOW COLUMNS FROM ' . $db->table('order')) as $row) {
        $columns[$row['Field']] = true;
    }
    return $columns;
}

function ytShippingHasColumn($db, $column)
{
    $columns = ytShippingColumns($db);
    return isset($columns[$column]);
}

function ytShippingGetOrderValue(array $order, array $keys, $default = '')
{
    foreach ($keys as $key) {
        if (isset($order[$key]) && trim((string) $order[$key]) !== '') {
            return $order[$key];
        }
    }
    return $default;
}

function ytShippingTimeValue(array $order, array $keys)
{
    foreach ($keys as $key) {
        if (!empty($order[$key])) {
            return intval($order[$key]);
        }
    }
    return 0;
}

if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['ajax_action'])) {
    requireAdminCsrfToken(true);
    if ($readonlyMode) {
        while (ob_get_level() > 0) { ob_end_clean(); }
        header('Content-Type: application/json; charset=utf-8');
        echo json_encode(['code' => 403, 'msg' => '当前为只读模式，升级专业版后可操作'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    while (ob_get_level() > 0) { ob_end_clean(); }
    header('Content-Type: application/json; charset=utf-8');

    $ajaxAction = trim((string) $_POST['ajax_action']);
    if ($ajaxAction !== 'ship') {
        echo json_encode(['code' => 404, 'msg' => '未知操作'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $id = intval($_POST['id'] ?? 0);
    $expressCompany = trim((string) ($_POST['express_company'] ?? ''));
    $expressNo = trim((string) ($_POST['express_no'] ?? ''));
    $shipNote = trim((string) ($_POST['ship_note'] ?? ''));

    if ($id <= 0) {
        echo json_encode(['code' => 400, 'msg' => '订单ID无效'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if ($expressCompany === '') {
        echo json_encode(['code' => 400, 'msg' => '请填写快递公司'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if ($expressNo === '') {
        echo json_encode(['code' => 400, 'msg' => '请填写物流单号'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $order = $db->fetch('SELECT * FROM ' . $db->table('order') . ' WHERE id = ?', [$id]);
    if (!$order) {
        echo json_encode(['code' => 404, 'msg' => '订单不存在'], JSON_UNESCAPED_UNICODE);
        exit;
    }
    if (intval($order['status'] ?? 0) !== 1 && intval($order['status'] ?? 0) !== 2) {
        echo json_encode(['code' => 400, 'msg' => '只有已付款或已发货订单可以填写物流'], JSON_UNESCAPED_UNICODE);
        exit;
    }

    $now = time();
    $update = [
        'status' => 2,
        'update_time' => $now,
        'ship_note' => $shipNote,
    ];
    if (ytShippingHasColumn($db, 'express_company')) {
        $update['express_company'] = $expressCompany;
    }
    if (ytShippingHasColumn($db, 'express_no')) {
        $update['express_no'] = $expressNo;
    }
    if (ytShippingHasColumn($db, 'delivery_time')) {
        $update['delivery_time'] = $now;
    }
    if (ytShippingHasColumn($db, 'ship_no')) {
        $update['ship_no'] = $expressNo;
    }
    if (ytShippingHasColumn($db, 'ship_time')) {
        $update['ship_time'] = $now;
    }

    $db->update('order', $update, 'id = ?', [$id]);
    if (function_exists('sendMemberMessage') && intval($order['member_id'] ?? 0) > 0) {
        try {
            sendMemberMessage(
                intval($order['member_id']),
                '订单已发货',
                '订单 ' . ($order['order_sn'] ?? $id) . " 已发货。\n物流公司：" . $expressCompany . "\n物流单号：" . $expressNo
            );
        } catch (Throwable $e) {
            error_log('Shipping notification failed: ' . $e->getMessage());
        }
    }
    echo json_encode(['code' => 200, 'msg' => '发货信息已保存'], JSON_UNESCAPED_UNICODE);
    exit;
}

$page = max(1, intval($_GET['page'] ?? 1));
$pageSize = 15;
$offset = ($page - 1) * $pageSize;
$status = trim((string) ($_GET['status'] ?? '1'));
$keyword = trim((string) ($_GET['keyword'] ?? ''));

$where = [];
$params = [];
if ($status !== '' && $status !== 'all') {
    $where[] = 'status = ?';
    $params[] = intval($status);
}
if ($keyword !== '') {
    $where[] = '(order_sn LIKE ? OR name LIKE ? OR consignee LIKE ? OR mobile LIKE ? OR express_no LIKE ? OR ship_no LIKE ?)';
    $keywordLike = '%' . $keyword . '%';
    array_push($params, $keywordLike, $keywordLike, $keywordLike, $keywordLike, $keywordLike, $keywordLike);
}
$whereSql = $where ? ('WHERE ' . implode(' AND ', $where)) : '';

$total = intval($db->fetch('SELECT COUNT(*) AS cnt FROM ' . $db->table('order') . ' ' . $whereSql, $params)['cnt'] ?? 0);
$totalPages = max(1, (int) ceil($total / $pageSize));
$orders = $db->fetchAll('SELECT * FROM ' . $db->table('order') . ' ' . $whereSql . ' ORDER BY id DESC LIMIT ' . $offset . ', ' . $pageSize, $params);

$waitingCount = intval($db->fetch('SELECT COUNT(*) AS cnt FROM ' . $db->table('order') . ' WHERE status = 1')['cnt'] ?? 0);
$shippedCount = intval($db->fetch('SELECT COUNT(*) AS cnt FROM ' . $db->table('order') . ' WHERE status = 2')['cnt'] ?? 0);
$completedCount = intval($db->fetch('SELECT COUNT(*) AS cnt FROM ' . $db->table('order') . ' WHERE status = 3')['cnt'] ?? 0);
$statusMap = [
    -1 => ['已取消', 'badge-danger'],
    0 => ['待付款', 'badge-warning'],
    1 => ['待发货', 'badge-primary'],
    2 => ['已发货', 'badge-info'],
    3 => ['已完成', 'badge-success'],
];
?>
<div class="page-container fade-in">
    <div class="page-header">
    <?php if ($readonlyMode) { ytShippingReadonlyBanner(); } ?>
        <div>
            <h1 style="margin:0;font-size:20px;color:#0f172a;">发货管理</h1>
            <p style="margin:6px 0 0;color:#64748b;font-size:13px;">管理快递公司、物流单号、发货时间和发货备注。</p>
        </div>
        <div class="page-actions"><a href="?act=order" class="btn btn-secondary">订单管理</a></div>
    </div>

    <div class="yt-ship-stats">
        <a href="?act=shipping&status=1" class="yt-ship-stat"><span>待发货</span><strong><?php echo $waitingCount; ?></strong></a>
        <a href="?act=shipping&status=2" class="yt-ship-stat"><span>已发货</span><strong><?php echo $shippedCount; ?></strong></a>
        <a href="?act=shipping&status=3" class="yt-ship-stat"><span>已完成</span><strong><?php echo $completedCount; ?></strong></a>
    </div>

    <div class="content-card" style="margin-bottom:16px;padding:16px;">
        <form method="get" style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
            <input type="hidden" name="act" value="shipping">
            <select name="status" class="form-control" style="width:160px;">
                <option value="all" <?php echo $status === 'all' ? 'selected' : ''; ?>>全部订单</option>
                <option value="1" <?php echo $status === '1' ? 'selected' : ''; ?>>待发货</option>
                <option value="2" <?php echo $status === '2' ? 'selected' : ''; ?>>已发货</option>
                <option value="3" <?php echo $status === '3' ? 'selected' : ''; ?>>已完成</option>
            </select>
            <input type="text" name="keyword" class="form-control" style="width:260px;" value="<?php echo htmlspecialchars($keyword, ENT_QUOTES, 'UTF-8'); ?>" placeholder="订单号/收货人/手机/物流单号">
            <button type="submit" class="btn btn-primary">筛选</button>
            <a href="?act=shipping" class="btn btn-secondary">重置</a>
        </form>
    </div>

    <div class="content-card">
        <?php if (empty($orders)): ?>
        <div class="empty-state" style="padding:54px 20px;text-align:center;color:#94a3b8;">暂无发货订单</div>
        <?php else: ?>
        <table class="data-table">
            <thead>
                <tr>
                    <th style="width:60px;">ID</th>
                    <th>订单信息</th>
                    <th style="width:150px;">收货人</th>
                    <th style="width:180px;">物流信息</th>
                    <th style="width:100px;">状态</th>
                    <th style="width:150px;">发货时间</th>
                    <th style="width:160px;">操作</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($orders as $order): ?>
                <?php
                $orderId = intval($order['id'] ?? 0);
                $expressCompany = (string) ytShippingGetOrderValue($order, ['express_company'], '');
                $expressNo = (string) ytShippingGetOrderValue($order, ['express_no', 'ship_no'], '');
                $shipTime = ytShippingTimeValue($order, ['delivery_time', 'ship_time']);
                $statusInfo = $statusMap[intval($order['status'] ?? 0)] ?? ['未知', 'badge-gray'];
                $consignee = ytShippingGetOrderValue($order, ['name', 'consignee'], '-');
                ?>
                <tr>
                    <td class="id-cell"><?php echo $orderId; ?></td>
                    <td>
                        <div style="font-family:monospace;font-weight:600;color:#0f172a;"><?php echo htmlspecialchars($order['order_sn'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></div>
                        <div style="margin-top:4px;color:#64748b;font-size:12px;">金额：￥<?php echo number_format(floatval($order['pay_price'] ?? ($order['total_amount'] ?? 0)), 2); ?></div>
                    </td>
                    <td>
                        <div style="font-weight:600;color:#334155;"><?php echo htmlspecialchars((string) $consignee, ENT_QUOTES, 'UTF-8'); ?></div>
                        <div style="margin-top:3px;color:#64748b;font-size:12px;"><?php echo htmlspecialchars($order['mobile'] ?? '-', ENT_QUOTES, 'UTF-8'); ?></div>
                    </td>
                    <td>
                        <div style="font-weight:600;color:#334155;"><?php echo htmlspecialchars($expressCompany !== '' ? $expressCompany : '未填写', ENT_QUOTES, 'UTF-8'); ?></div>
                        <div style="margin-top:3px;color:#64748b;font-size:12px;"><?php echo htmlspecialchars($expressNo !== '' ? $expressNo : '未填写', ENT_QUOTES, 'UTF-8'); ?></div>
                    </td>
                    <td><span class="badge <?php echo $statusInfo[1]; ?>"><?php echo $statusInfo[0]; ?></span></td>
                    <td style="color:#64748b;font-size:12px;"><?php echo $shipTime > 0 ? date('Y-m-d H:i', $shipTime) : '-'; ?></td>
                    <td>
                        <?php if ($readonlyMode): ?>
                        <a href="?act=auth" class="btn btn-secondary">升级后发货</a>
                        <?php else: ?>
                        <button type="button" class="btn btn-primary" onclick="openShipModal(<?php echo $orderId; ?>, '<?php echo htmlspecialchars(addslashes($expressCompany), ENT_QUOTES, 'UTF-8'); ?>', '<?php echo htmlspecialchars(addslashes($expressNo), ENT_QUOTES, 'UTF-8'); ?>', '<?php echo htmlspecialchars(addslashes($order['ship_note'] ?? ''), ENT_QUOTES, 'UTF-8'); ?>')">填写发货</button>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
        <?php if ($totalPages > 1): ?>
        <div class="pagination" style="padding:16px;text-align:center;">
            <?php for ($i = max(1, $page - 2); $i <= min($totalPages, $page + 2); $i++): ?>
            <a href="?act=shipping&page=<?php echo $i; ?>&status=<?php echo urlencode($status); ?>&keyword=<?php echo urlencode($keyword); ?>" <?php echo $i === $page ? 'class="active"' : ''; ?>><?php echo $i; ?></a>
            <?php endfor; ?>
        </div>
        <?php endif; ?>
        <?php endif; ?>
    </div>
</div>

<div id="shipModal" class="yt-ship-modal" style="display:none;">
    <div class="yt-ship-modal-card">
        <h3>填写发货信息</h3>
        <input type="hidden" id="shipOrderId">
        <div class="form-group">
            <label>快递公司</label>
            <input type="text" id="expressCompany" class="form-control" placeholder="如：顺丰速运、中通快递">
        </div>
        <div class="form-group">
            <label>物流单号</label>
            <input type="text" id="expressNo" class="form-control" placeholder="请输入物流单号">
        </div>
        <div class="form-group">
            <label>发货备注</label>
            <textarea id="shipNote" class="form-control" rows="3" placeholder="可填写发货说明或售后备注"></textarea>
        </div>
        <div style="display:flex;gap:10px;justify-content:flex-end;margin-top:20px;">
            <button type="button" class="btn btn-secondary" onclick="closeShipModal()">取消</button>
            <button type="button" class="btn btn-primary" onclick="submitShip()">保存发货</button>
        </div>
    </div>
</div>

<style>
.yt-ship-stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(180px,1fr));gap:12px;margin-bottom:16px;}
.yt-ship-stat{display:flex;justify-content:space-between;align-items:center;padding:16px 18px;background:#fff;border:1px solid #e2e8f0;border-radius:14px;text-decoration:none;color:#334155;}
.yt-ship-stat span{font-size:13px;color:#64748b;}
.yt-ship-stat strong{font-size:24px;color:#0f172a;}
.yt-ship-modal{position:fixed;inset:0;background:rgba(15,23,42,.48);z-index:9999;align-items:center;justify-content:center;padding:20px;}
.yt-ship-modal-card{width:420px;max-width:100%;background:#fff;border-radius:16px;padding:24px;box-shadow:0 24px 70px rgba(15,23,42,.24);}
.yt-ship-modal-card h3{margin:0 0 18px;font-size:18px;color:#0f172a;}
.yt-ship-modal-card .form-group{margin-bottom:14px;}
.yt-ship-modal-card label{display:block;font-size:13px;color:#475569;margin-bottom:6px;}
.yt-ship-modal-card textarea.form-control{resize:vertical;min-height:88px;}
</style>

<script>
var shippingCsrfToken = <?php echo json_encode(getAdminCsrfToken()); ?>;
function openShipModal(id, company, no, note) {
    document.getElementById('shipOrderId').value = id;
    document.getElementById('expressCompany').value = company || '';
    document.getElementById('expressNo').value = no || '';
    document.getElementById('shipNote').value = note || '';
    document.getElementById('shipModal').style.display = 'flex';
}
function closeShipModal() {
    document.getElementById('shipModal').style.display = 'none';
}
function submitShip() {
    var id = document.getElementById('shipOrderId').value;
    var company = document.getElementById('expressCompany').value.trim();
    var no = document.getElementById('expressNo').value.trim();
    var note = document.getElementById('shipNote').value.trim();
    if (!company) { alert('请填写快递公司'); return; }
    if (!no) { alert('请填写物流单号'); return; }

    var xhr = new XMLHttpRequest();
    xhr.open('POST', '?act=shipping', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        try {
            var res = JSON.parse(xhr.responseText);
            alert(res.msg || '操作完成');
            if (res.code === 200) { closeShipModal(); location.reload(); }
        } catch (e) {
            alert('操作失败');
        }
    };
    xhr.send('ajax_action=ship&id=' + encodeURIComponent(id) + '&express_company=' + encodeURIComponent(company) + '&express_no=' + encodeURIComponent(no) + '&ship_note=' + encodeURIComponent(note) + '&csrf_token=' + encodeURIComponent(shippingCsrfToken));
}
document.getElementById('shipModal').addEventListener('click', function(e) {
    if (e.target === this) closeShipModal();
});
</script>
