<?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ó) để giữ lại trên form
$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');
?>
<style>
    #inventoryTable thead tr:first-child th {
        text-align: center;
        vertical-align: middle;
        border-bottom: 1px solid #e3e6f0;
    }
    #inventoryTable thead tr:nth-child(2) th {
        text-align: center;
        padding-top: 0.3rem;
        padding-bottom: 0.3rem;
        border-top: none;
    }
    .header-group { font-weight: bold; }
    .header-opening { color: #4e73df; }
    .header-imported { color: #1cc88a; }
    .header-exported { color: #36b9cc; }
    .header-closing { color: #f6c23e; }
</style>

<div class="container-fluid">
    <h1 class="h3 mb-2 text-gray-800">Báo cáo Tồn kho</h1>
    <div class="card shadow mb-4">
        <div class="card-body">
            <form id="filter-form">
                <div class="row">
                    <div class="col-md-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"><select id="category" name="category" class="form-control"><option value="0">-- Danh mục --</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"><select id="manufacturer" name="manufacturer" class="form-control"><option value="0">-- Nhà sản xuất --</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"><select id="store" name="store" class="form-control"><?php foreach($stores as $s) { echo "<option value='{$s['id']}' ".($store == $s['id'] ? 'selected' : '').">".htmlspecialchars($s['store_name'])."</option>"; } ?></select></div>
                </div>
                <div class="row mt-3">
                    <div class="col-md-3"><label>Từ ngày</label><input type="date" id="from" name="from" class="form-control" value="<?php echo htmlspecialchars($from); ?>"></div>
                    <div class="col-md-3"><label>Đến ngày</label><input type="date" id="to" name="to" class="form-control" value="<?php echo htmlspecialchars($to); ?>"></div>
                    <div class="col-md-3 d-flex align-items-end"><button type="submit" class="btn btn-primary"><i class="fas fa-search"></i> Xem</button></div>
                    <div class="col-md-3 d-flex align-items-end"><button type="button" id="export-excel" class="btn btn-success"><i class="fas fa-file-excel"></i> Xuất Excel</button></div>
                </div>
            </form>
        </div>
    </div>
    
    <div class="row mb-4">
        <div class="col-xl-3 col-md-6 mb-4"><div class="card border-left-primary shadow h-100 py-2"><div class="card-body"><div class="row no-gutters align-items-center"><div class="col mr-2"><div class="text-xs font-weight-bold text-primary text-uppercase mb-1">Tồn đầu kỳ</div><div class="h5 mb-0 font-weight-bold text-gray-800" id="total_opening">0</div></div><div class="col-auto"><i class="fas fa-calendar fa-2x text-gray-300"></i></div></div></div></div></div>
        <div class="col-xl-3 col-md-6 mb-4"><div class="card border-left-success shadow h-100 py-2"><div class="card-body"><div class="row no-gutters align-items-center"><div class="col mr-2"><div class="text-xs font-weight-bold text-success text-uppercase mb-1">SL Nhập</div><div class="h5 mb-0 font-weight-bold text-gray-800" id="total_imported">0</div></div><div class="col-auto"><i class="fas fa-arrow-down fa-2x text-gray-300"></i></div></div></div></div></div>
        <div class="col-xl-3 col-md-6 mb-4"><div class="card border-left-info shadow h-100 py-2"><div class="card-body"><div class="row no-gutters align-items-center"><div class="col mr-2"><div class="text-xs font-weight-bold text-info text-uppercase mb-1">SL Xuất</div><div class="h5 mb-0 font-weight-bold text-gray-800" id="total_exported">0</div></div><div class="col-auto"><i class="fas fa-arrow-up fa-2x text-gray-300"></i></div></div></div></div></div>
        <div class="col-xl-3 col-md-6 mb-4"><div class="card border-left-warning shadow h-100 py-2"><div class="card-body"><div class="row no-gutters align-items-center"><div class="col mr-2"><div class="text-xs font-weight-bold text-warning text-uppercase mb-1">Tồn cuối kỳ</div><div class="h5 mb-0 font-weight-bold text-gray-800" id="total_closing">0</div></div><div class="col-auto"><i class="fas fa-boxes fa-2x text-gray-300"></i></div></div></div></div></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">Tên sản phẩm</th>
                            <th rowspan="2">Quy cách</th>
                            <th colspan="2" class="header-opening header-group">Đầu kỳ</th>
                            <th colspan="2" class="header-imported header-group">Nhập trong kỳ</th>
                            <th colspan="2" class="header-exported header-group">Xuất trong kỳ</th>
                            <th colspan="2" class="header-closing header-group">Cuối kỳ</th>
                        </tr>
                        <tr>
                            <th class="header-opening">SL</th><th class="header-opening">Thành tiền</th>
                            <th class="header-imported">SL</th><th class="header-imported">Thành tiền</th>
                            <th class="header-exported">SL</th><th class="header-exported">Thành tiền</th>
                            <th class="header-closing">SL</th><th class="header-closing">Thành tiền</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php require_once __DIR__ . '/../../templates/footer.php'; ?>
<script>
$(document).ready(function() {
    function formatNumber(num) { 
        return (num || 0).toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,'); 
    }
    
    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 = $('#from').val(); 
                d.to = $('#to').val(); 
            },
            // --- THÊM DÒNG NÀY ĐỂ VÔ HIỆU HÓA CACHE ---
            "cache": false
        },
        "columns": [
            { "data": "prd_code" }, 
            { "data": "prd_name" }, 
            { "data": "prd_quycach", "className": "text-center" },
            { "data": "opening_stock_qty", "className": "text-right" }, 
            { "data": "opening_stock_amount", "className": "text-right", "render": function(data){return formatNumber(data);} },
            { "data": "imported_qty", "className": "text-right" }, 
            { "data": "imported_amount", "className": "text-right", "render": function(data){return formatNumber(data);} },
            { "data": "exported_qty", "className": "text-right" }, 
            { "data": "exported_amount", "className": "text-right", "render": function(data){return formatNumber(data);} },
            { "data": "closing_stock_qty", "className": "text-right font-weight-bold" }, 
            { "data": "closing_stock_amount", "className": "text-right font-weight-bold", "render": function(data){return formatNumber(data);} }
        ],
        "language": { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" },
        "searching": false, 
        "order": [],
        "drawCallback": function (settings) {
            var api = this.api();
            var json = api.ajax.json();
            if(json){
                $('#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));
            }
        }
    });
    
    $('#filter-form').on('submit', function(e) { 
        e.preventDefault(); 
        table.ajax.reload(); 
    });
    
    $('#export-excel').on('click', function() { 
        alert('Chức năng xuất Excel sẽ được phát triển ở bước tiếp theo.'); 
    });
});
</script>