<?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 { 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; color:#3a3b45; }
    .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 { 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; }
    #phieuNhapTable thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; }
    #phieuNhapTable tbody tr:nth-child(even) { background-color: #f8f9fc; }
    #phieuNhapTable tbody tr:hover { background-color: #eaecf4; }
    .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; }
    .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: #1cc88a; border-color: #1cc88a; color: white; }
    .btn-create { background-color: #4e73df; border-color: #4e73df; 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 phiếu nhập</h1>
        <div class="d-flex gap-2">
            <a href="/quanlybanhang/modules/imports/report_imports.php" class="btn btn-action-lg btn-report shadow-sm"><i class="fas fa-file-alt me-1"></i> Báo cáo nhập</a>
            <a href="/quanlybanhang/modules/imports/tao_phieunhap.php" class="btn btn-action-lg btn-create shadow-sm"><i class="fas fa-plus me-1"></i> Tạo phiếu nhập</a>
        </div>
    </div>

    <div class="row mb-4">
        <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">Tổng số phiếu</div><div class="value" id="summary-total-slips">0</div></div><div class="icon-circle" style="background-color:#4e73df;"><i class="fas fa-clipboard-list"></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">Tổng tiền nhập</div><div class="value" id="summary-total-amount">0 ₫</div></div><div class="icon-circle" style="background-color:#1cc88a;"><i class="fas fa-cash-register"></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">Tổng nợ NCC</div><div class="value" id="summary-total-debt">0 ₫</div></div><div class="icon-circle" style="background-color:#e74a3b;"><i class="fas fa-hourglass-half"></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">Hôm nay</div><div class="value" id="summary-slips-today">0</div></div><div class="icon-circle" style="background-color:#f6c23e;"><i class="fas fa-calendar-check"></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="searchMaPhieu" placeholder="Nhập mã phiếu...">
            </div>
            <div class="col-12 col-md-2">
                <select class="form-select" id="filterView">
                    <option value="all" selected>Phiếu nhập</option>
                    <option value="debt">Phiếu còn nợ</option>
                    <option value="deleted">Phiếu đã xóa</option>
                </select>
            </div>
            <div class="col-12 col-md-4">
                <div class="input-group">
                    <input type="text" class="form-control" id="filterTuNgay" placeholder="Từ ngày">
                    <span class="input-group-text">to</span>
                    <input type="text" class="form-control" id="filterDenNgay" placeholder="Đến ngày">
                </div>
            </div>
            <div class="col-12 col-md-3 d-flex gap-2">
                <button type="button" class="btn btn-primary w-100" id="btn-filter"><i class="fas fa-search me-1"></i> Lọc</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 align-middle" id="phieuNhapTable" style="width:100%;"></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" };
    const fp_from = flatpickr("#filterTuNgay", fp_config);
    const fp_to = flatpickr("#filterDenNgay", fp_config);
    
    function formatNumber(num) { return (parseFloat(num) || 0).toLocaleString('vi-VN'); }

    function formatChildRow(d) {
        if (!d || d.length === 0) { return '<div class="p-3 text-center">Không có chi tiết sản phẩm.</div>'; }
        let totalQty = 0, totalAmount = 0, rows_html = '';
        d.forEach((item, index) => {
            let quantity = parseFloat(item.quantity) || 0;
            let price = parseFloat(item.price) || 0;
            let finalLineTotal = quantity * price;
            totalQty += quantity;
            totalAmount += finalLineTotal;
            rows_html += `<tr><td>${index + 1}</td><td>${item.code || ''}</td><td>${item.name || ''}</td><td class="text-center">${formatNumber(quantity)}</td><td class="text-end">${formatNumber(price)}</td><td class="text-end fw-bold">${formatNumber(finalLineTotal)}</td></tr>`;
        });
        let summaryHtml = `<div class="child-row-container"><div class="child-summary"><span>Số lượng SP: <strong>${formatNumber(totalQty)}</strong></span><span>Tổng tiền hàng: <strong>${formatNumber(totalAmount)}</strong></span></div>`;
        return summaryHtml + `<table class="table table-sm table-hover"><thead class="table-light"><tr><th>STT</th><th>Mã SP</th><th>Tên SP</th><th class="text-center">SL</th><th class="text-end">Giá nhập</th><th class="text-end">Thành tiền</th></tr></thead><tbody>${rows_html}</tbody></table></div>`;
    }
    
    var table = $('#phieuNhapTable').DataTable({
        "processing": true, "serverSide": true,
        "ajax": {
            "url": "/quanlybanhang/ajax/imports_ajax.php",
            "type": "POST",
            "data": function(d) {
                d.action = 'get_imports_list';
                d.view_mode = $('#filterView').val();
                d.ma_phieu = $('#searchMaPhieu').val();
                d.tu_ngay = $('#filterTuNgay').val();
                d.den_ngay = $('#filterDenNgay').val();
            }
        },
        "columns": [
            { "className": 'details-control text-center', "orderable": false, "data": null, "defaultContent": '<i class="fas fa-plus-circle text-primary"></i>', "title": "" },
            { "data": "input_code", "title": "Mã phiếu", render: (data, type, row) => `<a href="tao_phieunhap.php?id=${row.id}" class="fw-bold">${data}</a>` },
            { "data": "store_name", "title": "Kho" }, 
            { "data": "input_date", "title": "Ngày nhập", render: data => data ? new Date(data).toLocaleDateString('vi-VN') : '' }, 
            { "data": "user_name", "title": "Người nhập" },
            { "data": "total_money", "title": "Tổng tiền", "className": "text-end fw-bold", render: data => formatNumber(data) },
            { "data": "lack", "title": "Nợ", "className": "text-end text-danger fw-bold", render: data => formatNumber(data) },
            { "data": "id", "title": "Hành động", "orderable": false, "className": "text-center", render: function(data, type, row) {
                if (row.deleted == 1) return `<span class="badge bg-secondary">Đã xóa</span>`;
                let editUrl = `/quanlybanhang/modules/imports/tao_phieunhap.php?id=${data}`;
                let printUrl = `/quanlybanhang/modules/imports/print_slip.php?id=${data}`;
                let deleteButton = `<a href="#" class="btn btn-danger btn-sm btn-delete" data-id="${data}" title="Hủy phiếu"><i class="fas fa-trash"></i></a>`;
                return `<div class="btn-group btn-group-sm">${deleteButton}<a href="${editUrl}" class="btn btn-warning btn-sm" title="Sửa"><i class="fas fa-edit"></i></a><a href="${printUrl}" target="_blank" class="btn btn-info btn-sm" title="In"><i class="fas fa-print"></i></a></div>`;
            }}
        ],
        "language": { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" },
        "pageLength": 10, "searching": false, "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-total-slips').text(formatNumber(s.total_slips));
                $('#summary-total-amount').text(formatNumber(s.total_amount) + ' ₫');
                $('#summary-total-debt').text(formatNumber(s.total_debt) + ' ₫');
                $('#summary-slips-today').text(formatNumber(s.slips_today));
                $('#summary-info').html(`Tổng phiếu: <strong>${formatNumber(s.total_slips)}</strong>, Tổng tiền: <strong>${formatNumber(s.total_amount)} ₫</strong>`);
            }
        }
    });

    $('#btn-filter').on('click', e => { e.preventDefault(); 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') { fromDate = new Date(today.setDate(today.getDate() - today.getDay())); } 
        else if (range === 'month') { fromDate = new Date(today.getFullYear(), today.getMonth(), 1); } 
        else if (range === 'quarter') { fromDate = new Date(today.getFullYear(), Math.floor(today.getMonth() / 3) * 3, 1); }
        fp_from.setDate(fromDate);
        fp_to.setDate(new Date());
        table.ajax.reload();
    });
    
    $('#phieuNhapTable 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('shown');
            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');
            $.post('/quanlybanhang/ajax/imports_ajax.php', { action: 'get_import_details', import_id: row.data().id }, (res) => {
                if (res.status === 'success') {
                    row.child(formatChildRow(res.data), 'dt-child').show();
                    tr.addClass('shown');
                    icon.removeClass('fa-spinner fa-spin').addClass('fa-minus-circle text-danger');
                } else {
                    alert(res.message);
                    icon.removeClass('fa-spinner fa-spin').addClass('fa-plus-circle text-primary');
                }
            }, 'json').fail(() => {
                alert('Lỗi kết nối.');
                icon.removeClass('fa-spinner fa-spin').addClass('fa-plus-circle text-primary');
            });
        }
    });

    $('#phieuNhapTable tbody').on('click', '.btn-delete', function(e) {
        e.preventDefault();
        var slipId = $(this).data('id');
        if (confirm('Bạn có chắc chắn muốn hủy phiếu nhập này? Hành động này sẽ hoàn lại số lượng sản phẩm vào kho.')) {
            $.post('/quanlybanhang/ajax/imports_ajax.php', { action: 'delete_import_slip', slip_id: slipId }, function(response) {
                if(response.message) alert(response.message);
                if (response.status === 'success') { table.ajax.reload(null, false); }
            }, 'json').fail(function() { alert('Lỗi kết nối.'); });
        }
    });
});
</script>