<?php require_once __DIR__ . '/../../templates/header.php'; ?>

<div class="container-fluid">
    <div class="d-sm-flex align-items-center justify-content-between mb-4">
        <h1 class="h3 mb-0 text-gray-800">Tổng quan cửa hàng</h1>
    </div>
    <div class="row">
    <div class="col-xl-4 col-md-6 mb-4">
        <div class="card bg-success text-white shadow">
            <div class="card-body">
                Doanh thu hôm nay
                <span id="today_sales_amount" class="h4 mb-0 font-weight-bold float-right">0 đ</span>
            </div>
        </div>
    </div>
    <div class="col-xl-4 col-md-6 mb-4">
        <div class="card bg-info text-white shadow">
            <div class="card-body">
                Giao dịch hôm nay
                <span id="today_order_count" class="h4 mb-0 font-weight-bold float-right">0</span>
            </div>
        </div>
    </div>
    <div class="col-xl-4 col-md-6 mb-4">
        <div class="card bg-danger text-white shadow">
            <div class="card-body">
                Đơn hàng trả lại
                <span id="today_return_count" class="h4 mb-0 font-weight-bold float-right">0</span>
            </div>
        </div>
    </div>
</div>
    <div class="row">
        <div class="col-lg-4">
            <div class="card shadow mb-4">
                <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary"><i class="fas fa-chart-line"></i> Hoạt động</h6></div>
                <div class="card-body">
                    <p class="clearfix">Tiền bán hàng <span id="summary_total_sales" class="float-right font-weight-bold">0</span></p>
                    <p class="clearfix">Đơn bán / Đơn trả <span class="float-right"><span id="summary_total_orders">0</span> / <span id="summary_total_returns">0</span></span></p>
                    <p class="clearfix">SL bán / SL trả <span class="float-right"><span id="summary_sales_qty">0</span> / <span id="summary_return_qty">0</span></span></p>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="card shadow mb-4">
                <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-warning"><i class="fas fa-warehouse"></i> Thông tin kho</h6></div>
                <div class="card-body">
                    <p class="clearfix">Tồn kho <span id="warehouse_inventory" class="float-right font-weight-bold">0</span></p>
                    <p class="clearfix">Hết Hàng <span id="warehouse_out_of_stock" class="float-right text-danger">0</span></p>
                    <p class="clearfix">Sắp hết hàng <span id="warehouse_low_stock" class="float-right text-warning">0</span></p>
                </div>
            </div>
        </div>
        <div class="col-lg-4">
            <div class="card shadow mb-4">
                <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-info"><i class="fas fa-box"></i> Thông tin sản phẩm</h6></div>
                <div class="card-body">
                    <p class="clearfix">Sản phẩm/Nhà sản xuất <span class="float-right"><span id="product_info_total">0</span> / <span id="product_info_manufacturers">0</span></span></p>
                    <p class="clearfix">Chưa làm giá bán <span id="product_info_no_sell_price" class="float-right">0</span></p>
                    <p class="clearfix">Chưa nhập giá mua <span id="product_info_no_import_price" class="float-right">0</span></p>
                </div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-6">
            <div class="card shadow mb-4">
                <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Doanh số 7 ngày gần nhất</h6></div>
                <div class="card-body"><canvas id="salesByDayChart"></canvas></div>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="card shadow mb-4">
                <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Top 10 sản phẩm bán chạy</h6></div>
                <div class="card-body"><canvas id="salesByProductChart"></canvas></div>
            </div>
        </div>
         <div class="col-lg-12">
            <div class="card shadow mb-4">
                <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Doanh số theo nhân viên</h6></div>
                <div class="card-body"><canvas id="salesByEmployeeChart"></canvas></div>
            </div>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-6">
            <div class="card shadow mb-4">
                <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Top 3 khách hàng mua nhiều</h6></div>
                <div class="card-body">
                    <ul class="list-group" id="topCustomersList"></ul>
                </div>
            </div>
        </div>
        <div class="col-lg-6">
            <div class="card shadow mb-4">
                <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Top 3 nhân viên doanh thu cao</h6></div>
                <div class="card-body">
                    <ul class="list-group" id="topEmployeesList"></ul>
                </div>
            </div>
        </div>
    </div>

</div>

<?php require_once __DIR__ . '/../../templates/footer.php'; ?>

