<?php
require_once __DIR__ . '/../../core/init.php';

if (!isset($_GET['id']) || empty($_GET['id'])) { die('Không có nhà cung cấp nào được chọn.'); }
$supplier_id = intval($_GET['id']);

// Lấy thông tin chi tiết nhà cung cấp
$stmt = $conn->prepare("SELECT * FROM cms_suppliers WHERE ID = ?");
$stmt->bind_param("i", $supplier_id);
$stmt->execute();
$supplier = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$supplier) { die('Không tìm thấy nhà cung cấp.'); }

// Tối ưu câu lệnh SQL để lấy tên người tạo và sắp xếp nợ lên đầu
$sql_history = "SELECT i.*, u.display_name as creator_name 
                FROM cms_input i 
                LEFT JOIN cms_users u ON i.user_init = u.id 
                WHERE i.supplier_id = ? AND i.deleted = 0 
                ORDER BY i.lack DESC, i.input_date DESC";
$stmt_history = $conn->prepare($sql_history);
$stmt_history->bind_param("i", $supplier_id);
$stmt_history->execute();
$import_history = $stmt_history->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_history->close();

$debt_slips = array_filter($import_history, function($slip) { return isset($slip['lack']) && $slip['lack'] > 0; });
$total_slips = count($import_history);
$total_spent = array_sum(array_column($import_history, 'total_money'));
$total_debt = array_sum(array_column($import_history, 'lack'));

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

