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

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.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 .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 {
        background-color: #fff;
        border: 1px solid #e3e6f0;
        border-radius: 0.75rem;
        padding: 1.25rem;
        box-shadow: 0 .15rem 1.75rem 0 rgba(58,59,69,.15)!important;
    }
    .filter-card .form-control,
    .filter-card .form-select {
        height: 38px;
        font-size: 0.9rem;
        border-radius: 0.35rem;
        border-color: #d1d3e2;
    }
    .filter-card .form-control:focus,
    .filter-card .form-select:focus {
        border-color: #4e73df;
        box-shadow: 0 0 0 0.2rem rgba(78, 115, 223, 0.25);
    }
    .btn-quick-date.active {
        background-color: #4e73df;
        border-color: #4e73df;
        color: white;
    }
    
    #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; }
    
    .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.sum-qty { background-color:#4e73df; }
    .child-summary span.sum-subtotal { background-color:#1cc88a; }
    .child-summary span.sum-discount { background-color:#f6c23e; }
    .child-summary span.sum-total { background-color:#36b9cc; }
    .child-summary span.sum-debt { background-color:#e74a3b; }
    
    .datatable-footer {
        padding: 1rem 0;
        display: flex;
        justify-content: space-between;
        align-items: center;
    }

    .btn-action-lg {
        padding: 0.75rem 1.5rem;
        font-size: 1rem;
        font-weight: bold;
        border-radius: 0.5rem;
        box-shadow: 0 0.2rem 0.5rem rgba(0,0,0,0.1);
        transition: all 0.2s ease-in-out;
    }
    .btn-action-lg:hover {
        transform: translateY(-1px);
        box-shadow: 0 0.3rem 0.7rem rgba(0,0,0,0.2);
    }
    .btn-report {
        background-color: #20c997;
        border-color: #20c997;
        color: white;
    }
    .btn-sell {
        background-color: #007bff;
        border-color: #007bff;
        color: white;
    }
</style>

<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 Đơn hàng</h1>
        <div class="d-flex gap-2">
            <a href="/quanlybanhang/modules/reports/report_orders.php" class="btn btn-action-lg btn-report shadow-sm"><i class="fas fa-download me-1"></i> Báo cáo xuất</a>
            <a href="/quanlybanhang/modules/pos/pos.php" class="btn btn-action-lg btn-sell shadow-sm"><i class="fas fa-plus me-1"></i> Bán hàng</a>
        </div>
    </div>
    
    <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="filter-card mb-4">
        <div class="row g-2 align-items-center">
            <div class="col-12 col-md-3">
                <input type="text" class="form-control" id="filter-code" placeholder="Nhập mã đơn hàng...">
            </div>
            <div class="col-12 col-md-2">
                <select id="filter-status" class="form-select">
                 <option value="all_orders" selected>Tất cả đơn hàng</option>
                    <option value="draft">Đơn hàng khởi tạo</option>
                    <option value="deleted">Đơn hàng đã xóa</option>
                    <option value="debt">Đơn hàng còn nợ</option>
                </select>
            </div>
            <div class="col-12 col-md-4">
                <div class="input-group">
                    <input type="text" id="filter-from-date" class="form-control" placeholder="Từ ngày">
                    <span class="input-group-text">to</span>
                    <input type="text" id="filter-to-date" class="form-control" placeholder="Đến ngày">
                </div>
            </div>
            <div class="col-12 col-md-3 d-flex gap-2">
                <button class="btn btn-primary w-100" id="btn-filter"><i class="fas fa-search me-1"></i> Tìm kiếm</button>
                <div class="btn-group w-100">
                    <button class="btn btn-outline-secondary btn-quick-date" data-range="week">Tuần</button>
                    <button class="btn btn-outline-secondary btn-quick-date" data-range="month">Tháng</button>
                    <button class="btn btn-outline-secondary btn-quick-date" data-range="quarter">Quý</button>
                </div>
            </div>
        </div>
    </div>

    <div class="card shadow mb-4">
        <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", allowInput: true };
    const fp_from = flatpickr("#filter-from-date", fp_config);
    const fp_to = flatpickr("#filter-to-date", fp_config);

    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.code = $('#filter-code').val();
                d.filter_status = $('#filter-status').val();
                d.from = $('#filter-from-date').val();
                d.to = $('#filter-to-date').val();
            }
        },
        "columns": [
            { className: 'details-control text-center', orderable: false, data: null, defaultContent: '<i class="fas fa-plus-circle text-primary"></i>', title: '' },
            { "data": "output_code", "title": "Mã Đơn Hàng" },
            { "data": "store_name", "title": "Kho xuất" },
            { "data": "sell_date", "title": "Ngày bán" },
            { "data": "customer_name", "title": "Khách hàng" },
            { "data": "order_status", "title": "Trạng thái", "className": "text-center" },
            { "data": "total_quantity", "title": "Tổng SL", "className": "text-center" },
            { "data": "total_money", "title": "Tổng tiền", "className": "text-end", "render": data => formatNumber(data) },
            { "data": "lack", "title": "Nợ", "className": "text-end fw-bold text-danger", "render": data => formatNumber(data) },
            { "data": "actions", "title": "", "orderable": false, "className": "text-center" }
        ],
        "language": { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" },
        "order": [[3, "desc"]],
        "dom": "t<'datatable-footer'<'#summary-info'>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 = `Tổng số hóa đơn: <strong class="text-primary">${formatNumber(s.total_orders)}</strong>, 
                                   Tổng tiền: <strong class="text-success">${formatNumber(s.total_amount)}</strong>, 
                                   Tổng nợ: <strong class="text-danger">${formatNumber(s.total_debt)}</strong>`;
                $('#summary-info').html(summaryText);
            }
        }
    });

    $('#btn-filter').on('click', function() {
        table.ajax.reload();
        $('.btn-quick-date').removeClass('active');
    });

    $('.btn-quick-date').on('click', function() {
        $('.btn-quick-date').removeClass('active');
        $(this).addClass('active');

        const range = $(this).data('range');
        const today = new Date();
        let fromDate;

        if (range === 'week') {
            const firstDayOfWeek = today.getDate() - today.getDay();
            fromDate = new Date(today.setDate(firstDayOfWeek));
        } else if (range === 'month') {
            fromDate = new Date(today.getFullYear(), today.getMonth(), 1);
        } else if (range === 'quarter') {
            const currentQuarter = Math.floor(today.getMonth() / 3);
            fromDate = new Date(today.getFullYear(), currentQuarter * 3, 1);
        }

        fp_from.setDate(fromDate);
        fp_to.setDate(new Date());
        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);
        let summaryHtml = `<div class="child-row-container">
            <div class="child-summary">
                <span class="sum-qty">Số lượng SP: <strong>${formatNumber(order.total_quantity)}</strong></span>
                <span class="sum-subtotal">Tiền hàng: <strong>${formatNumber(order.total_price)}</strong></span>
                <span class="sum-discount">Giảm giá: <strong>${formatNumber(totalDiscount)}</strong></span>
                <span class="sum-total">Tổng tiền: <strong>${formatNumber(order.total_money)}</strong></span>
                <span class="sum-debt">Còn nợ: <strong>${formatNumber(order.lack)}</strong></span>
            </div>`;
            
        let productsHtml = `<table class="table table-sm table-bordered"><thead><tr class="table-light"><th>#</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>${item.code || 'N/A'}</td><td>${item.name || 'N/A'}</td><td>${formatNumber(item.quantity)}</td><td class="text-end">${formatNumber(item.price)}</td><td class="text-end">${formatNumber(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 {
            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>