<?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.'); }

// LẤY LỊCH SỬ NHẬP HÀNG
// QUAN TRỌNG: Sắp xếp theo ngày nhập mới nhất (input_date DESC) thay vì theo nợ
$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.input_date DESC"; // Sửa chỗ này để hiện phiếu mới nhất

$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();

// Tính toán tổng quan
$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 { width: 100% !important; }
    #importHistoryTable thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; white-space: nowrap; }
    #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:#fff; border-left:3px solid #4e73df; margin:5px 0; border: 1px solid #e3e6f0; }
    .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); margin-right: 5px;}
    .child-summary span:nth-child(1) { background-color:#4e73df; }
    .child-summary span:nth-child(2) { background-color:#1cc88a; }
    .debt-high { color: #e74a3b; font-weight: bold; }
    .paid-done { color: #1cc88a; font-weight: bold; }
</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" id="btnEditSupplier"><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 mb-4">
            <div class="card shadow">
                <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Thông tin chung</h6></div>
                <div class="card-body supplier-info-card">
                    <div class="row">
                        <div class="col-md-3 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-3 info-item"><span class="info-label">Điện thoại:</span><span class="info-value"><?php echo htmlspecialchars($supplier['supplier_phone'] ?? '-'); ?></span></div>
                        <div class="col-md-3 info-item"><span class="info-label">Mã số thuế:</span><span class="info-value"><?php echo htmlspecialchars($supplier['tax_code'] ?? '-'); ?></span></div>
                        <div class="col-md-3 info-item"><span class="info-label">Tổng nợ hiện tại:</span><span class="info-value text-danger fw-bold"><?php echo number_format($total_debt); ?> ₫</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'] ?? '-'); ?></span></div>
                        <div class="col-md-12 info-item"><span class="info-label">Ghi chú:</span><span class="info-value"><?php echo htmlspecialchars($supplier['notes'] ?? '-'); ?></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ử phiếu nhập (<?php echo $total_slips; ?> phiếu)</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-hand-holding-usd me-1"></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">
                            <thead>
                                <tr>
                                    <th style="width: 40px;"></th>
                                    <th>Mã phiếu</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">Thao tác</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 text-primary"><?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'] ?? 'Admin'); ?></td>
                                        <td class="text-end fw-bold"><?php echo number_format($slip['total_money']); ?></td>
                                        <td class="text-end text-success"><?php echo number_format($slip['payed']); ?></td>
                                        <td class="text-end <?php echo ($slip['lack'] > 0) ? 'debt-high' : 'paid-done'; ?>">
                                            <?php echo ($slip['lack'] > 0) ? number_format($slip['lack']) : '<i class="fas fa-check-circle"></i> Xong'; ?>
                                        </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 text-muted">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 class="me-4">Tổng nhập: <span class="text-primary"><?php echo number_format($total_spent); ?> ₫</span></span>
                    <span>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 bg-light">
                <h5 class="modal-title text-danger"><i class="fas fa-file-invoice-dollar me-2"></i>Trả nợ: <?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="alert alert-info small"><i class="fas fa-info-circle me-1"></i> Chỉ hiển thị các phiếu còn nợ. Nhập số tiền vào ô bên cạnh phiếu cần trả.</div>
                <div class="table-responsive" style="max-height: 400px; overflow-y: auto;">
                    <table class="table table-bordered table-sm">
                        <thead class="table-light position-sticky top-0">
                            <tr>
                                <th>Mã phiếu</th>
                                <th>Ngày nhập</th>
                                <th class="text-end">Nợ hiện tại</th>
                                <th style="width:180px;">Số tiền trả</th>
                                <th style="width:80px;"></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php if(empty($debt_slips)): ?>
                                <tr><td colspan="5" class="text-center text-success p-3"><i class="fas fa-check-circle me-2"></i>Không có phiếu nào còn nợ.</td></tr>
                            <?php else: foreach ($debt_slips as $slip): ?>
                            <tr class="debt-row" data-import-id="<?php echo $slip['id']; ?>">
                                <td class="align-middle fw-bold"><?php echo htmlspecialchars($slip['input_code']); ?></td>
                                <td class="align-middle"><?php echo date('d/m/Y', strtotime($slip['input_date'])); ?></td>
                                <td class="align-middle 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 text-end" placeholder="0" max="<?php echo $slip['lack']; ?>"></td>
                                <td class="text-center"><button class="btn btn-sm btn-primary btn-pay-single">Lưu</button></td>
                            </tr>
                            <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="modal fade" id="supplierModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Cập nhật Nhà cung cấp</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="supplierForm">
                    <input type="hidden" id="supplier_id" name="supplier_id" value="<?php echo $supplier['ID']; ?>">
                    <div class="row g-3">
                        <div class="col-md-6"><label class="form-label">Tên NCC <span class="text-danger">*</span></label><input type="text" class="form-control" name="supplier_name" value="<?php echo htmlspecialchars($supplier['supplier_name']); ?>" required></div>
                        <div class="col-md-6"><label class="form-label">Mã NCC</label><input type="text" class="form-control" name="supplier_code" value="<?php echo htmlspecialchars($supplier['supplier_code']); ?>"></div>
                        <div class="col-md-6"><label class="form-label">Điện thoại</label><input type="text" class="form-control" name="supplier_phone" value="<?php echo htmlspecialchars($supplier['supplier_phone']); ?>"></div>
                        <div class="col-md-6"><label class="form-label">Email</label><input type="email" class="form-control" name="supplier_email" value="<?php echo htmlspecialchars($supplier['supplier_email']); ?>"></div>
                        <div class="col-12"><label class="form-label">Địa chỉ</label><input type="text" class="form-control" name="supplier_address" value="<?php echo htmlspecialchars($supplier['supplier_addr']); ?>"></div>
                        <div class="col-md-6"><label class="form-label">Mã số thuế</label><input type="text" class="form-control" name="tax_code" value="<?php echo htmlspecialchars($supplier['tax_code']); ?>"></div>
                        <div class="col-md-6"><label class="form-label">Ghi chú</label><input type="text" class="form-control" name="note" value="<?php echo htmlspecialchars($supplier['notes']); ?>"></div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Đóng</button>
                <button type="button" class="btn btn-primary" id="btnSaveSupplier">Lưu lại</button>
            </div>
        </div>
    </div>
</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() {
    const supplierModal = new bootstrap.Modal(document.getElementById('supplierModal'));

    $('#btnEditSupplier').click(function() { supplierModal.show(); });

    $('#btnSaveSupplier').click(function() {
        $.post('/quanlybanhang/ajax/suppliers_ajax.php', $('#supplierForm').serialize() + '&action=edit_supplier', function(res) {
            alert(res.message);
            if(res.status === 'success') location.reload();
        }, 'json');
    });

    function formatChildRow(items) {
        if (!items || items.length === 0) return '<div class="p-3 text-center text-muted">Không có chi tiết sản phẩm.</div>';
        let totalQty = 0, totalAmount = 0, 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 || ''}</td><td>${item.name || 'SP Không tên'}</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>`;
        });
        return `<div class="child-row-container"><div class="child-summary"><span>Số lượng: <strong>${formatVNCurrency(totalQty)}</strong></span><span>Thành tiền: <strong>${formatVNCurrency(totalAmount)}</strong></span></div><table class="table table-sm table-striped mb-0" style="background:#fff"><thead><tr><th>#</th><th>Mã</th><th>Tên sản phẩm</th><th class="text-center">SL</th><th class="text-end">Đơn giá</th><th class="text-end">Tổng</th></tr></thead><tbody>${rowsHtml}</tbody></table></div>`;
    }

    $('#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;
        
        if (tr.next().hasClass('child-row')) { 
            tr.next().remove(); 
            icon.removeClass('fa-minus-circle text-danger').addClass('fa-plus-circle text-primary'); 
            return; 
        }
        
        icon.removeClass('fa-plus-circle text-primary').addClass('fa-spinner fa-spin');
        $.post('/quanlybanhang/ajax/suppliers_ajax.php', { action: 'get_import_details', import_id: importId }, function(res) {
            icon.removeClass('fa-spinner fa-spin').addClass('fa-minus-circle text-danger');
            if (res.status === 'success') {
                tr.after(`<tr class="child-row"><td colspan="${colCount}">${formatChildRow(res.data)}</td></tr>`);
            } else {
                alert('Lỗi tải dữ liệu: ' + res.message);
            }
        }, 'json');
    });

    $('#payDebtModal').on('click', '.btn-pay-single', function() {
        var $btn = $(this), $row = $btn.closest('tr'), amount = $row.find('.amount-to-pay').val();
        if (!amount || amount <= 0) return alert('Vui lòng nhập số tiền hợp lệ');
        
        if (confirm('Xác nhận thanh toán ' + parseInt(amount).toLocaleString('vi-VN') + ' đ cho phiếu này?')) {
            $btn.prop('disabled', true).text('Đang xử lý...');
            $.post('/quanlybanhang/ajax/suppliers_ajax.php', { action: 'pay_debt', import_id: $row.data('import-id'), amount: amount }, function(res) {
                alert(res.message);
                if(res.status === 'success') location.reload(); else { $btn.prop('disabled', false).text('Lưu'); }
            }, 'json');
        }
    });
});
</script>