<script>
$(document).ready(function() {
    const formatCurrency = (number) => new Intl.NumberFormat('vi-VN', { style: 'currency', currency: 'VND' }).format(number || 0);
    const formatNumber = (number) => new Intl.NumberFormat('vi-VN').format(number || 0);
    const chartColors = ['#4e73df', '#1cc88a', '#36b9cc', '#f6c23e', '#e74a3b', '#858796', '#f8f9fc', '#5a5c69', '#d1d3e2', '#4e73df'];

    $.ajax({
        url: '/quanlybanhang/ajax/dashboard_ajax.php',
        type: 'GET',
        dataType: 'json',
        data: { action: 'get_dashboard_data' },
        success: function(response) {
            if (response.status === 'success') {
                const data = response.data;
                
                $('#today_sales_amount').text(formatCurrency(data.today_sales_amount));
                $('#today_order_count').text(formatNumber(data.today_order_count));
                //$('#today_return_count').text(formatNumber(data//.today_return_count));
                $('#summary_total_sales').text(formatCurrency(data.summary_total_sales));
                $('#summary_total_orders').text(formatNumber(data.summary_total_orders));
                $('#summary_total_returns').text(formatNumber(data.summary_total_returns));
                $('#summary_sales_qty').text(formatNumber(data.summary_sales_qty));
                $('#summary_return_qty').text(formatNumber(data.summary_return_qty));
                $('#warehouse_inventory').text(formatNumber(data.warehouse_inventory));
                $('#warehouse_out_of_stock').text(formatNumber(data.warehouse_out_of_stock));
                $('#warehouse_low_stock').text(formatNumber(data.warehouse_low_stock));
                $('#product_info_total').text(formatNumber(data.product_info_total));
                $('#product_info_manufacturers').text(formatNumber(data.product_info_manufacturers));
                $('#product_info_no_sell_price').text(formatNumber(data.product_info_no_sell_price));
                $('#product_info_no_import_price').text(formatNumber(data.product_info_no_import_price));

                renderSalesByDayChart(data.charts.sales_by_day);
                renderSalesByProductChart(data.charts.sales_by_product);
                renderSalesByEmployeeChart(data.charts.sales_by_employee);

                renderTopList('#topCustomersList', data.tops.customers, 'customer_name', 'total_spent');
                renderTopList('#topEmployeesList', data.tops.employees, 'display_name', 'total_revenue');
            }
        },
        error: function() {
            alert('Không thể tải dữ liệu tổng quan. Vui lòng thử lại.');
        }
    });

    function renderSalesByDayChart(chartData) {
        if (!chartData || chartData.length === 0) return;
        const ctx = document.getElementById('salesByDayChart').getContext('2d');
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: chartData.map(d => d.sale_day),
                datasets: [{ label: 'Doanh số', data: chartData.map(d => d.daily_total), backgroundColor: chartColors[0] }]
            },
            options: { responsive: true, maintainAspectRatio: false, scales: { y: { ticks: { callback: function(value) { return formatNumber(value); } } } } }
        });
    }

    function renderSalesByProductChart(chartData) {
        if (!chartData || Object.keys(chartData).length === 0) return;
        const ctx = document.getElementById('salesByProductChart').getContext('2d');
        const labels = Object.values(chartData).map(d => d.name);
        const data = Object.values(chartData).map(d => d.total);
        new Chart(ctx, {
            type: 'doughnut',
            data: {
                labels: labels,
                datasets: [{ data: data, backgroundColor: chartColors }]
            },
            options: { responsive: true, maintainAspectRatio: false }
        });
    }
    
    function renderSalesByEmployeeChart(chartData) {
        if (!chartData || chartData.length === 0) return;
        const ctx = document.getElementById('salesByEmployeeChart').getContext('2d');
        new Chart(ctx, {
            type: 'bar',
            data: {
                labels: chartData.map(d => d.display_name),
                datasets: [{ label: 'Doanh số', data: chartData.map(d => d.employee_total), backgroundColor: chartColors }]
            },
            options: { responsive: true, maintainAspectRatio: false, scales: { y: { ticks: { callback: function(value) { return formatNumber(value); } } } } }
        });
    }

    function renderTopList(elementId, listData, nameKey, valueKey) {
        const listElement = $(elementId);
        listElement.empty();
        if(listData && listData.length > 0) {
            listData.forEach(item => {
                const listItem = `<li class="list-group-item d-flex justify-content-between align-items-center">
                                    ${item[nameKey]}
                                    <span class="badge badge-primary badge-pill">${formatCurrency(item[valueKey])}</span>
                                  </li>`;
                listElement.append(listItem);
            });
        } else {
            listElement.append('<li class="list-group-item">Không có dữ liệu.</li>');
        }
    }
});
</script>