<?php
/**
 * 地区统计分析展示页面
 */
require_once 'conn.php';
require_once 'statistics_utils.php';
require_once 'statistics_region.php';

// 检查登录状态
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'];

// 特定国家过滤
$country_id = isset($_GET['country_id']) ? intval($_GET['country_id']) : 0;

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


    <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="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">
                <label for="country_id">国家/地区</label>
                <select class="form-control" id="country_id" name="country_id">
                    <option value="0">全部地区</option>
                    <?php
                    $country_filter = isset($_GET['country_id']) ? intval($_GET['country_id']) : 0;
                    $sql = "SELECT id, countryName FROM country ORDER BY countryName";
                    $countries = $conn->query($sql);
                    while($country = $countries->fetch_assoc()) {
                        $selected = ($country_filter == $country['id']) ? 'selected' : '';
                        echo "<option value='{$country['id']}' {$selected}>{$country['countryName']}</option>";
                    }
                    ?>
                </select>
            </div>
            <div class="form-group">
                <button type="submit" class="btn">应用筛选</button>
            </div>
        </form>
    </div>
    
    <!-- 地区销售数据概览 -->
    <div class="key-metrics-section">
        <div class="section-title">
            <h2>地区销售概览</h2>
        </div>
        <div class="stats-row">
            <div class="stat-card">
                <h3>总销售额</h3>
                <?php
                $total_sales = getRegionTotalSales($conn, $start_date, $end_date);
                echo "<div class='stat-value'>¥" . number_format($total_sales['total_amount'], 2) . "</div>";
                echo "<div class='stat-trend " . ($total_sales['growth'] >= 0 ? 'positive' : 'negative') . "'>";
                echo ($total_sales['growth'] >= 0 ? '+' : '') . number_format($total_sales['growth'], 2) . "%</div>";
                ?>
            </div>
            
            <div class="stat-card">
                <h3>活跃国家数</h3>
                <?php
                $active_countries = getActiveCountries($conn, $start_date, $end_date);
                echo "<div class='stat-value'>" . $active_countries['count'] . "</div>";
                ?>
            </div>
            
            <div class="stat-card">
                <h3>平均订单金额</h3>
                <?php
                $avg_order = getAverageOrderByRegion($conn, $start_date, $end_date);
                echo "<div class='stat-value'>¥" . number_format($avg_order['global_avg'], 2) . "</div>";
                ?>
            </div>
        </div>
    </div>
    
    <!-- 热门地区 -->
    <div class="chart-container">
        <div class="section-title">
            <h2>热门地区</h2>
        </div>
        <?php
        $region_orders = getOrdersByRegion($conn, $start_date, $end_date);
        $region_labels = [];
        $region_order_counts = [];
        $region_quantities = [];
        $region_amounts = [];
        
        while ($row = $region_orders->fetch_assoc()) {
            $region_labels[] = $row['countryName'];
            $region_order_counts[] = $row['order_count'];
            $region_quantities[] = $row['total_quantity'];
            $region_amounts[] = $row['total_amount'];
        }
        renderTopRegionsTable($region_labels, $region_order_counts, $region_quantities, $region_amounts);
        ?>
    </div>
    
    <!-- 客户国家分布 -->
    <div class="chart-container">
        <div class="section-title">
            <h2>客户国家分布</h2>
        </div>
        <?php
        $country_distribution = getCustomerCountryDistribution($conn);
        $country_labels = [];
        $country_data = [];
        
        while ($row = $country_distribution->fetch_assoc()) {
            $country_labels[] = $row['countryName'];
            $country_data[] = $row['customer_count'];
        }
        renderCustomerCountryDistributionChart($country_labels, $country_data);
        ?>
    </div>
    
    <!-- 地区销售趋势 -->
    <div class="chart-container">
        <div class="section-title">
            <h2>地区销售趋势</h2>
        </div>
        <?php
        $growth_trends = getRegionGrowthTrends($conn, $start_date, $end_date, $period);
        renderRegionGrowthTrendsChart($growth_trends);
        ?>
    </div>
    
    <!-- 地区订单分析 -->
    <div class="chart-container">
        <div class="section-title">
            <h2>地区订单分析</h2>
        </div>
        <?php
        renderRegionOrdersChart($region_labels, $region_order_counts, $region_quantities);
        ?>
    </div>
    
    <!-- 地区平均订单金额分析 -->
    <div class="chart-container">
        <div class="section-title">
            <h2>地区平均订单金额分析</h2>
        </div>
        <?php
        $avg_order_data = getAverageOrderByRegion($conn, $start_date, $end_date);
        renderAverageOrderByRegionChart($avg_order_data['regions']);
        ?>
    </div>
    
    <!-- 各地区产品类别偏好 -->
    <div class="chart-container">
        <div class="section-title">
            <h2>各地区产品类别偏好</h2>
        </div>
        <?php
        $category_preferences = getRegionCategoryPreferences($conn, $start_date, $end_date);
        renderRegionCategoryPreferencesChart($category_preferences);
        ?>
    </div>
    
    <!-- 地区销售同比分析 -->
    <div class="chart-container">
        <div class="section-title">
            <h2>地区销售同比分析</h2>
        </div>
        <?php
        $comparison_data = getRegionSalesComparison($conn, $start_date, $end_date);
        renderRegionSalesComparisonTable($comparison_data);
        ?>
    </div>
    
    <!-- 地区季节性分析 -->
    <div class="chart-container">
        <div class="section-title">
            <h2>地区季节性分析</h2>
        </div>
        <?php
        $seasonal_analysis = getRegionSeasonalAnalysis($conn);
        renderRegionSeasonalAnalysisChart($seasonal_analysis);
        ?>
    </div>
    
    <!-- 地区销售预测 -->
    <div class="chart-container">
        <div class="section-title">
            <h2>地区销售预测</h2>
        </div>
        <?php
        $forecast_data = getRegionSalesForecast($conn, $start_date, $end_date);
        renderRegionSalesForecastChart($forecast_data);
        ?>
    </div>


