<?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');

// ID loại chi phí nhập hàng (Cần loại trừ khi tính chi phí hoạt động)
// Dựa theo file net_profit bạn gửi thì loại trừ type_id = 3
$inventory_expense_id = 3;

// =================================================================================
// 1. XỬ LÝ 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"]; 
$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 (Doanh số, Lợi nhuận gộp, Số đơn, Số SP)
$sql_month = "SELECT 
                COUNT(ID) as total_orders, 
                SUM(total_money) as total_revenue, 
                SUM(total_money - total_origin_price) as total_gross_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_gross_profit = $res_month['total_gross_profit'] ?? 0;
$month_orders = $res_month['total_orders'] ?? 0;
$month_products = $res_month['total_products'] ?? 0;

// --- MỚI: Tính chi phí hoạt động tháng (Trừ tiền nhập hàng) ---
// Chỉ Admin (group_id = 1) mới xem được chi phí đầy đủ, nhân viên chỉ xem đơn của mình thì không trừ chi phí chung
$month_expenses = 0;
if ($group_id == 1) {
    $sql_month_exp = "SELECT SUM(total_money) as total_chi FROM cms_payment 
                      WHERE deleted = 0 AND type_id != ? 
                      AND payment_date BETWEEN ? AND ?";
    $stmt_m_exp = $conn->prepare($sql_month_exp);
    $stmt_m_exp->bind_param("iss", $inventory_expense_id, $month_params[0], $month_params[1]); // Dùng lại tham số ngày
    $stmt_m_exp->execute();
    $res_m_exp = $stmt_m_exp->get_result()->fetch_assoc();
    $month_expenses = $res_m_exp['total_chi'] ?? 0;
    $stmt_m_exp->close();
}
$month_net_profit = $month_gross_profit - $month_expenses;


// =================================================================================
// 2. XỬ LÝ 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);

// Query tổng hợp hôm nay (Thêm tính lợi nhuận gộp hôm nay)
$sql_today = "SELECT 
                COUNT(ID) as total_orders, 
                SUM(total_money) as total_revenue,
                SUM(total_money - total_origin_price) as total_gross_profit
              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;
$today_gross_profit = $res_today['total_gross_profit'] ?? 0;

// --- MỚI: Tính chi phí hoạt động hôm nay ---
$today_expenses = 0;
if ($group_id == 1) {
    $sql_today_exp = "SELECT SUM(total_money) as total_chi FROM cms_payment 
                      WHERE deleted = 0 AND type_id != ? 
                      AND DATE(payment_date) = ?";
    $stmt_t_exp = $conn->prepare($sql_today_exp);
    $stmt_t_exp->bind_param("is", $inventory_expense_id, $current_date);
    $stmt_t_exp->execute();
    $res_t_exp = $stmt_t_exp->get_result()->fetch_assoc();
    $today_expenses = $res_t_exp['total_chi'] ?? 0;
    $stmt_t_exp->close();
}
$today_net_profit = $today_gross_profit - $today_expenses;


// =================================================================================
// 3. DỮ LIỆU BIỂU ĐỒ (7 NGÀY GẦN NHẤT)
// =================================================================================
$chart_labels = [];
$chart_data = [];
for ($i = 6; $i >= 0; $i--) {
    $d = date('Y-m-d', strtotime("-$i days"));
    $chart_labels[] = date('d/m', strtotime($d));
    
    $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; position: relative; overflow: hidden; }
    .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; }
    
    /* Bảng màu sắc phong phú hơn cho các thẻ mới */
    .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; }
    .bg-teal-light { background: #d2f4ea; color: #20c997; } /* Màu cho Lợi nhuận ròng */
    .bg-pink-light { background: #f8d4e6; color: #d63384; } /* Màu cho Lợi nhuận gộp */
    
    .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; }
    
    /* Style cho số liệu phụ (Chi phí) */
    .ov-sub { font-size: 0.7rem; color: #999; margin-top: 4px; display: block;}
    .text-teal { color: #20c997; }
    .text-pink { color: #d63384; }
    .text-purple { color: #6f42c1; }
</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>
        
        <?php if ($group_id == 1): // Chỉ hiện cho Admin ?>
        <div class="col-6">
            <div class="overview-card h-100">
                <div class="overview-icon bg-pink-light"><i class="fas fa-hand-holding-usd"></i></div>
                <div class="ov-label">Lãi gộp</div>
                <div class="ov-value text-pink"><?php echo number_format($today_gross_profit); ?></div>
            </div>
        </div>
        <div class="col-6">
            <div class="overview-card h-100">
                <div class="overview-icon bg-teal-light"><i class="fas fa-piggy-bank"></i></div>
                <div class="ov-label">Lãi ròng (H.Nay)</div>
                <div class="ov-value text-teal"><?php echo number_format($today_net_profit); ?></div>
                <?php if($today_expenses > 0): ?>
                    <span class="ov-sub">(- CP: <?php echo number_format($today_expenses); ?>)</span>
                <?php endif; ?>
            </div>
        </div>
        <?php endif; ?>
    </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 gộp</div>
                <div class="ov-value text-purple"><?php echo number_format($month_gross_profit); ?></div>
            </div>
        </div>

        <?php if ($group_id == 1): // Chỉ hiện cho Admin ?>
        <div class="col-12">
            <div class="overview-card h-100 d-flex align-items-center justify-content-between">
                <div>
                    <div class="overview-icon bg-teal-light mb-1"><i class="fas fa-money-bill-wave"></i></div>
                    <div class="ov-label text-teal">LỢI NHUẬN RÒNG (THỰC TẾ)</div>
                    <div class="ov-value text-teal fs-3"><?php echo number_format($month_net_profit); ?></div>
                </div>
                <div class="text-end text-muted small">
                    <div><i class="fas fa-minus-circle text-danger"></i> Chi phí: <b><?php echo number_format($month_expenses); ?></b></div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <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
                }]
            },
            options: {
                responsive: true, 
                maintainAspectRatio: false,
                plugins: { legend: { display: false } },
                scales: { 
                    y: { 
                        beginAtZero: true, 
                        ticks: { 
                            callback: function(val) { 
                                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>