<?php
/**
 * 销售统计分析展示页面
 */
require_once 'conn.php';
require_once 'statistics_utils.php';
require_once 'statistics_sales.php';
require_once 'statistics_customers.php';
// Helper functions for formatting

function formatCurrency($value) {
    return '¥' . number_format($value ?? 0, 2);
}

// 检查登录状态
if (!isset($_SESSION['employee_id'])) {
    checkLogin();
}

// 获取日期范围参数
$date_params = getDateRangeParams();
$start_date = $date_params['start_date_sql'];
$end_date = $date_params['end_date_sql'];
$date_range = $date_params['date_range'];
$period = $date_params['period'];

// 获取选中的业务员ID
$selected_employee = isset($_GET['employee_id']) ? intval($_GET['employee_id']) : 0;

// 获取所有业务员列表
$employees = getAllEmployees($conn);

// 页面头部
include('statistics_header.php');
?>

<style>

.page-header {
    margin-bottom: 30px;
}

.page-title {
    font-size: 24px;
    color: #333;
    margin: 0;
}

.filter-form {
    background: #f5f5f5;
    padding: 20px;
    border-radius: 8px;
    margin-bottom: 30px;
}

.filter-form-inline {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    align-items: flex-end;
}

.form-group {
    margin-bottom: 10px;
}

.form-group label {
    display: block;
    margin-bottom: 5px;
    color: #666;
}



.btn {
    background: #4a90e2;
    color: white;
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}

.btn:hover {
    background: #357abd;
}

.chart-container {
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    padding: 20px;
    margin-bottom: 30px;
}

.chart-header {
    margin-bottom: 20px;
}

.chart-title {
    font-size: 18px;
    color: #333;
    margin: 0;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.stat-card {
    background: white;
    padding: 20px;
    border-radius: 8px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    text-align: center;
}

.stat-card h3 {
    font-size: 16px;
    color: #666;
    margin: 0 0 10px 0;
}

.stat-value {
    font-size: 24px;
    color: #4a90e2;
    font-weight: bold;
}

.analysis-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(350px, 1fr));
    gap: 20px;
    margin-bottom: 30px;
}

.table-responsive {
    overflow-x: auto;
}

.data-table {
    width: 100%;
    border-collapse: collapse;
}

.data-table th,
.data-table td {
    padding: 12px;
    text-align: left;
    border-bottom: 1px solid #ddd;
}

.data-table th {
    background: #f5f5f5;
    font-weight: bold;
}

.data-table tr:hover {
    background: #f9f9f9;
}

.employee-stats {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 30px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.employee-header {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
}

.employee-avatar {
    width: 64px;
    height: 64px;
    border-radius: 50%;
    background: #f0f0f0;
    margin-right: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 24px;
    color: #666;
}

.employee-info {
    flex: 1;
}

.employee-name {
    font-size: 20px;
    font-weight: bold;
    margin: 0 0 5px;
}

.employee-contact {
    color: #666;
    font-size: 14px;
}

.performance-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 15px;
    margin-bottom: 20px;
}

.performance-card {
    background: #f8f9fa;
    padding: 15px;
    border-radius: 6px;
    text-align: center;
}

.performance-label {
    font-size: 14px;
    color: #666;
    margin-bottom: 5px;
}

.performance-value {
    font-size: 20px;
    font-weight: bold;
    color: #4a90e2;
}

.trend-chart {
    margin-top: 20px;
}
</style>