<style>
    .positive {
        color: #28a745;
        font-weight: bold;
    }
    .negative {
        color: #dc3545;
        font-weight: bold;
    }
    .key-metrics-section {
        margin-bottom: 30px;
    }
    .section-title {
        margin-bottom: 20px;
        border-bottom: 1px solid #eee;
        padding-bottom: 10px;
    }
    .section-title h2 {
        font-size: 20px;
        margin: 0;
        color: #333;
    }
    .stats-row {
        display: flex;
        flex-wrap: nowrap;
        gap: 20px;
        justify-content: space-between;
        width: 100%;
        margin-bottom: 20px;
    }
    .stat-card {
        background-color: #f8f9fa;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 0;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        height: 100%;
        transition: all 0.3s ease;
        flex: 1;
        min-width: 0; /* Prevents flex items from overflowing */
    }
    .stat-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 5px 15px rgba(0,0,0,0.1);
    }
    .stat-value {
        font-size: 24px;
        font-weight: bold;
        margin: 10px 0;
    }
    .stat-trend {
        font-size: 16px;
    }
    .chart-container {
        background-color: #fff;
        border-radius: 8px;
        padding: 20px;
        margin-bottom: 30px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    .chart-title {
        margin-top: 0;
        margin-bottom: 20px;
        font-size: 18px;
        font-weight: bold;
    }
    .filter-form {
        background-color: #f8f9fa;
        border-radius: 8px;
        padding: 15px;
        margin-bottom: 30px;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1);
    }
    .filter-form-inline {
        display: flex;
        flex-wrap: wrap;
        align-items: end;
        gap: 15px;
    }
    .form-group {
        margin-bottom: 10px;
    }
    .data-table {
        width: 100%;
        border-collapse: collapse;
        margin-top: 15px;
    }
    .data-table th, .data-table td {
        padding: 12px 15px;
        text-align: left;
        border-bottom: 1px solid #ddd;
    }
    .data-table th {
        background-color: #f8f9fa;
        font-weight: bold;
        color: #333;
    }
    .data-table tr:hover {
        background-color: #f5f5f5;
    }
    .subchart-container {
        margin-bottom: 20px;
    }
    .subchart-title {
        font-size: 16px;
        margin-bottom: 15px;
        color: #555;
    }
    .grid-row {
        display: flex;
        flex-wrap: wrap;
        margin: -10px; /* Negative margin to offset the padding in grid-column */
    }
    .grid-column {
        flex: 0 0 50%; /* Two columns per row */
        padding: 10px;
        box-sizing: border-box;
    }
    @media (max-width: 768px) {
        .grid-column {
            flex: 0 0 100%; /* Full width on small screens */
        }
        .stats-row {
            flex-direction: column;
        }
    }
</style>

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

// 初始化所有图表的配置
Chart.defaults.font.family = "'Arial', sans-serif";
Chart.defaults.color = '#666';
Chart.defaults.plugins.tooltip.backgroundColor = 'rgba(0, 0, 0, 0.8)';
Chart.defaults.plugins.legend.position = 'bottom';
</script>

<?php
// 页面底部
include('statistics_footer.php');
?>