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

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<style>
    /* === THẺ THỐNG KÊ & BỘ LỌC === */
    .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); box-shadow:0 .5rem 2rem 0 rgba(58,59,69,.2)!important; }
    .summary-card .card-body { display:flex; justify-content:space-between; align-items:center; padding:1.5rem; }
    .summary-card .text-content .label { color:#858796; font-size:0.8rem; font-weight:700; text-transform:uppercase; margin-bottom:0.25rem; }
    .summary-card .text-content .value { color:#3a3b45; font-size:1.75rem; font-weight:700; }
    .summary-card .icon-circle { display:flex; align-items:center; justify-content:center; width:50px; height:50px; border-radius:50%; color:white; font-size:1.5rem; }
    .summary-card .icon-circle.bg-primary { background-color:#4e73df; }
    .summary-card .icon-circle.bg-success { background-color:#1cc88a; }
    .summary-card .icon-circle.bg-danger { background-color:#e74a3b; }
    .filter-card { border-left:4px solid #4e73df; }
    .filter-card .card-header { background-color:transparent; border-bottom:1px solid #e3e6f0; font-weight:700; color:#4e73df; }
    .flatpickr-calendar { font-family:"Nunito",sans-serif; box-shadow:0 0.5rem 1rem rgba(0,0,0,0.15); border-radius:0.5rem; }
    .flatpickr-day.selected { background:#4e73df; border-color:#4e73df; }
    input.form-control[readonly] { background-color:#fff !important; cursor:pointer; }

    /* === NÂNG CẤP GIAO DIỆN BẢNG DANH SÁCH ĐƠN HÀNG === */
    #ordersTable thead th {
        background-color: #4e73df !important;
        color: #ffffff !important;
        font-weight: bold;
        vertical-align: middle;
    }
    #ordersTable tbody tr:nth-child(even) { background-color: #f8f9fc; }
    #ordersTable tbody tr:hover { background-color: #eaecf4; }
    .badge { font-size: 0.8em; padding: 0.5em 0.75em; }

    /* === CSS CHO PHẦN CHI TIẾT ĐƠN HÀNG (khi bung ra) === */
    .child-row-container { padding:1rem; background-color:#f8f9fc; border-left:3px solid #4e73df; margin:5px 0; }
    .child-summary { margin-bottom:1rem; display:flex; flex-wrap:wrap; gap:8px; }
    .child-summary span { padding:6px 12px; border-radius:16px; color:white; font-size:.9em; font-weight:500; display:inline-flex; align-items:center; box-shadow:0 2px 4px rgba(0,0,0,.1); white-space:nowrap; }
    .child-summary strong { color:white; margin-left:4px; }
    .child-summary span:nth-child(1) { background-color:#4e73df; }
    .child-summary span:nth-child(2) { background-color:#1cc88a; }
    .child-summary span:nth-child(3) { background-color:#f6c23e; }
    .child-summary span:nth-child(4) { background-color:#36b9cc; }
    .child-summary span:nth-child(5) { background-color:#e74a3b; }
    #ordersTable .table-sm > thead { background-color:#4e73df; color:white; border-color:#4e73df; }
    #ordersTable .table-sm > thead th { font-weight:600; }
    #ordersTable .table-sm > tbody > tr:hover { background-color:#eaecf4; }
    #ordersTable .table-sm > tbody td:last-child { font-weight:700; color:#2e59d9; }
</style>

<div class="container-fluid">
    <h1 class="h3 mb-4 text-gray-800">Quản lý Đơn hàng</h1>

    <div class="row mb-4">
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card summary-card">
                <div class="card-body">
                    <div class="text-content"><div class="label">Tổng số hóa đơn</div><div class="value" id="summary-card-orders">0</div></div>
                    <div class="icon-circle bg-primary"><i class="fas fa-file-invoice-dollar"></i></div>
                </div>
            </div>
        </div>
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card summary-card">
                <div class="card-body">
                    <div class="text-content"><div class="label">Tổng tiền</div><div class="value" id="summary-card-amount">0 ₫</div></div>
                    <div class="icon-circle bg-success"><i class="fas fa-coins"></i></div>
                </div>
            </div>
        </div>
        <div class="col-xl-4 col-md-6 mb-4">
            <div class="card summary-card">
                <div class="card-body">
                    <div class="text-content"><div class="label">Tổng nợ</div><div class="value" id="summary-card-debt">0 ₫</div></div>
                    <div class="icon-circle bg-danger"><i class="fas fa-exclamation-triangle"></i></div>
                </div>
            </div>
        </div>
    </div>

    <div class="card shadow mb-4 filter-card">
        <div class="card-header py-3">
            <h6 class="m-0 font-weight-bold"><i class="fas fa-filter mr-2"></i>Bộ lọc và Tìm kiếm</h6>
        </div>
        <div class="card-body">
            <form id="filter-form">
                <div class="row align-items-end">
                    <div class="col-md-3 mb-3"><label class="form-label">Chế độ xem</label><select class="form-select form-control" id="filterView"><option value="all" selected>Tất cả đơn hàng</option><option value="debt">Đơn hàng còn nợ</option><option value="deleted">Đơn hàng đã xóa</option></select></div>
                    <div class="col-md-3 mb-3"><label class="form-label">Mã đơn hàng</label><input type="text" class="form-control" id="code" placeholder="Nhập mã đơn hàng..."></div>
                    <div class="col-md-2 mb-3"><label class="form-label">Từ ngày</label><input type="text" class="form-control" id="from_date" placeholder="Chọn ngày bắt đầu"></div>
                    <div class="col-md-2 mb-3"><label class="form-label">Đến ngày</label><input type="text" class="form-control" id="to_date" placeholder="Chọn ngày kết thúc"></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-1"></i> Lọc</button></div>
                </div>
            </form>
        </div>
    </div>

    <div class="card shadow mb-4">
        <div class="card-header py-3 d-flex justify-content-between align-items-center">
            <h6 class="m-0 font-weight-bold text-primary">Danh sách đơn hàng</h6>
            <a href="/quanlybanhang/modules/pos/banhang.php" class="btn btn-success btn-sm"><i class="fas fa-plus fa-sm"></i> Tạo đơn hàng mới</a>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="ordersTable" width="100%" cellspacing="0"></table>
            </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>
$(document).ready(function() {
    
    const fp_config = { locale: "vn", altInput: true, altFormat: "d/m/Y", dateFormat: "Y-m-d" };
    flatpickr("#from_date", { ...fp_config, defaultDate: "<?php echo date('Y-m-01'); ?>" });
    flatpickr("#to_date", { ...fp_config, defaultDate: "today" });

    function formatNumber(num) { return (parseFloat(num) || 0).toLocaleString('vi-VN'); }
    
    var table = $('#ordersTable').DataTable({
        "processing": true,
        "serverSide": true,
        "searching": false,
        "ajax": {
            "url": "/quanlybanhang/ajax/orders_ajax.php",
            "type": "POST",
            "data": function(d) {
                d.action = 'get_orders_list';
                d.view_mode = $('#filterView').val();
                d.code = $('#code').val();
                d.from = $('#from_date').val();
                d.to = $('#to_date').val();
            }
        },
        "columns": [
            { className: 'details-control text-center', orderable: false, data: null, defaultContent: '<i class="fas fa-plus-circle text-primary"></i>', title: '' },
            
            // ⭐⭐⭐ DÒNG QUAN TRỌNG ĐÃ SỬA ⭐⭐⭐
            { "data": "output_code", "title": "Mã ĐH", "render": (data, type, row) => `<a href="/quanlybanhang/modules/pos/banhang.php?edit_order_id=${row.id}" class="fw-bold">${data}</a>` },
            
            { "data": "sell_date", "title": "Ngày bán" },
            { "data": "customer_name", "title": "Khách hàng" },
            { "data": "username", "title": "Thu ngân" },
            { "data": "total_money", "title": "Tổng tiền", "className": "text-end", "render": data => formatNumber(data) },
            { "data": "lack", "title": "Còn nợ", "className": "text-end fw-bold text-danger", "render": data => formatNumber(data) },
            { "data": "order_status", "title": "Trạng thái", "className": "text-center", "render": function(data) {
                switch(data) {
                    case 'Hoàn thành': return '<span class="badge bg-success">Hoàn thành</span>';
                    case 'Đã hủy': return '<span class="badge bg-danger">Đã hủy</span>';
                    case 'Đang giao': return '<span class="badge bg-info">Đang giao</span>';
                    case 'Xác nhận': return '<span class="badge bg-primary">Xác nhận</span>';
                    default: return `<span class="badge bg-secondary">${data}</span>`;
                }
            }},
            { "data": "actions", "title": "Hành động", "orderable": false, "className": "text-center" }
        ],
        "language": { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" },
        "order": [[2, "desc"]],
        "dom": "t<'d-flex justify-content-between align-items-center mt-3'<'#summary-info.py-2 fw-bold'>p>",
        "drawCallback": function(settings) {
            var json = this.api().ajax.json();
            if (json && json.summary) {
                let s = json.summary;
                $('#summary-card-orders').text(formatNumber(s.total_orders));
                $('#summary-card-amount').text(formatNumber(s.total_amount) + ' ₫');
                $('#summary-card-debt').text(formatNumber(s.total_debt) + ' ₫');
                let summaryText = `<span class="me-4">Tổng số hóa đơn: <span class="text-dark">${formatNumber(s.total_orders)}</span></span><span class="me-4">Tổng tiền: <span class="text-dark">${formatNumber(s.total_amount)}</span></span><span>Tổng nợ: <span class="text-danger">${formatNumber(s.total_debt)}</span></span>`;
                $('#summary-info').html(summaryText);
            }
        }
    });

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

    function formatDetails(response) {
        const order = response.order;
        const items = response.items;
        if (!order || !items) return '<div class="p-3 text-center text-muted">Không có dữ liệu chi tiết.</div>';
        
        const totalDiscount = (parseFloat(order.total_discount) || 0) + (parseFloat(order.discount_item) || 0);
        const formatVNCurrency = (num) => (num || 0).toLocaleString('vi-VN');

        let summaryHtml = `<div class="child-row-container"><div class="child-summary"><span>Số lượng SP: <strong>${formatVNCurrency(order.total_quantity)}</strong></span><span>Tiền hàng: <strong>${formatVNCurrency(order.total_price)}</strong></span><span>Giảm giá: <strong>${formatVNCurrency(totalDiscount)}</strong></span><span>Tổng tiền: <strong>${formatVNCurrency(order.total_money)}</strong></span><span>Còn nợ: <strong>${formatVNCurrency(order.lack)}</strong></span></div>`;
        let productsHtml = `<table class="table table-sm table-hover"><thead><tr><th>STT</th><th>Mã SP</th><th>Tên sản phẩm</th><th>SL</th><th>Đơn giá</th><th>Thành tiền</th></tr></thead><tbody>`;
        if (items.length > 0) {
            items.forEach((item, index) => {
                let lineTotal = (item.quantity || 0) * (item.price || 0);
                productsHtml += `<tr><td>${index + 1}</td><td><a href="/quanlybanhang/modules/products/add.php?id=${item.id}" target="_blank">${item.code || 'N/A'}</a></td><td>${item.name || 'N/A'}</td><td>${formatVNCurrency(item.quantity)}</td><td>${formatVNCurrency(item.price)}</td><td>${formatVNCurrency(lineTotal)}</td></tr>`;
            });
        } else {
            productsHtml += `<tr><td colspan="6" class="text-center">Đơn hàng không có sản phẩm.</td></tr>`;
        }
        productsHtml += '</tbody></table></div>';
        return summaryHtml + productsHtml;
    }

    $('#ordersTable tbody').on('click', 'td.details-control', function () {
        var tr = $(this).closest('tr');
        var row = table.row(tr);
        var icon = $(this).find('i');

        if (row.child.isShown()) {
            row.child.hide();
            tr.removeClass('dt-hasChild');
            icon.removeClass('fa-minus-circle text-danger').addClass('fa-plus-circle text-primary');
        } else {
            table.rows().every(function(){
                if(this.child.isShown()){
                    this.child.hide();
                    $(this.node()).removeClass('dt-hasChild');
                    $(this.node()).find('td.details-control i').removeClass('fa-minus-circle text-danger').addClass('fa-plus-circle text-primary');
                }
            });

            icon.removeClass('fa-plus-circle text-primary').addClass('fa-spinner fa-spin');
            
            $.ajax({
                url: '/quanlybanhang/ajax/orders_ajax.php',
                type: 'POST',
                dataType: 'json',
                data: { action: 'get_order_details', order_id: row.data().id },
                success: function(response) {
                    if (response.status === 'success') {
                        row.child(formatDetails(response), 'child-row').show();
                        tr.addClass('dt-hasChild');
                        icon.removeClass('fa-spinner fa-spin').addClass('fa-minus-circle text-danger');
                    } else {
                        row.child('<div class="p-3 text-center text-danger">Lỗi: ' + response.message + '</div>').show();
                        icon.removeClass('fa-spinner fa-spin').addClass('fa-plus-circle text-primary');
                    }
                },
                error: function() {
                    row.child('<div class="p-3 text-center text-danger">Lỗi kết nối.</div>').show();
                    icon.removeClass('fa-spinner fa-spin').addClass('fa-plus-circle text-primary');
                }
            });
        }
    });

    $('#ordersTable tbody').on('click', '.btn-delete-order', function(e) {
        e.preventDefault();
        var orderId = $(this).data('id');
        var orderCode = $(this).data('code');
    
        if (confirm(`Bạn có chắc chắn muốn XÓA đơn hàng [${orderCode}]?`)) {
            $.ajax({
                url: '/quanlybanhang/ajax/orders_ajax.php',
                type: 'POST',
                dataType: 'json',
                data: { action: 'delete_order', order_id: orderId },
                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.'); }
            });
        }
    });
});
</script>