<style>
    .supplier-info-card .info-item { margin-bottom: 1rem; }
    .supplier-info-card .info-label { font-weight: 600; color: #858796; display: block; }
    .supplier-info-card .info-value { font-size: 1.1rem; color: #3a3b45; }
    #importHistoryTable thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; }
    #importHistoryTable tbody tr:nth-child(even) { background-color: #f8f9fc; }
    #importHistoryTable tbody tr:hover { background-color: #eaecf4; }
    .details-control { cursor: pointer; width: 25px; }
    .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; }
    #importHistoryTable .table-sm > thead { background-color:#4e73df; color:white; border-color:#4e73df; }
    #importHistoryTable .table-sm > tbody td:last-child { font-weight:700; color:#2e59d9; }
</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">Chi tiết NCC: <?php echo htmlspecialchars($supplier['supplier_name']); ?></h1>
        <div>
            <button type="button" class="btn btn-sm btn-warning shadow-sm" data-bs-toggle="modal" data-bs-target="#supplierModal"><i class="fas fa-edit fa-sm text-white-50"></i> Sửa</button>
            <a href="list.php" class="btn btn-sm btn-secondary shadow-sm"><i class="fas fa-arrow-left fa-sm text-white-50"></i> Quay lại</a>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-12">
            <div class="card shadow mb-4">
                <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Thông tin nhà cung cấp</h6></div>
                <div class="card-body supplier-info-card">
                    <div class="row">
                        <div class="col-md-4 info-item"><span class="info-label">Mã NCC:</span><span class="info-value"><?php echo htmlspecialchars($supplier['supplier_code']); ?></span></div>
                        <div class="col-md-4 info-item"><span class="info-label">Số điện thoại:</span><span class="info-value"><?php echo htmlspecialchars($supplier['supplier_phone'] ?? 'Chưa có'); ?></span></div>
                        <div class="col-md-4 info-item"><span class="info-label">Mã số thuế:</span><span class="info-value"><?php echo htmlspecialchars($supplier['tax_code'] ?? 'Chưa có'); ?></span></div>
                        <div class="col-md-12 info-item"><span class="info-label">Địa chỉ:</span><span class="info-value"><?php echo htmlspecialchars($supplier['supplier_addr'] ?? 'Chưa có'); ?></span></div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-lg-12">
            <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">Lịch sử nhập hàng</h6>
                    <?php if ($total_debt > 0): ?>
                        <button class="btn btn-danger btn-sm" data-bs-toggle="modal" data-bs-target="#payDebtModal"><i class="fas fa-dollar-sign fa-sm"></i> Trả nợ NCC</button>
                    <?php endif; ?>
                </div>
                <div class="card-body p-0">
                    <div class="table-responsive">
                        <table class="table table-hover mb-0" id="importHistoryTable" width="100%" cellspacing="0">
                            <thead>
                                <tr>
                                    <th></th>
                                    <th>Mã phiếu nhập</th>
                                    <th>Ngày nhập</th>
                                    <th>Người tạo</th>
                                    <th class="text-end">Tổng tiền</th>
                                    <th class="text-end">Đã trả</th>
                                    <th class="text-end">Còn nợ</th>
                                    <th class="text-center">Hành động</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php if (!empty($import_history)): foreach ($import_history as $slip): ?>
                                    <tr data-import-id="<?php echo $slip['ID']; ?>">
                                        <td class="details-control text-center"><i class="fas fa-plus-circle text-primary"></i></td>
                                        <td><a href="/quanlybanhang/modules/imports/tao_phieunhap.php?id=<?php echo $slip['ID']; ?>" class="fw-bold"><?php echo htmlspecialchars($slip['input_code']); ?></a></td>
                                        <td><?php echo date('d/m/Y H:i', strtotime($slip['input_date'])); ?></td>
                                        <td><?php echo htmlspecialchars($slip['creator_name'] ?? 'N/A'); ?></td>
                                        <td class="text-end"><?php echo number_format($slip['total_money']); ?></td>
                                        <td class="text-end"><?php echo number_format($slip['payed']); ?></td>
                                        <td class="text-end fw-bold text-danger"><?php echo number_format($slip['lack']); ?></td>
                                        <td class="text-center"><a href="/quanlybanhang/modules/imports/print_slip.php?id=<?php echo $slip['ID']; ?>" class="btn btn-sm btn-info" target="_blank" title="In phiếu"><i class="fas fa-print"></i></a></td>
                                    </tr>
                                <?php endforeach; else: ?><tr><td colspan="8" class="text-center p-4">Chưa có lịch sử nhập hàng.</td></tr><?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
                <div class="card-footer d-flex justify-content-end fw-bold"><span>Tổng số phiếu: <span class="text-primary"><?php echo $total_slips; ?></span></span><span class="ms-4">Tổng nhập: <span class="text-primary"><?php echo number_format($total_spent); ?></span></span><span class="ms-4">Tổng nợ: <span class="text-danger"><?php echo number_format($total_debt); ?></span></span></div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="payDebtModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header"><h5 class="modal-title">Trả nợ nhà cung cấp: <?php echo htmlspecialchars($supplier['supplier_name']); ?></h5><button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
            <div class="modal-body">
                <div class="table-responsive"><table class="table">
                    <thead class="table-light"><tr><th>Mã PN</th><th>Ngày nhập</th><th class="text-end">Nợ</th><th style="width:180px;">Số tiền trả</th><th style="width:100px;"></th></tr></thead>
                    <tbody>
                        <?php foreach ($debt_slips as $slip): ?>
                        <tr class="debt-row" data-import-id="<?php echo $slip['ID']; ?>">
                            <td><?php echo htmlspecialchars($slip['input_code']); ?></td>
                            <td><?php echo date('d/m/Y', strtotime($slip['input_date'])); ?></td>
                            <td class="text-end text-danger fw-bold"><?php echo number_format($slip['lack']); ?></td>
                            <td><input type="number" class="form-control form-control-sm amount-to-pay" placeholder="Nhập số tiền" max="<?php echo $slip['lack']; ?>"></td>
                            <td><button class="btn btn-sm btn-primary btn-pay-single">Trả</button></td>
                        </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table></div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="supplierModal" tabindex="-1">
    </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>
$(document).ready(function() {
    function formatChildRow(items) {
        if (!items || items.length === 0) return '<div class="p-3 text-center text-muted">Không có dữ liệu.</div>';
        
        let totalQty = 0;
        let totalAmount = 0;
        let rowsHtml = '';
        const formatVNCurrency = (num) => (num || 0).toLocaleString('vi-VN');

        items.forEach((item, index) => {
            let quantity = parseFloat(item.quantity) || 0;
            let price = parseFloat(item.price) || 0;
            let lineTotal = quantity * price;
            totalQty += quantity;
            totalAmount += lineTotal;
            rowsHtml += `<tr><td>${index + 1}</td><td>${item.code || 'N/A'}</td><td>${item.name || 'N/A'}</td><td class="text-center">${formatVNCurrency(quantity)}</td><td class="text-end">${formatVNCurrency(price)}</td><td class="text-end fw-bold">${formatVNCurrency(lineTotal)}</td></tr>`;
        });

        let summaryHtml = `<div class="child-row-container"><div class="child-summary"><span>Số lượng SP: <strong>${formatVNCurrency(totalQty)}</strong></span><span>Tổng tiền hàng: <strong>${formatVNCurrency(totalAmount)}</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>Giá nhập</th><th>Thành tiền</th></tr></thead><tbody>${rowsHtml}</tbody></table></div>`;
        return summaryHtml + productsHtml;
    }

    $('#importHistoryTable tbody').on('click', 'td.details-control', function () {
        var tr = $(this).closest('tr');
        var icon = $(this).find('i');
        var importId = tr.data('import-id');
        var colCount = tr.prop('cells').length;
        var is_open = tr.next().hasClass('child-row');

        $('#importHistoryTable tbody tr.child-row').remove();
        $('#importHistoryTable tbody td.details-control i').removeClass('fa-minus-circle text-danger').addClass('fa-plus-circle text-primary');
        
        if (is_open) { return; }
        if (!importId) { 
            alert('Lỗi: Không tìm thấy ID phiếu nhập.');
            return;
        }

        icon.removeClass('fa-plus-circle text-primary').addClass('fa-spinner fa-spin');
        var loadingRow = $('<tr class="child-row"><td colspan="' + colCount + '"><div class="p-3 text-center">Đang tải...</div></td></tr>');
        tr.after(loadingRow);
        
        $.ajax({
            url: '/quanlybanhang/ajax/imports_ajax.php',
            type: 'POST',
            dataType: 'json',
            data: { action: 'get_import_details', import_id: importId },
            success: function(response) {
                loadingRow.remove();
                if (response.status === 'success') {
                    var detailHtml = formatChildRow(response.data);
                    var detailRow = $('<tr class="child-row"><td colspan="' + colCount + '">' + detailHtml + '</td></tr>');
                    tr.after(detailRow);
                    icon.removeClass('fa-spinner fa-spin').addClass('fa-minus-circle text-danger');
                } else {
                    var errorRow = $('<tr class="child-row"><td colspan="' + colCount + '"><div class="p-3 text-center text-danger">Lỗi: ' + response.message + '</div></td></tr>');
                    tr.after(errorRow);
                    icon.removeClass('fa-spinner fa-spin').addClass('fa-plus-circle text-primary');
                }
            },
            error: function() {
                loadingRow.remove();
                var errorRow = $('<tr class="child-row"><td colspan="' + colCount + '"><div class="p-3 text-center text-danger">Lỗi kết nối.</div></td></tr>');
                tr.after(errorRow);
                icon.removeClass('fa-spinner fa-spin').addClass('fa-plus-circle text-primary');
            }
        });
    });
    
    $('#payDebtModal').on('click', '.btn-pay-single', function() {
        var $button = $(this), $row = $button.closest('tr'), importId = $row.data('import-id'), amount = $row.find('.amount-to-pay').val();
        if (!amount || parseInt(amount) <= 0) { alert('Vui lòng nhập số tiền hợp lệ.'); return; }
        if (confirm(`Bạn có chắc muốn trả nợ ${parseInt(amount).toLocaleString('vi-VN')} cho phiếu nhập này?`)) {
            $button.prop('disabled', true).html('<span class="spinner-border spinner-border-sm"></span>');
            $.ajax({
                url: '/quanlybanhang/ajax/suppliers_ajax.php', type: 'POST', dataType: 'json', 
                data: { action: 'pay_debt', import_id: importId, amount: amount },
                success: function(response) { 
                    alert(response.message); 
                    if (response.status === 'success') { 
                        location.reload(); 
                    } else { 
                        $button.prop('disabled', false).text('Trả'); 
                    } 
                },
                error: function() { 
                    alert('Lỗi khi gửi yêu cầu trả nợ.'); 
                    $button.prop('disabled', false).text('Trả'); 
                }
            });
        }
    });
});
</script>