<?php
// File: /quanlybanhang/modules/pos/tabs/overview_tab.php
require_once __DIR__ . '/../../../core/init.php';

if (!isset($_SESSION['user_id'])) {
    echo '<div class="text-center p-5">Vui lòng đăng nhập lại.</div>';
    exit();
}

$user_id = $_SESSION['user_id'];
$group_id = $_SESSION['group_id'] ?? 0;
$current_date = date('Y-m-d');
$first_day_of_month = date('Y-m-01');

// 1. LẤY SỐ LIỆU THÁNG NÀY
$month_params = [];
$month_types = "";
$month_where = ["o.sell_date BETWEEN ? AND ?", "o.deleted = 0", "o.order_status = 1"]; // Chỉ tính đơn hoàn thành
$month_params[] = $first_day_of_month . " 00:00:00";
$month_params[] = $current_date . " 23:59:59";
$month_types .= "ss";

if ($group_id != 1) {
    $month_where[] = "o.user_init = ?";
    $month_params[] = $user_id;
    $month_types .= "i";
}
$month_sql_where = " WHERE " . implode(" AND ", $month_where);

// Query tổng hợp tháng
$sql_month = "SELECT 
                COUNT(ID) as total_orders, 
                SUM(total_money) as total_revenue, 
                SUM(total_money - total_origin_price) as total_profit,
                SUM(total_quantity) as total_products
              FROM cms_orders o " . $month_sql_where;

$stmt_month = $conn->prepare($sql_month);
if (!empty($month_types)) $stmt_month->bind_param($month_types, ...$month_params);
$stmt_month->execute();
$res_month = $stmt_month->get_result()->fetch_assoc();
$stmt_month->close();

$month_revenue = $res_month['total_revenue'] ?? 0;
$month_profit = $res_month['total_profit'] ?? 0;
$month_orders = $res_month['total_orders'] ?? 0;
$month_products = $res_month['total_products'] ?? 0;

// 2. LẤY SỐ LIỆU HÔM NAY
$today_params = [];
$today_types = "";
$today_where = ["DATE(o.sell_date) = ?", "o.deleted = 0", "o.order_status = 1"];
$today_params[] = $current_date;
$today_types .= "s";

if ($group_id != 1) {
    $today_where[] = "o.user_init = ?";
    $today_params[] = $user_id;
    $today_types .= "i";
}
$today_sql_where = " WHERE " . implode(" AND ", $today_where);

$sql_today = "SELECT COUNT(ID) as total_orders, SUM(total_money) as total_revenue FROM cms_orders o " . $today_sql_where;
$stmt_today = $conn->prepare($sql_today);
if (!empty($today_types)) $stmt_today->bind_param($today_types, ...$today_params);
$stmt_today->execute();
$res_today = $stmt_today->get_result()->fetch_assoc();
$stmt_today->close();

$today_revenue = $res_today['total_revenue'] ?? 0;
$today_orders = $res_today['total_orders'] ?? 0;

// 3. DỮ LIỆU BIỂU ĐỒ (7 NGÀY GẦN NHẤT)
$chart_labels = [];
$chart_data = [];
// Logic lấy dữ liệu biểu đồ tương tự trang Profit nhưng giới hạn 7 ngày
for ($i = 6; $i >= 0; $i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $chart_labels[] = date('d/m', strtotime($d));
    
    // Query đơn giản lấy doanh thu ngày đó
    $sql_chart = "SELECT SUM(total_money) as rev FROM cms_orders o WHERE DATE(o.sell_date) = '$d' AND o.deleted = 0 AND o.order_status = 1";
    if ($group_id != 1) $sql_chart .= " AND o.user_init = $user_id";
    
    $row = $conn->query($sql_chart)->fetch_assoc();
    $chart_data[] = $row['rev'] ?? 0;
}
?>

