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

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<style>
    /* --- SUMMARY CARDS (GRADIENT) --- */
    .summary-box { 
        padding: 25px; border-radius: 15px; color: white; 
        position: relative; overflow: hidden; box-shadow: 0 4px 15px rgba(0,0,0,0.1); 
        transition: transform 0.2s;
    }
    .summary-box:hover { transform: translateY(-5px); }
    .bg-primary-gradient { background: linear-gradient(45deg, #4e73df, #224abe); }
    .bg-success-gradient { background: linear-gradient(45deg, #1cc88a, #13855c); }
    .bg-danger-gradient  { background: linear-gradient(45deg, #e74a3b, #be2617); }
    
    .summary-title { font-size: 0.9rem; text-transform: uppercase; font-weight: 600; opacity: 0.9; margin-bottom: 5px; }
    .summary-value { font-size: 2rem; font-weight: 800; }
    .summary-icon { position: absolute; right: 20px; bottom: 15px; font-size: 3.5rem; opacity: 0.2; }

    /* --- FILTER BAR --- */
    .filter-bar { background: #fff; padding: 20px; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 25px; }
    .form-label { font-weight: 600; font-size: 0.9rem; color: #555; margin-bottom: 5px; }

    /* --- TABLE STYLES --- */
    .table-card { border: none; border-radius: 12px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); overflow: hidden; }
    #ordersTable thead th { 
        background-color: #f8f9fc; color: #5a5c69; 
        font-weight: 700; text-transform: uppercase; font-size: 0.85rem; border-bottom: 2px solid #e3e6f0; padding: 15px 10px;
    }
    #ordersTable tbody td { vertical-align: middle; padding: 12px 10px; font-size: 0.95rem; color: #444; }
    
    /* Child Row (Chi tiết) */
    .child-row-content { background: #f8f9fc; padding: 15px; border-radius: 8px; box-shadow: inset 0 0 10px rgba(0,0,0,0.05); }
    .child-table th { background: #e9ecef !important; font-size: 0.85rem; }
    
    .badge { padding: 6px 10px; border-radius: 6px; font-weight: 600; }
    
    /* Nút bấm */
    .btn-custom-lg { padding: 10px 20px; font-weight: 700; border-radius: 8px; }
</style>

<div class="container-fluid">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h1 class="h3 mb-1 text-gray-800 fw-bold">Quản lý Đơn hàng</h1>
            <p class="mb-0 text-muted small">Theo dõi và quản lý lịch sử bán hàng</p>
        </div>
        <a href="/quanlybanhang/modules/pos/thungan.php" class="btn btn-primary btn-custom-lg shadow-sm">
            <i class="fas fa-plus-circle me-2"></i>Tạo đơn mới (POS)
        </a>
    </div>

    <div class="row g-4 mb-4">
        <div class="col-md-4">
            <div class="summary-box bg-primary-gradient">
                <div class="summary-title">Tổng đơn hàng</div>
                <div class="summary-value" id="sum-total-orders">0</div>
                <i class="fas fa-file-invoice summary-icon"></i>
            </div>
        </div>
        <div class="col-md-4">
            <div class="summary-box bg-success-gradient">
                <div class="summary-title">Doanh thu thực tế</div>
                <div class="summary-value" id="sum-total-money">0 ₫</div>
                <i class="fas fa-coins summary-icon"></i>
            </div>
        </div>
        <div class="col-md-4">
            <div class="summary-box bg-danger-gradient">
                <div class="summary-title">Khách nợ</div>
                <div class="summary-value" id="sum-total-debt">0 ₫</div>
                <i class="fas fa-hand-holding-usd summary-icon"></i>
            </div>
        </div>
    </div>

    <div class="filter-bar">
        <div class="row g-3">
            <div class="col-md-3">
                <label class="form-label">Mã đơn hàng</label>
                <input type="text" id="filter-code" class="form-control" placeholder="Nhập mã DH...">
            </div>
            <div class="col-md-3">
                <label class="form-label">Trạng thái</label>
                <select id="filter-status" class="form-select">
                    <option value="all">Tất cả</option>
                    <option value="done">Hoàn thành</option>
                    <option value="debt">Còn nợ</option>
                    <option value="draft">Lưu tạm</option>
                </select>
            </div>
            <div class="col-md-4">
                <label class="form-label">Thời gian</label>
                <div class="input-group">
                    <input type="text" id="date-from" class="form-control flatpickr" placeholder="Từ ngày">
                    <span class="input-group-text bg-light">➜</span>
                    <input type="text" id="date-to" class="form-control flatpickr" placeholder="Đến ngày">
                </div>
            </div>
            <div class="col-md-2 d-flex align-items-end">
                <button id="btn-filter" class="btn btn-dark w-100 fw-bold" style="height: 38px;"><i class="fas fa-search me-1"></i> Lọc</button>
            </div>
        </div>
    </div>

    <div class="card table-card">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table id="ordersTable" class="table table-hover mb-0" width="100%">
                    <thead>
                        <tr>
                            <th></th> <th>Mã Đơn</th>
                            <th>Thời gian</th>
                            <th>Khách hàng</th>
                            <th>Bàn/Khu vực</th>
                            <th class="text-center">Trạng thái</th>
                            <th class="text-end">Tổng tiền</th>
                            <th class="text-end">Nợ</th>
                            <th class="text-center">Thao tác</th>
                        </tr>
                    </thead>
                    <tbody></tbody>
                </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() {
    // Init Datepicker
    flatpickr(".flatpickr", { locale: "vn", dateFormat: "Y-m-d" });
    
    // Init DataTable
    var table = $('#ordersTable').DataTable({
        processing: true, serverSide: true, searching: false, lengthChange: false, pageLength: 10,
        ajax: {
            url: "/quanlybanhang/ajax/orders_ajax.php", type: "POST",
            data: function(d) {
                d.action = 'get_orders_list';
                d.code = $('#filter-code').val();
                d.filter_status = $('#filter-status').val();
                d.from = $('#date-from').val();
                d.to = $('#date-to').val();
            }
        },
        columns: [
            {
                className: 'dt-control text-center', orderable: false, data: null, defaultContent: '<i class="fas fa-plus-circle text-primary" style="cursor:pointer; font-size:1.2rem;"></i>'
            },
            { data: 'output_code' },
            { data: 'sell_date' },
            { data: 'customer_name', render: (d) => `<strong>${d}</strong>` },
            { data: 'table_name' },
            { data: 'order_status', className: "text-center" },
            { data: 'total_money', className: "text-end fw-bold text-success" },
            { data: 'lack', className: "text-end" },
            { data: 'actions', className: "text-center" }
        ],
        drawCallback: function(settings) {
            var json = this.api().ajax.json();
            if(json && json.summary) {
                $('#sum-total-orders').text(json.summary.total_orders);
                $('#sum-total-money').text(new Intl.NumberFormat('vi-VN').format(json.summary.total_amount) + ' ₫');
                $('#sum-total-debt').text(new Intl.NumberFormat('vi-VN').format(json.summary.total_debt) + ' ₫');
            }
        },
        language: { url: "//cdn.datatables.net/plug-ins/1.10.21/i18n/Vietnamese.json" }
    });

    // Filter Button
    $('#btn-filter').click(() => table.ajax.reload());

    // --- SỰ KIỆN CLICK XEM CHI TIẾT (CHILD ROW) ---
    $('#ordersTable tbody').on('click', 'td.dt-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('shown');
            icon.removeClass('fa-minus-circle text-danger').addClass('fa-plus-circle text-primary');
        } else {
            // Loading
            icon.removeClass('fa-plus-circle text-primary').addClass('fa-spinner fa-spin text-secondary');
            
            // Gọi Ajax lấy chi tiết
            $.post('/quanlybanhang/ajax/orders_ajax.php', { action: 'get_order_details', order_id: row.data().id }, function(res) {
                if(res.status === 'success') {
                    row.child(formatDetailRow(res)).show();
                    tr.addClass('shown');
                    icon.removeClass('fa-spinner fa-spin text-secondary').addClass('fa-minus-circle text-danger');
                } else {
                    alert(res.message);
                }
            }, 'json');
        }
    });
    
    // Hàm render HTML chi tiết
    function formatDetailRow(d) {
        let items = d.items;
        let html = `<div class="child-row-content">
            <h6 class="fw-bold mb-3"><i class="fas fa-list me-2"></i>Chi tiết món ăn</h6>
            <table class="table table-sm table-bordered bg-white child-table">
                <thead><tr><th>#</th><th>Tên món</th><th class="text-center">SL</th><th class="text-end">Đơn giá</th><th class="text-end">Thành tiền</th></tr></thead>
                <tbody>`;
        
        items.forEach((item, idx) => {
            html += `<tr>
                <td>${idx+1}</td>
                <td>
                    ${item.image ? `<img src="/quanlybanhang/${item.image}" style="width:30px;height:30px;object-fit:cover;margin-right:5px;border-radius:4px;">` : ''} 
                    <strong>${item.name}</strong>
                </td>
                <td class="text-center">${item.quantity}</td>
                <td class="text-end">${new Intl.NumberFormat('vi-VN').format(item.price)}</td>
                <td class="text-end fw-bold">${new Intl.NumberFormat('vi-VN').format(item.total)}</td>
            </tr>`;
        });
        
        html += `</tbody></table></div>`;
        return html;
    }

    // Xóa đơn
    $('body').on('click', '.btn-delete', function() {
        if(confirm('Xóa đơn hàng này? (Dữ liệu sẽ không thể khôi phục)')) {
            let id = $(this).data('id');
            $.post('/quanlybanhang/ajax/orders_ajax.php', { action: 'delete_order', order_id: id }, function(res) {
                if(res.status === 'success') { alert('Đã xóa!'); table.ajax.reload(null, false); }
                else alert(res.message);
            }, 'json');
        }
    });
});
</script>