<?php
require_once __DIR__ . '/../../templates/header.php';
// Tải các danh sách cần thiết cho bộ lọc
$categories_list = $conn->query("SELECT id, prd_group_name FROM cms_products_group ORDER BY prd_group_name ASC")->fetch_all(MYSQLI_ASSOC);
$manufacturers_list = $conn->query("SELECT id, prd_manuf_name FROM cms_products_manufacture ORDER BY prd_manuf_name ASC")->fetch_all(MYSQLI_ASSOC);
$units_list = $conn->query("SELECT id, prd_unit_name FROM cms_products_unit ORDER BY prd_unit_name ASC")->fetch_all(MYSQLI_ASSOC);
?>

<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">Danh sách sản phẩm</h1>
        <div>
            <button type="button" class="btn btn-warning btn-sm shadow-sm" data-toggle="modal" data-target="#importModal">
                <i class="fas fa-file-import fa-sm text-white-50"></i> Import dữ liệu
            </button>
            <a href="download_template.php" class="btn btn-info btn-sm shadow-sm">
                <i class="fas fa-file-download fa-sm text-white-50"></i> Tải file mẫu
            </a>
            <a href="export.php" class="btn btn-success btn-sm shadow-sm">
                <i class="fas fa-file-excel fa-sm text-white-50"></i> Xuất Excel
            </a>
            <a href="/quanlybanhang/modules/products/add.php" class="btn btn-primary btn-sm shadow-sm">
                <i class="fas fa-plus fa-sm text-white-50"></i> Tạo sản phẩm
            </a>
        </div>
    </div>

    <?php
    if (isset($_SESSION['import_message'])) {
        echo '<div class="alert alert-success alert-dismissible fade show" role="alert">
                ' . nl2br($_SESSION['import_message']) . '
                <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
              </div>';
        unset($_SESSION['import_message']);
    }
    ?>

    <div class="card shadow mb-4">
        <div class="card-body">
            <form id="filter-form" class="row">
                <div class="col-md-3 mb-2"><input type="text" class="form-control" id="search_term" placeholder="Mã hoặc tên sản phẩm..."></div>
                <div class="col-md-2 mb-2">
                    <select class="form-control" id="prd_status"><option value="">-- Tình trạng --</option><option value="1">Đang kinh doanh</option><option value="0">Ngừng kinh doanh</option></select>
                </div>
                <div class="col-md-2 mb-2">
                    <select class="form-control" id="category_id"><option value="">-- Danh mục --</option><?php foreach ($categories_list as $category) echo "<option value='{$category['id']}'>" . htmlspecialchars($category['prd_group_name']) . "</option>"; ?></select>
                </div>
                <div class="col-md-3 mb-2">
                    <select class="form-control" id="manufacturer_id"><option value="">-- Nhà sản xuất --</option><?php foreach ($manufacturers_list as $manufacturer) echo "<option value='{$manufacturer['id']}'>" . htmlspecialchars($manufacturer['prd_manuf_name']) . "</option>"; ?></select>
                </div>
                <div class="col-md-2 mb-2"><button type="submit" class="btn btn-primary btn-block"><i class="fas fa-search"></i> Tìm</button></div>
            </form>
        </div>
    </div>

    <div class="card shadow mb-4">
        <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Kết quả tìm kiếm</h6></div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered table-hover" id="productsTable" width="100%" cellspacing="0">
                    <thead>
                        <tr><th>Hình ảnh</th><th>Tên sản phẩm</th><th>Mã SP</th><th class="text-right">Tồn kho</th><th class="text-right">Giá bán lẻ</th><th class="text-right">Giá bán sỉ</th><th>Danh mục</th><th class="text-center">Hành động</th></tr>
                    </thead>
                    <tbody></tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="importModal" tabindex="-1" aria-labelledby="importModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="importModalLabel">Import sản phẩm từ Excel</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <form action="import.php" method="POST" enctype="multipart/form-data">
          <div class="modal-body">
            <p>Vui lòng chọn file Excel (.xlsx, .xls) để import. Hãy đảm bảo file tuân thủ đúng theo <a href="download_template.php">file mẫu</a>.</p>
            <div class="form-group">
                <label for="import_file">Chọn file:</label>
                <input type="file" class="form-control-file" name="import_file" id="import_file" required accept=".xlsx, .xls">
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Hủy</button>
            <button type="submit" class="btn btn-primary">Bắt đầu Import</button>
          </div>
      </form>
    </div>
  </div>