<style>
    .overview-card { background: #fff; border-radius: 12px; padding: 15px; margin-bottom: 15px; border: 1px solid #f0f0f0; box-shadow: 0 2px 5px rgba(0,0,0,0.03); transition: transform 0.2s; }
    .overview-card:active { transform: scale(0.98); }
    
    .overview-icon { width: 40px; height: 40px; border-radius: 10px; display: flex; align-items: center; justify-content: center; font-size: 1.2rem; margin-bottom: 10px; }
    
    /* Màu sắc Icon nền */
    .bg-blue-light { background: #e7f1ff; color: #0d6efd; }
    .bg-green-light { background: #d1e7dd; color: #198754; }
    .bg-orange-light { background: #ffecb5; color: #ffc107; }
    .bg-purple-light { background: #e0cffc; color: #6f42c1; }
    .bg-red-light { background: #f8d7da; color: #dc3545; }
    
    .ov-label { font-size: 0.75rem; color: #6c757d; font-weight: 700; text-transform: uppercase; margin-bottom: 4px; }
    .ov-value { font-size: 1.2rem; font-weight: 800; color: #212529; margin-bottom: 0; line-height: 1.2; }
    .ov-sub { font-size: 0.7rem; color: #999; margin-top: 2px; }
</style>

<div class="container-fluid pt-3 pb-5">
    <div class="d-flex justify-content-between align-items-center mb-3 px-1">
        <h6 class="fw-bold m-0 text-uppercase text-secondary"><i class="fas fa-calendar-day me-2"></i>Hôm Nay (<?php echo date('d/m'); ?>)</h6>
    </div>

    <div class="row g-2 mb-4">
        <div class="col-6">
            <div class="overview-card h-100">
                <div class="overview-icon bg-blue-light"><i class="fas fa-coins"></i></div>
                <div class="ov-label">Doanh số</div>
                <div class="ov-value text-primary"><?php echo number_format($today_revenue); ?></div>
            </div>
        </div>
        <div class="col-6">
            <div class="overview-card h-100">
                <div class="overview-icon bg-orange-light"><i class="fas fa-receipt"></i></div>
                <div class="ov-label">Đơn hàng</div>
                <div class="ov-value text-warning"><?php echo number_format($today_orders); ?></div>
            </div>
        </div>
    </div>

    <div class="d-flex justify-content-between align-items-center mb-3 px-1 border-top pt-3">
        <h6 class="fw-bold m-0 text-uppercase text-secondary"><i class="fas fa-calendar-alt me-2"></i>Tháng Này (<?php echo date('m/Y'); ?>)</h6>
    </div>

    <div class="row g-2 mb-3">
        <div class="col-6">
            <div class="overview-card h-100">
                <div class="overview-icon bg-green-light"><i class="fas fa-chart-line"></i></div>
                <div class="ov-label">Doanh số tháng</div>
                <div class="ov-value text-success"><?php echo number_format($month_revenue); ?></div>
            </div>
        </div>
        <div class="col-6">
            <div class="overview-card h-100">
                <div class="overview-icon bg-purple-light"><i class="fas fa-wallet"></i></div>
                <div class="ov-label">Lợi nhuận</div>
                <div class="ov-value text-purple"><?php echo number_format($month_profit); ?></div>
            </div>
        </div>
        <div class="col-6">
            <div class="overview-card h-100">
                <div class="overview-icon bg-red-light"><i class="fas fa-box-open"></i></div>
                <div class="ov-label">Sản phẩm bán</div>
                <div class="ov-value text-danger"><?php echo number_format($month_products); ?></div>
            </div>
        </div>
        <div class="col-6">
            <div class="overview-card h-100">
                <div class="overview-icon bg-orange-light"><i class="fas fa-file-invoice"></i></div>
                <div class="ov-label">Tổng đơn</div>
                <div class="ov-value text-warning"><?php echo number_format($month_orders); ?></div>
            </div>
        </div>
    </div>

    <div class="overview-card mt-3">
        <h6 class="fw-bold text-secondary mb-3 small text-uppercase"><i class="fas fa-chart-bar me-2"></i>Doanh thu 7 ngày qua</h6>
        <div style="height: 220px;">
            <canvas id="overviewChart"></canvas>
        </div>
    </div>
</div>

<script>
$(function() {
    // Hủy biểu đồ cũ nếu có (tránh lỗi khi reload tab)
    if (window.myOverviewChart instanceof Chart) { window.myOverviewChart.destroy(); }

    const ctx = document.getElementById('overviewChart');
    if (ctx) {
        window.myOverviewChart = new Chart(ctx, {
            type: 'bar',
            data: {
                labels: <?php echo json_encode($chart_labels); ?>,
                datasets: [{
                    label: 'Doanh thu',
                    data: <?php echo json_encode($chart_data); ?>,
                    backgroundColor: '#0d6efd',
                    borderRadius: 4,
                    barThickness: 15 // Cột dày hơn chút cho dễ nhìn
                }]
            },
            options: {
                responsive: true, 
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: { 
                    y: { 
                        beginAtZero: true, 
                        ticks: { 
                            callback: function(val) { 
                                // Rút gọn số tiền (ví dụ 1.000.000 -> 1M, 500.000 -> 500k)
                                if(val >= 1000000) return (val/1000000).toFixed(1) + 'M';
                                if(val >= 1000) return (val/1000).toFixed(0) + 'k';
                                return val; 
                            },
                            font: { size: 10 }
                        } 
                    }, 
                    x: { grid: { display: false }, ticks: { font: { size: 10 } } } 
                }
            }
        });
    }
});
</script>