<?php
/**
 * 订单统计API
 */
require_once dirname(__DIR__) . '/config.php';
require_once dirname(__DIR__) . '/includes/functions.php';

header('Content-Type: application/json');

// 检查登录
if (!isLoggedIn()) {
    echo json_encode(['success' => false, 'message' => '请先登录']);
    exit;
}

$user = currentUser();
if ($user['role'] !== 'admin') {
    echo json_encode(['success' => false, 'message' => '无权限']);
    exit;
}

// 获取统计数据
$pending_count = $db->fetchOne("SELECT COUNT(*) as cnt FROM orders WHERE status = 'pending'")['cnt'] ?? 0;
$expired_count = $db->fetchOne("SELECT COUNT(*) as cnt FROM orders WHERE status = 'pending' AND expire_at IS NOT NULL AND expire_at < NOW()")['cnt'] ?? 0;
$today_cancelled = $db->fetchOne("SELECT COUNT(*) as cnt FROM orders WHERE status = 'cancelled' AND DATE(updated_at) = CURDATE()")['cnt'] ?? 0;

echo json_encode([
    'success' => true,
    'pending_count' => $pending_count,
    'expired_count' => $expired_count,
    'today_cancelled' => $today_cancelled,
    'last_run' => date('Y-m-d H:i:s')
]);