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

$from_date = $_GET['from'] ?? date('Y-m-01');
$to_date = $_GET['to'] ?? date('Y-m-d');

$params_date_range = [$from_date . ' 00:00:00', $to_date . ' 23:59:59'];
$types_date_range = 'ss';

// --- [ĐIỀU CHỈNH CUỐI CÙNG] ---
// Dựa theo file payment_helpers.php, ID của "Chi nhập hàng" là 3.
// Chúng ta sẽ loại trừ chính xác ID này.
$inventory_expense_type_id = 3; 

// --- Tính lợi nhuận gộp (Không thay đổi) ---
$gross_profit = 0;
$sql_profit = "SELECT SUM(total_money - total_origin_price) as total_profit FROM cms_orders WHERE deleted = 0 AND order_status > 0 AND sell_date BETWEEN ? AND ?";
$stmt_profit = $conn->prepare($sql_profit);
if ($stmt_profit) {
    $stmt_profit->bind_param($types_date_range, $params_date_range[0], $params_date_range[1]);
    $stmt_profit->execute();
    $profit_result = $stmt_profit->get_result()->fetch_assoc();
    $gross_profit = $profit_result['total_profit'] ?? 0;
    $stmt_profit->close();
}

// --- Tính tổng chi phí hoạt động: Lấy tất cả chi phí, TRỪ chi phí nhập hàng (type_id = 3) ---
$total_expenses = 0;
$sql_expenses = "SELECT SUM(total_money) as total_chi FROM cms_payment WHERE deleted = 0 AND type_id != ? AND payment_date BETWEEN ? AND ?";
$stmt_expenses = $conn->prepare($sql_expenses);
if ($stmt_expenses) {
    $stmt_expenses->bind_param("iss", $inventory_expense_type_id, $params_date_range[0], $params_date_range[1]);
    $stmt_expenses->execute();
    $expenses_result = $stmt_expenses->get_result()->fetch_assoc();
    $total_expenses = $expenses_result['total_chi'] ?? 0;
    $stmt_expenses->close();
}

$net_profit = $gross_profit - $total_expenses;

// --- Lấy chi tiết đơn hàng (Không thay đổi) ---
$orders_data = [];
$sql_orders = "SELECT o.id as order_id, o.output_code, c.customer_name, o.total_money, o.total_origin_price, (o.total_money - o.total_origin_price) as profit 
               FROM cms_orders o
               LEFT JOIN cms_customers c ON o.customer_id = c.ID
               WHERE o.deleted = 0 AND o.order_status > 0 AND o.sell_date BETWEEN ? AND ? 
               ORDER BY o.id DESC";
$stmt_orders = $conn->prepare($sql_orders);
if ($stmt_orders) {
    $stmt_orders->bind_param($types_date_range, $params_date_range[0], $params_date_range[1]);
    $stmt_orders->execute();
    $orders_data = $stmt_orders->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_orders->close();
}

