<?php
require_once __DIR__ . '/../../templates/header.php';
$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);
?>

<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:1px solid #e3e6f0; border-radius:0.75rem; transition:all .2s ease-in-out; box-shadow:0 .15rem 1.75rem 0 rgba(58,59,69,.15)!important; }
    .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; }
    .filter-card { border-left:4px solid #4e73df; }
    .select2-container--bootstrap-5 .select2-selection { padding: .43rem 1rem; height: calc(1.5em + .75rem + 2px); }
    #productsTable thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; }
    #productsTable tbody tr:nth-child(even) { background-color: #f8f9fc; }
    #productsTable tbody tr:hover { background-color: #eaecf4; }
    .table-footer-summary { padding: 1rem; font-weight: bold; background-color: #f8f9fc; border-top: 1px solid #e3e6f0; }
    .select2-container--bootstrap-5 .select2-selection--single .select2-selection__rendered { font-size: 0.875rem; }
    #editProductModal .modal-header, #quickManageModal .modal-header { background-color: #f8f9fc; border-bottom: 1px solid #e3e6f0; }
    #editProductModal .modal-title, #quickManageModal .modal-title { font-weight: 600; color: #3a3b45; }
    #editProductModal .form-label { font-weight: 500; color: #6c757d; }
    #quickManageModal { z-index: 1060; }
    .icon-status { color: #d63384; font-size: 1.1em; }
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Quản lý Sản phẩm</h1>
    <div class="row mb-4">
        <div class="col-xl-6 col-md-12 mb-4"><div class="card summary-card"><div class="card-body"><div class="text-content"><div class="label" style="color: #1cc88a;">Tổng giá trị tồn kho</div><div class="value" id="summary-inventory-value" style="color: #1cc88a;">0 ₫</div></div><div class="icon-circle" style="background-color: #1cc88a;"><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: #4e73df;">Tổng số sản phẩm</div><div class="value" id="summary-total-products">0</div></div><div class="icon-circle" style="background-color: #4e73df;"><i class="fas fa-boxes"></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: #36b9cc;">Tổng số nhà sản xuất</div><div class="value" id="summary-total-manufacturers">0</div></div><div class="icon-circle" style="background-color: #36b9cc;"><i class="fas fa-industry"></i></div></div></div></div>
    </div>
    
    <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex justify-content-between align-items-center flex-wrap">
            <h6 class="m-0 font-weight-bold text-primary">Danh sách sản phẩm</h6>
            <div class="btn-group btn-group-sm mt-2 mt-md-0">
                <button type="button" class="btn btn-warning btn-sm" data-bs-toggle="modal" data-bs-target="#importModal"><i class="fas fa-file-import fa-sm"></i> Import</button>
                <a href="download_template.php" class="btn btn-info btn-sm"><i class="fas fa-file-download fa-sm"></i> Tải mẫu</a>
                <a href="print_barcode.php" class="btn btn-secondary btn-sm"><i class="fas fa-barcode fa-sm"></i> In mã vạch</a>
                <a href="export.php" class="btn btn-success btn-sm"><i class="fas fa-file-excel fa-sm"></i> Xuất Excel</a>
                <a href="/quanlybanhang/modules/products/add.php" class="btn btn-primary btn-sm"><i class="fas fa-plus fa-sm"></i> Tạo sản phẩm</a>
            </div>
        </div>
        <div class="card-body">
            <div class="card mb-4 filter-card">
                <div class="card-body">
                    <form id="filter-form" class="row gx-3 align-items-center">
                        <div class="col-md-3"><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"><select class="form-control" id="prd_status" data-placeholder="Tất cả tình trạng"><option value=""></option><option value="1">Đang kinh doanh</option><option value="0">Ngừng kinh doanh</option></select></div>
                        <div class="col-md-3"><select class="form-control" id="category_id" data-placeholder="Tất cả danh mục"><option value=""></option><?php foreach ($categories_list as $category) echo "<option value='{$category['id']}'>" . htmlspecialchars($category['prd_group_name']) . "</option>"; ?></select></div>
                        <div class="col-md-2"><select class="form-control" id="manufacturer_id" data-placeholder="Tất cả nhà sản xuất"><option value=""></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"><button type="submit" class="btn btn-primary w-100"><i class="fas fa-search fa-sm"></i> Tìm</button></div>
                    </form>
                </div>
            </div>
            <div class="table-responsive">
                <table class="table table-hover" id="productsTable" width="100%" cellspacing="0"></table>
            </div>
        </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" id="editProductModalLabel">Chỉnh sửa sản phẩm</h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <form id="editProductForm">
                    <input type="hidden" name="prd_id" id="edit_prd_id">
                    <div class="mb-3"><label for="edit_prd_name" class="form-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-4 mb-3"><label for="edit_prd_code" class="form-label">Mã sản phẩm</label><input type="text" class="form-control" name="prd_code" id="edit_prd_code"></div>
                        <div class="col-md-4 mb-3"><label for="edit_prd_inventory" class="form-label">Tồn kho</label><input type="text" class="form-control" name="prd_inventory" id="edit_prd_inventory" readonly></div>
                        <div class="col-md-4 mb-3"><label for="edit_prd_origin_price" class="form-label">Giá vốn</label><input type="number" class="form-control" name="prd_origin_price" id="edit_prd_origin_price"></div>
                        <div class="col-md-6 mb-3"><label for="edit_prd_sell_price" class="form-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 class="col-md-6 mb-3"><label for="edit_prd_sell_price2" class="form-label">Giá bán sỉ</label><input type="number" class="form-control" name="prd_sell_price2" id="edit_prd_sell_price2"></div>
                    </div>
                    <div class="row">
                        <div class="col-md-4 mb-3"><label for="edit_prd_group_id" class="form-label">Danh mục</label><div class="input-group"><select class="form-select" name="prd_group_id" id="edit_prd_group_id" style="width: 100%;"><?php foreach ($categories_list as $item) echo "<option value='{$item['id']}'>".htmlspecialchars($item['prd_group_name'])."</option>"; ?></select><button class="btn btn-outline-primary btn-quick-manage" type="button" data-type="category" data-title="Quản lý Danh mục"><i class="fas fa-plus"></i></button></div></div>
                        <div class="col-md-4 mb-3"><label for="edit_prd_manufacture_id" class="form-label">Nhà sản xuất</label><div class="input-group"><select class="form-select" name="prd_manufacture_id" id="edit_prd_manufacture_id" style="width: 100%;"><?php foreach ($manufacturers_list as $item) echo "<option value='{$item['id']}'>".htmlspecialchars($item['prd_manuf_name'])."</option>"; ?></select><button class="btn btn-outline-primary btn-quick-manage" type="button" data-type="manufacturer" data-title="Quản lý Nhà sản xuất"><i class="fas fa-plus"></i></button></div></div>
                        <div class="col-md-4 mb-3"><label for="edit_prd_unit_id" class="form-label">Đơn vị tính</label><div class="input-group"><select class="form-select" name="prd_unit_id" id="edit_prd_unit_id" style="width: 100%;"><?php foreach ($units_list as $item) echo "<option value='{$item['id']}'>".htmlspecialchars($item['prd_unit_name'])."</option>"; ?></select><button class="btn btn-outline-primary btn-quick-manage" type="button" data-type="unit" data-title="Quản lý Đơn vị tính"><i class="fas fa-plus"></i></button></div></div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Hủy</button>
                <button type="submit" class="btn btn-primary" form="editProductForm">Lưu thay đổi</button>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="quickManageModal" tabindex="-1"><div class="modal-dialog modal-lg"><div class="modal-content"><div class="modal-header"><h5 class="modal-title" id="quickManageModalTitle"></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div><div class="modal-body"><ul class="nav nav-tabs"><li class="nav-item"><a class="nav-link active" data-bs-toggle="tab" href="#list-tab-pane">Danh sách</a></li><li class="nav-item"><a class="nav-link" data-bs-toggle="tab" href="#add-tab-pane">Tạo mới</a></li></ul><div class="tab-content pt-3"><div class="tab-pane fade show active" id="list-tab-pane"><div class="table-responsive"><table class="table table-hover"><thead><tr><th>ID</th><th>Tên</th><th class="text-center">Hành động</th></tr></thead><tbody id="modal-item-list"></tbody></table></div></div><div class="tab-pane fade" id="add-tab-pane"><form id="modal-add-form"><div class="mb-3"><label class="form-label">Nhập tên mới:</label><input type="text" class="form-control" id="modal-new-name" required></div><button type="submit" class="btn btn-primary">Lưu</button></form></div></div></div></div></div></div>

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

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.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() {
    $('#prd_status, #category_id, #manufacturer_id').select2({ theme: "bootstrap-5", allowClear: true });
    $('#edit_prd_group_id, #edit_prd_manufacture_id, #edit_prd_unit_id').select2({ theme: "bootstrap-5", dropdownParent: $('#editProductModal') });

    var table = $('#productsTable').DataTable({
        "processing": true, "serverSide": true,
        "ajax": { "url": "/quanlybanhang/ajax/products_ajax.php", "type": "POST", "data": function(d) { d.action = 'get_products_list'; 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", "title":"Ảnh", "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;border-radius:4px;">`; } },
            { "data": "prd_name", "title":"Tên sản phẩm", "render": function(data, type, row) { return `<a href="/quanlybanhang/modules/products/add.php?id=${row.id}" class="fw-bold" title="Chỉnh sửa chi tiết">${data}</a>`; }},
            { "data": "prd_code", "title":"Mã SP" }, { "data": "prd_inventory", "title":"Tồn kho", "className": "text-end fw-bold" },
            { "data": "prd_sell_price", "title":"Giá lẻ", "className": "text-end", "render": data => (parseFloat(data) || 0).toLocaleString('vi-VN') + ' ₫' },
            { "data": "prd_sell_price2", "title":"Giá sỉ", "className": "text-end", "render": data => (parseFloat(data) || 0).toLocaleString('vi-VN') + ' ₫' },
            { "data": "prd_group_name", "title":"Danh mục" }, { "data": "prd_manuf_name", "title":"Nhà sản xuất" },
            { "data": "id", "title":"Hành động", "orderable": false, "className": "text-center", "render": function(data, type, row) {
                let statusBtn = '';
                if (row.prd_status == 1) {
                    statusBtn = `<button class="btn btn-light btn-sm btn-toggle-status" data-id="${data}" data-status="1" title="Ngừng kinh doanh"><i class="fas fa-pause icon-status"></i></button>`;
                } else {
                    statusBtn = `<button class="btn btn-light btn-sm btn-toggle-status" data-id="${data}" data-status="0" title="Kinh doanh lại"><i class="fas fa-sync-alt icon-status"></i></button>`;
                }
                return `<div class="btn-group btn-group-sm">${statusBtn}<button class="btn btn-warning btn-edit-modal" data-id="${data}" title="Sửa nhanh"><i class="fas fa-edit"></i></button><button class="btn btn-danger btn-delete" data-id="${data}" data-name="${row.prd_name}" title="Xóa"><i class="fas fa-trash"></i></button></div>`;
            }}
        ],
        "language": { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" },
        "pageLength": 10, "searching": false, "order": [[1, "asc"]],
        "dom": "t<'d-flex justify-content-between align-items-center'<'table-footer-summary'>p>",
        "drawCallback": function(settings) {
            var json = this.api().ajax.json();
            if (json && json.summary) {
                const s = json.summary; const format = (num) => (parseFloat(num) || 0).toLocaleString('vi-VN');
                $('#summary-inventory-value').text(format(s.total_inventory_value) + ' ₫');
                $('#summary-total-products').text(format(s.total_products));
                $('#summary-total-manufacturers').text(format(s.total_manufacturers));
                $('.table-footer-summary').html(`SL sản phẩm/SL nhà sản xuất: <span class="text-danger">${format(s.total_products)} / ${format(s.total_manufacturers)}</span>`);
            }
        }
    });

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

    $('#productsTable tbody').on('click', '.btn-toggle-status', function(e) {
        e.preventDefault();
        const productId = $(this).data('id');
        const currentStatus = $(this).data('status');
        const message = currentStatus == 1 ? 'Bạn có chắc muốn NGỪNG KINH DOANH sản phẩm này?' : 'Bạn có chắc muốn KINH DOANH LẠI sản phẩm này?';

        if (confirm(message)) {
            $.ajax({
                url: '/quanlybanhang/ajax/products_ajax.php',
                type: 'POST',
                dataType: 'json',
                data: {
                    action: 'toggle_product_status',
                    product_id: productId,
                    current_status: currentStatus
                },
                success: function(response) {
                    alert(response.message);
                    if (response.status === 'success') {
                        table.ajax.reload(null, false);
                    }
                },
                error: function() {
                    alert('Đã xảy ra lỗi kết nối. Vui lòng thử lại.');
                }
            });
        }
    });

    $('#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;
                    $('#edit_prd_id').val(data.ID); $('#edit_prd_name').val(data.prd_name); $('#edit_prd_code').val(data.prd_code);
                    $('#edit_prd_inventory').val(data.prd_sls); $('#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).trigger('change');
                    $('#edit_prd_manufacture_id').val(data.prd_manufacture_id).trigger('change');
                    $('#edit_prd_unit_id').val(data.prd_unit_id).trigger('change');
                    var editModal = new bootstrap.Modal(document.getElementById('editProductModal'));
                    editModal.show();
                } else { alert(response.message); }
            }
        });
    });

    $('#editProductForm').on('submit', 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') {
                    bootstrap.Modal.getInstance(document.getElementById('editProductModal')).hide();
                    table.ajax.reload(null, false);
                }
            }
        });
    });

    $('#productsTable tbody').on('click', '.btn-delete', function(e) {
        e.preventDefault();
        var productName = $(this).data('name');
        if (confirm(`Bạn có chắc chắn muốn xóa sản phẩm "${productName}"?`)) {
            $.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); }
                }
            });
        }
    });

    let currentType = '';
    const quickManageModal = new bootstrap.Modal(document.getElementById('quickManageModal'));

    $('#editProductModal').on('click', '.btn-quick-manage', function() {
        currentType = $(this).data('type');
        $('#quickManageModalTitle').text($(this).data('title'));
        loadModalList();
        quickManageModal.show();
    });

    function loadModalList() {
        $.ajax({
            url: '/quanlybanhang/ajax/quick_manage_ajax.php', type: 'GET', data: { action: 'get_list', type: currentType },
            success: function(res) {
                const listBody = $('#modal-item-list'); listBody.empty();
                if (res.status === 'success' && res.data.length > 0) {
                    res.data.forEach(item => {
                        listBody.append(`<tr data-id="${item.id}" data-name="${item.name}"><td>${item.id}</td><td><span class="view-mode">${item.name}</span><input type="text" class="form-control form-control-sm edit-mode" value="${item.name}" style="display:none;"></td><td class="text-center" style="width:120px;"><div class="btn-group btn-group-sm"><button class="btn btn-warning btn-edit-quick view-mode"><i class="fas fa-edit"></i></button><button class="btn btn-danger btn-delete-quick view-mode"><i class="fas fa-trash"></i></button><button class="btn btn-success btn-save-quick edit-mode" style="display:none;"><i class="fas fa-check"></i></button><button class="btn btn-secondary btn-cancel-quick edit-mode" style="display:none;"><i class="fas fa-times"></i></button></div></td></tr>`);
                    });
                } else { listBody.append('<tr><td colspan="3" class="text-center">Chưa có dữ liệu.</td></tr>'); }
            }
        });
    }

    $('#modal-add-form').on('submit', function(e) { e.preventDefault();
        const newName = $('#modal-new-name').val().trim();
        if(newName === '') { alert('Tên không được để trống.'); return; }
        $.ajax({
            url: '/quanlybanhang/ajax/quick_manage_ajax.php', type: 'POST', dataType: 'json', data: { action: 'add', type: currentType, name: newName },
            success: function(res) {
                if (res.status === 'success') {
                    $('#modal-new-name').val('');
                    loadModalList();
                    refreshMainDropdowns(res.new_item.id);
                } else { alert(res.message); }
            }
        });
    });

    $('#modal-item-list').on('click', '.btn-edit-quick', function() { $(this).closest('tr').find('.view-mode, .edit-mode').toggle(); });
    $('#modal-item-list').on('click', '.btn-cancel-quick', function() { $(this).closest('tr').find('.view-mode, .edit-mode').toggle(); });

    $('#modal-item-list').on('click', '.btn-delete-quick', function() {
        if (confirm('Bạn có chắc chắn muốn xóa mục này?')) {
            const id = $(this).closest('tr').data('id');
            $.ajax({
                url: '/quanlybanhang/ajax/quick_manage_ajax.php', type: 'POST', data: { action: 'delete', type: currentType, id: id }, dataType: 'json',
                success: function(res) {
                    alert(res.message);
                    if (res.status === 'success') {
                        loadModalList();
                        refreshMainDropdowns();
                    }
                }
            });
        }
    });

    $('#modal-item-list').on('click', '.btn-save-quick', function() {
        const tr = $(this).closest('tr');
        const id = tr.data('id');
        const newName = tr.find('.edit-mode input').val().trim();
        if (newName === '') { alert('Tên không được để trống.'); return; }
        $.ajax({
            url: '/quanlybanhang/ajax/quick_manage_ajax.php', type: 'POST', dataType: 'json',
            data: { action: 'update', type: currentType, id: id, name: newName },
            success: function(res) {
                if(res.status === 'success') {
                    tr.data('name', newName);
                    tr.find('span.view-mode').text(newName);
                    tr.find('.view-mode, .edit-mode').toggle();
                    refreshMainDropdowns(id);
                }
                alert(res.message);
            }
        });
    });

    function refreshMainDropdowns(selectedId = null) {
        const dropdownMappings = { 'category': '#edit_prd_group_id', 'manufacturer': '#edit_prd_manufacture_id', 'unit': '#edit_prd_unit_id' };
        const dropdown = $(dropdownMappings[currentType]);
        if (!dropdown.length) return;

        $.ajax({
            url: '/quanlybanhang/ajax/quick_manage_ajax.php', type: 'GET', data: { action: 'get_list', type: currentType },
            success: function(res) {
                if (res.status === 'success') {
                    const currentValue = selectedId || dropdown.val();
                    dropdown.empty();
                    res.data.forEach(item => { dropdown.append($('<option>', { value: item.id, text: item.name })); });
                    dropdown.val(currentValue).trigger('change');
                }
            }
        });
    }
});
</script>