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

// Lấy dữ liệu cho các bộ lọc
$categories = $conn->query("SELECT id, prd_group_name FROM cms_products_group ORDER BY prd_group_name ASC")->fetch_all(MYSQLI_ASSOC);
$manufacturers = $conn->query("SELECT id, prd_manuf_name FROM cms_products_manufacture ORDER BY prd_manuf_name ASC")->fetch_all(MYSQLI_ASSOC);
$stores = $conn->query("SELECT id, store_name FROM cms_stores ORDER BY store_name ASC")->fetch_all(MYSQLI_ASSOC);

// Lấy giá trị filter đã chọn (nếu có)
$q = $_GET['q'] ?? '';
$category = $_GET['category'] ?? 0;
$manufacturer = $_GET['manufacturer'] ?? 0;
$store = $_GET['store'] ?? 1;
$from = $_GET['from'] ?? date('Y-m-01');
$to = $_GET['to'] ?? date('Y-m-t');
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" />
<style>
    .summary-card { background-color:#fff; border:none; border-radius:0.75rem; box-shadow:0 .15rem 1.75rem 0 rgba(58,59,69,.15)!important; transition:all .2s ease-in-out; }
    .summary-card:hover { transform: translateY(-5px); }
    .summary-card .card-body { padding: 1.5rem; display: flex; justify-content: space-between; align-items: center; }
    .summary-card .text-content .label { font-size:0.8rem; font-weight:700; text-transform:uppercase; margin-bottom:0.25rem; }
    .summary-card .text-content .value { font-size:1.75rem; font-weight:700; }
    .summary-card .icon-circle { width:50px; height:50px; border-radius:50%; display:flex; align-items:center; justify-content:center; color:white; font-size:1.5rem; }
    
    #inventoryTable thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; text-align: center; }
    #inventoryTable tbody tr { border-bottom: 1px solid #e3e6f0; }
    #inventoryTable tbody tr:nth-child(even) { background-color: #f8f9fc; }
    #inventoryTable tbody tr:hover { background-color: #eaecf4; }
    #inventoryTable th, #inventoryTable td { white-space: nowrap; }

    /* Sửa lỗi màu nền cho các cột */
    #inventoryTable td.col-opening { background-color: #e7f0ff !important; }
    #inventoryTable td.col-imported { background-color: #e7f5ec !important; }
    #inventoryTable td.col-exported { background-color: #eaf9fb !important; }
    #inventoryTable td.col-closing { background-color: #fff8e4 !important; font-weight: bold; }
    
    .dataTables_wrapper .dataTables_info { padding-top: 0.85em; }
    .total-value-footer {
        padding: 1rem;
        background-color: #e0efff; /* Màu xanh nhạt hơn */
        color: #4e73df; /* Chuyển màu chữ sang xanh đậm để dễ đọc */
        font-size: 1.2rem;
        font-weight: bold;
        text-align: right;
        border-radius: 0 0 0.35rem 0.35rem;
        margin-top: -1px;
    }
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Báo cáo Tồn kho</h1>

    <div class="row">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card"><div class="card-body">
                <div class="text-content"><div class="label" style="color:#4e73df;">Tồn đầu kỳ</div><div class="value text-gray-800" id="total_opening">0</div></div>
                <div class="icon-circle" style="background-color:#4e73df;"><i class="fas fa-warehouse"></i></div>
            </div></div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card"><div class="card-body">
                <div class="text-content"><div class="label" style="color:#1cc88a;">SL Nhập</div><div class="value text-gray-800" id="total_imported">0</div></div>
                <div class="icon-circle" style="background-color:#1cc88a;"><i class="fas fa-arrow-circle-down"></i></div>
            </div></div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card"><div class="card-body">
                <div class="text-content"><div class="label" style="color:#e74a3b;">SL Xuất</div><div class="value text-gray-800" id="total_exported">0</div></div>
                <div class="icon-circle" style="background-color:#e74a3b;"><i class="fas fa-arrow-circle-up"></i></div>
            </div></div>
        </div>
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card summary-card"><div class="card-body">
                <div class="text-content"><div class="label" style="color:#f6c23e;">Tồn cuối kỳ</div><div class="value text-gray-800" id="total_closing">0</div></div>
                <div class="icon-circle" style="background-color:#f6c23e;"><i class="fas fa-cubes"></i></div>
            </div></div>
        </div>
    </div>

    <div class="card shadow mb-4">
        <div class="card-body">
            <form id="filter-form">
                <div class="row align-items-end">
                    <div class="col-md-3 mb-3"><input type="text" id="q" name="q" class="form-control" placeholder="Tên hoặc mã SP..." value="<?php echo htmlspecialchars($q); ?>"></div>
                    <div class="col-md-2 mb-3"><select id="category" name="category" data-placeholder="-- Danh mục --"><option value=""></option><?php foreach($categories as $cat) { echo "<option value='{$cat['id']}' ".($category == $cat['id'] ? 'selected' : '').">".htmlspecialchars($cat['prd_group_name'])."</option>"; } ?></select></div>
                    <div class="col-md-2 mb-3"><select id="manufacturer" name="manufacturer" data-placeholder="-- Nhà sản xuất --"><option value=""></option><?php foreach($manufacturers as $man) { echo "<option value='{$man['id']}' ".($manufacturer == $man['id'] ? 'selected' : '').">".htmlspecialchars($man['prd_manuf_name'])."</option>"; } ?></select></div>
                    <div class="col-md-2 mb-3"><select id="store" name="store" data-placeholder="-- Chọn kho --"><?php foreach($stores as $s) { echo "<option value='{$s['id']}' ".($store == $s['id'] ? 'selected' : '').">".htmlspecialchars($s['store_name'])."</option>"; } ?></select></div>
                    <div class="col-md-3 mb-3"><input type="text" class="form-control" name="from" placeholder="Từ ngày" value="<?php echo htmlspecialchars($from); ?>"></div>
                    <div class="col-md-3 mb-3"><input type="text" class="form-control" name="to" placeholder="Đến ngày" value="<?php echo htmlspecialchars($to); ?>"></div>
                    <div class="col-md-2 mb-3"><button type="submit" class="btn btn-primary w-100"><i class="fas fa-search fa-sm mr-2"></i> Xem</button></div>
                    <div class="col-md-2 mb-3"><button type="button" id="export-excel" class="btn btn-success w-100"><i class="fas fa-file-excel fa-sm mr-2"></i> Xuất Excel</button></div>
                </div>
            </form>
        </div>
    </div>
    
    <div class="card shadow mb-4">
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" id="inventoryTable" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th rowspan="2">Mã SP</th>
                            <th rowspan="2" style="text-align: left;">Tên sản phẩm</th>
                            <th colspan="2">Đầu kỳ</th>
                            <th colspan="2">Nhập trong kỳ</th>
                            <th colspan="2">Xuất trong kỳ</th>
                            <th colspan="2">Cuối kỳ</th>
                        </tr>
                        <tr>
                            <th>SL</th><th>Thành tiền</th>
                            <th>SL</th><th>Thành tiền</th>
                            <th>SL</th><th>Thành tiền</th>
                            <th>SL</th><th>Thành tiền</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
             <div id="total-inventory-value-footer" class="total-value-footer" style="display: none;"></div>
        </div>
    </div>
</div>

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

<script src="https://cdn.jsdelivr.net/npm/flatpickr"></script>
<script src="https://npmcdn.com/flatpickr/dist/l10n/vn.js"></script>
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    function formatNumber(num) { 
        return parseFloat(num || 0).toLocaleString('vi-VN');
    }

    $('#category, #manufacturer, #store').select2({ theme: "bootstrap-5", allowClear: true });
    const fp_config = { locale: "vn", altInput: true, altFormat: "d/m/Y", dateFormat: "Y-m-d" };
    flatpickr('input[name="from"]', { ...fp_config, defaultDate: "<?php echo $from; ?>" });
    flatpickr('input[name="to"]', { ...fp_config, defaultDate: "<?php echo $to; ?>" });
    
    var table = $('#inventoryTable').DataTable({
        "processing": true, 
        "serverSide": true,
        "ajax": { 
            "url": "/quanlybanhang/ajax/inventory_ajax.php", 
            "type": "POST", 
            "data": function(d) { 
                d.q = $('#q').val(); 
                d.category = $('#category').val(); 
                d.manufacturer = $('#manufacturer').val(); 
                d.store = $('#store').val(); 
                d.from = $('input[name="from"]').val(); 
                d.to = $('input[name="to"]').val(); 
            },
            "cache": false
        },
        "columns": [
            { 
                "data": "prd_code",
                "render": function(data, type, row) {
                    return `<a href="chi_tiet_san_pham.php?id=${row.id}">${data}</a>`;
                }
            }, 
            { 
                "data": "prd_name",
                "className": "text-left",
                "render": function(data, type, row) {
                    return `<a href="chi_tiet_san_pham.php?id=${row.id}">${data}</a>`;
                }
            }, 
            { "data": "opening_stock_qty", "className": "text-right col-opening" }, 
            { "data": "opening_stock_amount", "className": "text-right col-opening", "render": formatNumber },
            { "data": "imported_qty", "className": "text-right col-imported" }, 
            { "data": "imported_amount", "className": "text-right col-imported", "render": formatNumber },
            { "data": "exported_qty", "className": "text-right col-exported" }, 
            { "data": "exported_amount", "className": "text-right col-exported", "render": formatNumber },
            { "data": "closing_stock_qty", "className": "text-right col-closing" }, 
            { "data": "closing_stock_amount", "className": "text-right col-closing", "render": formatNumber }
        ],
        "language": { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" },
        "searching": false, 
        "ordering": false,
        "drawCallback": function (settings) {
            var api = this.api();
            var json = api.ajax.json();
            if(json){
                // Sửa lại key cho đúng với file ajax gốc của bạn
                $('#total_opening').text(formatNumber(json.total_opening));
                $('#total_imported').text(formatNumber(json.total_imported));
                $('#total_exported').text(formatNumber(json.total_exported));
                $('#total_closing').text(formatNumber(json.total_closing));

                if(json.total_inventory_value !== undefined) {
                    $('#total-inventory-value-footer').html(`Tổng giá trị tồn kho: ${formatNumber(json.total_inventory_value)}`).show();
                } else {
                    $('#total-inventory-value-footer').hide();
                }
            }
        }
    });
    
    $('#filter-form').on('submit', function(e) { 
        e.preventDefault(); 
        table.ajax.reload(); 
    });
    
    $('#export-excel').on('click', function() { 
        var params = $('#filter-form').serialize();
        window.location.href = '/quanlybanhang/export/excel_inventory.php?' + params;
    });
});
</script>