</div>

<div class="modal fade" id="editProductModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Chỉnh sửa sản phẩm</h5>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
            <div class="modal-body">
                <form id="editProductForm">
                    <input type="hidden" name="prd_id" id="edit_prd_id">
                    
                    <div class="form-group">
                        <label>Tên sản phẩm <span class="text-danger">*</span></label>
                        <input type="text" class="form-control" name="prd_name" id="edit_prd_name" required>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6"><div class="form-group"><label>Mã sản phẩm</label><input type="text" class="form-control" name="prd_code" id="edit_prd_code"></div></div>
                        <div class="col-md-6"><div class="form-group"><label>Giá vốn</label><input type="number" class="form-control" name="prd_origin_price" id="edit_prd_origin_price"></div></div>
                    </div>

                    <div class="row">
                        <div class="col-md-6"><div class="form-group"><label>Giá bán lẻ <span class="text-danger">*</span></label><input type="number" class="form-control" name="prd_sell_price" id="edit_prd_sell_price" required></div></div>
                        <div class="col-md-6"><div class="form-group"><label>Giá bán sỉ</label><input type="number" class="form-control" name="prd_sell_price2" id="edit_prd_sell_price2"></div></div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-6">
                             <div class="form-group">
                                <label>Danh mục</label>
                                <select class="form-control" name="prd_group_id" id="edit_prd_group_id">
                                    <?php foreach ($categories_list as $item) echo "<option value='{$item['id']}'>".htmlspecialchars($item['prd_group_name'])."</option>"; ?>
                                </select>
                            </div>
                        </div>
                         <div class="col-md-6">
                            <div class="form-group">
                                <label>Nhà sản xuất</label>
                                <select class="form-control" name="prd_manufacture_id" id="edit_prd_manufacture_id">
                                    <?php foreach ($manufacturers_list as $item) echo "<option value='{$item['id']}'>".htmlspecialchars($item['prd_manuf_name'])."</option>"; ?>
                                </select>
                            </div>
                        </div>
                    </div>

                     <div class="row">
                        <div class="col-md-4">
                            <div class="form-group">
                                <label>Đơn vị tính</label>
                                <select class="form-control" name="prd_unit_id" id="edit_prd_unit_id">
                                    <?php foreach ($units_list as $item) echo "<option value='{$item['id']}'>".htmlspecialchars($item['prd_unit_name'])."</option>"; ?>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-4"><div class="form-group"><label>Tên quy cách</label><input type="text" class="form-control" name="prd_tenquycach" id="edit_prd_tenquycach" placeholder="Vd: Thùng"></div></div>
                        <div class="col-md-4"><div class="form-group"><label>Quy cách (SL)</label><input type="number" class="form-control" name="prd_quycach" id="edit_prd_quycach" placeholder="Vd: 24"></div></div>
                    </div>

                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">Hủy</button>
                <button type="submit" class="btn btn-primary" form="editProductForm">Lưu thay đổi</button>
            </div>
        </div>
    </div>
</div>


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