<div class="container">
    <div class="page-header">
        <h1 class="page-title">销售统计分析</h1>
    </div>
    
    <!-- 日期和业务员筛选 -->
    <div class="filter-form">
        <form method="get" class="filter-form-inline">
            <div class="form-group">
                <label for="employee_id">选择业务员</label>
                <select class="form-control" id="employee_id" name="employee_id">
                    <option value="0">全部业务员</option>
                    <?php foreach ($employees as $emp): ?>
                    <option value="<?php echo $emp['id']; ?>" <?php echo $selected_employee == $emp['id'] ? 'selected' : ''; ?>>
                        <?php echo htmlspecialchars($emp['em_user']); ?>
                    </option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="form-group">
                <label for="date_range">选择日期范围</label>
                <select class="form-control" id="date_range" name="date_range" onchange="toggleCustomDates()">
                    <option value="current_month" <?php echo $date_range == 'current_month' ? 'selected' : ''; ?>>本月</option>
                    <option value="last_month" <?php echo $date_range == 'last_month' ? 'selected' : ''; ?>>上月</option>
                    <option value="current_year" <?php echo $date_range == 'current_year' ? 'selected' : ''; ?>>今年</option>
                    <option value="last_30_days" <?php echo $date_range == 'last_30_days' ? 'selected' : ''; ?>>最近30天</option>
                    <option value="last_90_days" <?php echo $date_range == 'last_90_days' ? 'selected' : ''; ?>>最近90天</option>
                    <option value="custom" <?php echo $date_range == 'custom' ? 'selected' : ''; ?>>自定义日期范围</option>
                </select>
            </div>
            <div class="form-group custom-date-inputs" style="display: <?php echo $date_range == 'custom' ? 'inline-block' : 'none'; ?>">
                <label for="start_date">开始日期</label>
                <input type="date" class="form-control" id="start_date" name="start_date" value="<?php echo $date_params['custom_start']; ?>">
            </div>
            <div class="form-group custom-date-inputs" style="display: <?php echo $date_range == 'custom' ? 'inline-block' : 'none'; ?>">
                <label for="end_date">结束日期</label>
                <input type="date" class="form-control" id="end_date" name="end_date" value="<?php echo $date_params['custom_end']; ?>">
            </div>
            <div class="form-group">
                <label for="period">时间粒度</label>
                <select class="form-control" id="period" name="period">
                    <option value="day" <?php echo $period == 'day' ? 'selected' : ''; ?>>日</option>
                    <option value="week" <?php echo $period == 'week' ? 'selected' : ''; ?>>周</option>
                    <option value="month" <?php echo $period == 'month' ? 'selected' : ''; ?>>月</option>
                </select>
            </div>
            <div class="form-group">
                <button type="submit" class="btn">应用筛选</button>
            </div>
        </form>
    </div>

    <?php if ($selected_employee > 0): ?>
    <!-- 单个业务员详细分析 -->
    <?php
    $employee_detail = getEmployeeDetail($conn, $selected_employee);
    $employee_stats = getEmployeeStats($conn, $selected_employee, $start_date, $end_date);
    ?>
    <div class="employee-stats">
        <div class="employee-header">
            <div class="employee-avatar">
                <?php echo strtoupper(substr($employee_detail['em_user'], 0, 1)); ?>
            </div>
            <div class="employee-info">
                <h2 class="employee-name"><?php echo htmlspecialchars($employee_detail['em_user']); ?></h2>
                <div class="employee-contact">
                    <?php if ($employee_detail['em_email']): ?>
                    <span>邮箱: <?php echo htmlspecialchars($employee_detail['em_email']); ?></span>
                    <?php endif; ?>
                    <?php if ($employee_detail['em_tel']): ?>
                    <span>电话: <?php echo htmlspecialchars($employee_detail['em_tel']); ?></span>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <div class="performance-grid">
            <div class="performance-card">
                <div class="performance-label">总订单数</div>
                <div class="performance-value"><?php echo formatNumber($employee_stats['total_orders']); ?></div>
            </div>
            <div class="performance-card">
                <div class="performance-label">总销售额</div>
                <div class="performance-value"><?php echo formatCurrency($employee_stats['total_revenue']); ?></div>
            </div>
            <div class="performance-card">
                <div class="performance-label">客户数量</div>
                <div class="performance-value"><?php echo formatNumber($employee_stats['customer_count']); ?></div>
            </div>
            <div class="performance-card">
                <div class="performance-label">平均订单金额</div>
                <div class="performance-value"><?php echo formatCurrency($employee_stats['avg_order_value']); ?></div>
            </div>
            <div class="performance-card">
                <div class="performance-label">订单完成率</div>
                <div class="performance-value"><?php echo formatNumber($employee_stats['completion_rate'], 1); ?>%</div>
            </div>
        </div>

        <!-- 业务员销售趋势 -->
        <div class="trend-chart">
            <?php renderEmployeeSalesTrend($conn, $selected_employee, $start_date, $end_date); ?>
        </div>

        <!-- 业务员客户分布 -->
        <div class="trend-chart">
            <?php renderEmployeeCustomerDistribution($conn, $selected_employee, $start_date, $end_date); ?>
        </div>

        <!-- 业务员产品销售分析 -->
        <div class="trend-chart">
            <?php renderEmployeeProductAnalysis($conn, $selected_employee, $start_date, $end_date); ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- 销售概览 -->
    <div class="chart-container">
        <div class="chart-header">
            <h2 class="chart-title">销售概览</h2>
        </div>
        <div class="card-body">
            <?php
            $sales_overview = getSalesOverview($conn, $start_date, $end_date);
            renderSalesOverviewCards($sales_overview);
            ?>
        </div>
    </div>
    
    <!-- 销售转化率分析 -->
    <div class="chart-container">
        <div class="chart-header">
            <h2 class="chart-title">销售转化率分析</h2>
        </div>
        <?php
        $conversion_stats = getOrderConversionStats($conn, $start_date, $end_date);
        renderConversionAnalysis($conversion_stats);
        ?>
    </div>

    <!-- 产品类别销售分析 -->
    <div class="chart-container">
        <div class="chart-header">
            <h2 class="chart-title">产品类别销售分析</h2>
        </div>
        <?php
        $category_sales = getProductCategorySales($conn, $start_date, $end_date);
        renderCategorySalesChart($category_sales);
        ?>
    </div>

    <!-- 客户地区分布 -->
    <div class="chart-container">
        <div class="chart-header">
            <h2 class="chart-title">客户地区分布</h2>
        </div>
        <?php
        $customer_distribution = getCustomerDistribution($conn, $start_date, $end_date);
        renderCustomerDistributionChart($customer_distribution);
        ?>
    </div>

    <!-- 销售员业绩排行 -->
    <div class="chart-container">
        <div class="chart-header">
            <h2 class="chart-title">销售员业绩排行</h2>
        </div>
        <?php
        $employee_performance = getEmployeePerformance($conn, $start_date, $end_date);
        renderEmployeePerformanceTable($employee_performance);
        ?>
    </div>
    
    <!-- 月度销售趋势 -->
    <div class="chart-container">
        <?php
        $monthly_sales = getMonthlySalesTrend($conn, $start_date, $end_date);
        
        $monthly_labels = [];
        $monthly_orders = [];
        $monthly_revenue = [];
        
        while ($row = $monthly_sales->fetch_assoc()) {
            $monthly_labels[] = $row['month'];
            $monthly_orders[] = $row['orders'];
            $monthly_revenue[] = $row['revenue'];
        }
        
        renderMonthlySalesTrendChart($monthly_labels, $monthly_orders, $monthly_revenue);
        ?>
    </div>
    
    <!-- 支付状态分析 -->
    <div class="chart-container">
        <div class="chart-header">
            <h2 class="chart-title">支付状态分析</h2>
        </div>
        <?php
        $payment_stats = getPaymentStatusStats($conn, $start_date, $end_date);
        renderPaymentStatusChart($payment_stats);
        ?>
    </div>

    <!-- 详细订单趋势 -->
    <div class="chart-container">
        <?php
        $detailed_trends = getDetailedOrderTrend($conn, $start_date, $end_date, $period);
        
        $time_labels = [];
        $time_orders = [];
        $time_quantities = [];
        
        while ($row = $detailed_trends->fetch_assoc()) {
            $time_labels[] = $row['time_period'];
            $time_orders[] = $row['order_count'];
            $time_quantities[] = $row['total_quantity'];
        }
        renderDetailedOrderTrendChart($time_labels, $time_orders, $time_quantities, $period);
        ?>
    </div>
</div>

<script>
function toggleCustomDates() {
    const dateRange = document.getElementById('date_range').value;
    const customDateInputs = document.querySelectorAll('.custom-date-inputs');
    
    customDateInputs.forEach(el => {
        el.style.display = dateRange === 'custom' ? 'inline-block' : 'none';
    });
}
</script>

<?php
include('statistics_footer.php');
?>