// --- Lấy danh sách chi tiết chi phí hoạt động: TRỪ chi phí nhập hàng (type_id = 3) ---
$expenses_data = [];
$sql_expenses_list = "SELECT id, total_money, notes, payment_date FROM cms_payment WHERE deleted = 0 AND type_id != ? AND payment_date BETWEEN ? AND ? ORDER BY id DESC";
$stmt_expenses_list = $conn->prepare($sql_expenses_list);
if ($stmt_expenses_list) {
    $stmt_expenses_list->bind_param("iss", $inventory_expense_type_id, $params_date_range[0], $params_date_range[1]);
    $stmt_expenses_list->execute();
    $expenses_data = $stmt_expenses_list->get_result()->fetch_all(MYSQLI_ASSOC);
    $stmt_expenses_list->close();
}
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<style>
    .summary-card-profit { background-color:#fff; border:none; border-radius:0.75rem; box-shadow:0 .15rem 1.75rem 0 rgba(58,59,69,.15)!important; transition:all .2s ease-in-out; }
    .summary-card-profit:hover { transform: translateY(-5px); }
    .summary-card-profit .card-body { padding: 1.5rem; display: flex; justify-content: space-between; align-items: center; }
    .summary-card-profit .text-content .label { font-size:0.8rem; font-weight:700; text-transform:uppercase; margin-bottom:0.25rem; }
    .summary-card-profit .text-content .value { font-size:1.75rem; font-weight:700; }
    .summary-card-profit .icon-circle { width:50px; height:50px; border-radius:50%; display:flex; align-items:center; justify-content:center; color:white; font-size:1.5rem; }
    #ordersTable thead th, #expensesTable thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; }
    .note { font-size: 0.9rem; font-style: italic; color: #20c997; margin-top: -0.25rem; font-weight: 500;}
    .details-control { cursor: pointer; width: 25px; }
    .child-row-container { padding:1rem; background-color:#f8f9fc; border-left:3px solid #4e73df; margin:5px 0; }
</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">Báo cáo lợi nhuận ròng</h1>
        <a href="index.php" class="btn btn-secondary shadow-sm"><i class="fas fa-arrow-left fa-sm text-white-50"></i> Quay lại Lợi nhuận gộp</a>
    </div>
    
    <div class="row">
        <div class="col-xl-4 col-md-6 mb-4"><div class="card summary-card-profit"><div class="card-body"><div class="text-content"><div class="label" style="color:#1cc88a;">Lợi nhuận gộp</div><div class="value text-gray-800"><?php echo number_format($gross_profit); ?></div></div><div class="icon-circle" style="background-color:#1cc88a;"><i class="fas fa-wallet"></i></div></div></div></div>
        <div class="col-xl-4 col-md-6 mb-4"><div class="card summary-card-profit"><div class="card-body"><div class="text-content"><div class="label" style="color:#e74a3b;">Chi phí hoạt động</div><div class="value text-gray-800"><?php echo number_format($total_expenses); ?></div></div><div class="icon-circle" style="background-color:#e74a3b;"><i class="fas fa-receipt"></i></div></div></div></div>
        <div class="col-xl-4 col-md-6 mb-4"><div class="card summary-card-profit"><div class="card-body"><div class="text-content"><div class="label" style="color:#4e73df;">Lợi nhuận ròng</div><div class="value font-weight-bold" style="color:#4e73df;"><?php echo number_format($net_profit); ?></div><p class="note">Lợi nhuận cuối cùng sau khi trừ chi phí</p></div><div class="icon-circle" style="background-color:#4e73df;"><i class="fas fa-chart-pie"></i></div></div></div></div>
    </div>

    <div class="card shadow mb-4">
        <div class="card-body">
            <form method="GET">
                <div class="row align-items-end">
                    <div class="col-md-3 mb-3"><label class="form-label">Từ ngày</label><input type="text" class="form-control" name="from" value="<?php echo htmlspecialchars($from_date); ?>"></div>
                    <div class="col-md-3 mb-3"><label class="form-label">Đến ngày</label><input type="text" class="form-control" name="to" value="<?php echo htmlspecialchars($to_date); ?>"></div>
                    <div class="col-md-3 mb-3"><button type="submit" class="btn btn-primary w-100"><i class="fas fa-search fa-sm mr-2"></i>Xem báo cáo</button></div>
                </div>
            </form>
        </div>
    </div>

    <div class="row">
        <div class="col-lg-7">
            <div class="card shadow mb-4">
                <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Chi tiết Lợi nhuận gộp theo Đơn hàng</h6></div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover" id="ordersTable" width="100%" cellspacing="0">
                            <thead><tr><th></th><th>Mã ĐH</th><th>Khách hàng</th><th class="text-end">Doanh số</th><th class="text-end">Tiền vốn</th><th class="text-end">Lợi nhuận</th></tr></thead>
                            <tbody>
                                <?php if (empty($orders_data)): ?>
                                    <tr><td colspan="6" class="text-center">Không có dữ liệu.</td></tr>
                                <?php else: foreach($orders_data as $row): ?>
                                    <tr data-id="<?php echo $row['order_id']; ?>">
                                        <td class="details-control text-center"><i class="fas fa-plus-circle text-primary"></i></td>
                                        <td><?php echo htmlspecialchars($row['output_code']); ?></td>
                                        <td><?php echo htmlspecialchars(empty($row['customer_name']) ? 'Khách lẻ' : $row['customer_name']); ?></td>
                                        <td class="text-end"><?php echo number_format($row['total_money']); ?></td>
                                        <td class="text-end"><?php echo number_format($row['total_origin_price']); ?></td>
                                        <td class="text-end fw-bold text-success"><?php echo number_format($row['profit']); ?></td>
                                    </tr>
                                <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-5">
            <div class="card shadow mb-4">
                <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-danger">Chi tiết Chi phí hoạt động (Phiếu chi)</h6></div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover" id="expensesTable" width="100%" cellspacing="0">
                            <thead><tr><th>Ngày chi</th><th>Lý do chi</th><th class="text-end">Số tiền</th></tr></thead>
                            <tbody>
                                <?php if (empty($expenses_data)): ?>
                                    <tr><td colspan="3" class="text-center">Không có dữ liệu.</td></tr>
                                <?php else: foreach($expenses_data as $row): ?>
                                    <tr>
                                        <td><?php echo date('d/m/Y', strtotime($row['payment_date'])); ?></td>
                                        <td><?php echo htmlspecialchars($row['notes']); ?></td>
                                        <td class="text-end text-danger"><?php echo number_format($row['total_money']); ?></td>
                                    </tr>
                                <?php endforeach; endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </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" };
    flatpickr('input[name="from"]', { ...fp_config, defaultDate: "<?php echo $from_date; ?>" });
    flatpickr('input[name="to"]', { ...fp_config, defaultDate: "<?php echo $to_date; ?>" });

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

        $('#ordersTable tbody tr.child-row').remove();
        $('#ordersTable tbody td.details-control i').removeClass('fa-minus-circle text-danger').addClass('fa-plus-circle text-primary');

        if (is_open) { return; }
        if (!dataId) 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/orders_ajax.php',
            type: 'POST',
            dataType: 'json',
            data: { action: 'get_order_details', order_id: dataId },
            success: function(response) {
                loadingRow.remove();
                if (response.status === 'success') {
                    var detailHtml = formatOrderDetails(response);
                    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');
            }
        });
    });
    
    function formatOrderDetails(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);
        const formatVNCurrency = (num) => (num || 0).toLocaleString('vi-VN');

        let summaryHtml = `<div class="child-row-container"><div class="child-summary"><span>Số lượng SP: <strong>${formatVNCurrency(order.total_quantity)}</strong></span><span>Tiền hàng: <strong>${formatVNCurrency(order.total_price)}</strong></span><span>Giảm giá: <strong>${formatVNCurrency(totalDiscount)}</strong></span><span>Tổng tiền: <strong>${formatVNCurrency(order.total_money)}</strong></span><span>Còn nợ: <strong>${formatVNCurrency(order.lack)}</strong></span></div>`;
        let productsHtml = `<table class="table table-sm table-bordered"><thead><tr><th>STT</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>${formatVNCurrency(item.quantity)}</td><td>${formatVNCurrency(item.price)}</td><td>${formatVNCurrency(lineTotal)}</td></tr>`;
            });
        }
        productsHtml += '</tbody></table></div>';
        return summaryHtml + productsHtml;
    }
});
</script>