<script>
$(document).ready(function() {
    var table = $('#productsTable').DataTable({
        "processing": true, "serverSide": true,
        "ajax": { "url": "/quanlybanhang/ajax/products_ajax.php", "type": "POST", "data": function(d) {
                d.search_term = $('#search_term').val();
                d.prd_status = $('#prd_status').val();
                d.category_id = $('#category_id').val();
                d.manufacturer_id = $('#manufacturer_id').val();
            }},
        "columns": [
            { "data": "prd_image_url", "orderable": false, "className": "text-center", "render": function(data) { return `<img src="${data || '/quanlybanhang/assets/img/no-image.png'}" alt="Ảnh" style="width: 50px; height: 50px; object-fit: cover;">`; } },
            { "data": "prd_name", "render": function(data, type, row) { return `<a href="/quanlybanhang/modules/products/add.php?id=${row.id}" class="font-weight-bold" title="Chỉnh sửa chi tiết">${data}</a>`; }},
            { "data": "prd_code" },
            { "data": "prd_inventory", "className": "text-right font-weight-bold" },
            { "data": "prd_sell_price", "className": "text-right", "render": $.fn.dataTable.render.number(',', '.', 0, '', ' đ') },
            { "data": "prd_sell_price2", "className": "text-right", "render": $.fn.dataTable.render.number(',', '.', 0, '', ' đ') },
            { "data": "prd_group_name" },
            { "data": "id", "orderable": false, "className": "text-center", "render": function(data) {
                return `<a href="#" class="btn btn-warning btn-sm btn-edit-modal" data-id="${data}" title="Sửa nhanh"><i class="fas fa-edit"></i></a>
                        <a href="#" class="btn btn-danger btn-sm btn-delete" data-id="${data}" title="Xóa"><i class="fas fa-trash"></i></a>`;
            }}
        ],
        "language": { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" },
        "pageLength": 10, "searching": false, "order": [[1, "asc"]]
    });

    $('#filter-form').on('submit', function(e) { e.preventDefault(); table.ajax.reload(); });

    // AJAX để lấy và điền dữ liệu vào MODAL
    $('#productsTable tbody').on('click', '.btn-edit-modal', function(e) {
        e.preventDefault();
        var productId = $(this).data('id');
        $.ajax({
            url: '/quanlybanhang/ajax/products_ajax.php', type: 'GET', dataType: 'json',
            data: { action: 'get_product_details', product_id: productId },
            success: function(response) {
                if (response.status === 'success') {
                    var data = response.data;
                    // AJAX sẽ điền dữ liệu vào các ID này
                    $('#edit_prd_id').val(data.ID);
                    $('#edit_prd_name').val(data.prd_name);
                    $('#edit_prd_code').val(data.prd_code);
                    $('#edit_prd_origin_price').val(data.prd_origin_price);
                    $('#edit_prd_sell_price').val(data.prd_sell_price);
                    $('#edit_prd_sell_price2').val(data.prd_sell_price2);
                    $('#edit_prd_group_id').val(data.prd_group_id);
                    $('#edit_prd_manufacture_id').val(data.prd_manufacture_id);
                    $('#edit_prd_unit_id').val(data.prd_unit_id);
                    $('#edit_prd_tenquycach').val(data.prd_tenquycach);
                    $('#edit_prd_quycach').val(data.prd_quycach);
                    
                    $('#editProductModal').modal('show');
                } else { alert(response.message); }
            }
        });
    });

    // AJAX để LƯU dữ liệu từ MODAL
    // Cần phải lắng nghe sự kiện submit trên #editProductModal thay vì #editProductForm
    // vì form được load động
    $('#editProductModal').on('submit', '#editProductForm', function(e) {
        e.preventDefault();
        $.ajax({
            url: '/quanlybanhang/ajax/products_ajax.php', type: 'POST', dataType: 'json',
            data: $(this).serialize() + '&action=edit_product',
            success: function(response) {
                alert(response.message);
                if (response.status === 'success') {
                    $('#editProductModal').modal('hide');
                    table.ajax.reload(null, false);
                }
            }
        });
    });
    
    // AJAX để XÓA sản phẩm
    $('#productsTable tbody').on('click', '.btn-delete', function(e) {
        e.preventDefault();
        if (confirm('Bạn có chắc chắn muốn xóa sản phẩm này?')) {
            $.ajax({
                url: '/quanlybanhang/ajax/products_ajax.php', type: 'POST', dataType: 'json',
                data: { action: 'delete_product', product_id: $(this).data('id') },
                success: function(response) {
                    alert(response.message);
                    if (response.status === 'success') {
                        table.ajax.reload(null, false);
                    }
                }
            });
        }
    });
});
</script>