<?php
// File: /quanlybanhang/modules/pos/tabs/profit_tab.php
require_once __DIR__ . '/../../../core/init.php';

if (!isset($_SESSION['user_id'])) {
    echo '<div class="text-center p-5">Vui lòng đăng nhập lại.</div>';
    exit();
}

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

$whereClauses = ["o.deleted = 0", "o.order_status = 1"];
$params = [];
$types = '';

$whereClauses[] = "o.sell_date BETWEEN ? AND ?";
$params[] = $from_date . ' 00:00:00';
$params[] = $to_date . ' 23:59:59';
$types .= 'ss';

$orderWhereSql = " WHERE " . implode(' AND ', $whereClauses);

function refValues($arr){ $refs = []; foreach($arr as $key => $value) $refs[$key] = &$arr[$key]; return $refs; }
function bind_dynamic_params($stmt, $types, $params) { if (!empty($types)) call_user_func_array([$stmt, 'bind_param'], refValues(array_merge([$types], $params))); }

// 1. Tổng hợp số liệu
$sql_summary = "SELECT SUM(total_money) as total_revenue, SUM(total_origin_price) as total_cost FROM cms_orders o" . $orderWhereSql;
$stmt_summary = $conn->prepare($sql_summary);
bind_dynamic_params($stmt_summary, $types, $params);
$stmt_summary->execute();
$summary_result = $stmt_summary->get_result()->fetch_assoc();
$total_revenue_card = $summary_result['total_revenue'] ?? 0;
$total_cost_card = $summary_result['total_cost'] ?? 0;
$gross_profit_card = $total_revenue_card - $total_cost_card;
$stmt_summary->close();

// 2. Biểu đồ Line
$chart_labels = [];
$chart_data = [];
$sql_chart = "SELECT DATE_FORMAT(sell_date, '%d/%m') as day, SUM(total_money - total_origin_price) as daily_profit FROM cms_orders o " . $orderWhereSql . " GROUP BY DATE(sell_date) ORDER BY DATE(sell_date)";
$stmt_chart = $conn->prepare($sql_chart);
bind_dynamic_params($stmt_chart, $types, $params);
$stmt_chart->execute();
$chart_result = $stmt_chart->get_result()->fetch_all(MYSQLI_ASSOC);
foreach($chart_result as $row) {
    $chart_labels[] = $row['day'];
    $chart_data[] = $row['daily_profit'];
}
$stmt_chart->close();

// 3. Chi tiết
$report_data = [];
$sql_report = "SELECT o.output_code, o.sell_date, o.total_money as revenue, o.total_origin_price as cost, (o.total_money - o.total_origin_price) as profit, c.customer_name 
               FROM cms_orders o LEFT JOIN cms_customers c ON o.customer_id = c.ID" . $orderWhereSql . " ORDER BY o.id DESC LIMIT 50";
$stmt_report = $conn->prepare($sql_report);
bind_dynamic_params($stmt_report, $types, $params);
$stmt_report->execute();
$report_data = $stmt_report->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_report->close();
?>

<style>
    .profit-card { background: #fff; border-radius: 12px; padding: 10px; box-shadow: 0 2px 6px rgba(0,0,0,0.05); border: 1px solid #f0f0f0; height: 100%; text-align: center; }
    .profit-label { font-size: 0.7rem; color: #6c757d; text-transform: uppercase; font-weight: 700; margin-bottom: 5px; }
    .profit-value { font-size: 0.9rem; font-weight: 800; word-break: break-word; }
    .text-revenue { color: #0d6efd; }
    .text-cost { color: #fd7e14; }
    .text-profit { color: #198754; }
    .chart-container { background: #fff; border-radius: 12px; padding: 15px; margin-bottom: 15px; box-shadow: 0 2px 6px rgba(0,0,0,0.05); }
    .list-item-profit { background: #fff; border-radius: 8px; padding: 10px; margin-bottom: 8px; border-left: 4px solid #ddd; box-shadow: 0 1px 2px rgba(0,0,0,0.05); }
    .list-item-profit.high { border-left-color: #198754; }
    .list-item-profit.medium { border-left-color: #ffc107; }
    .list-item-profit.low { border-left-color: #dc3545; }
</style>

<div class="container-fluid pt-3 pb-5">
    <div class="card border-0 shadow-sm mb-3 rounded-3">
        <div class="card-body p-2">
            <div class="row g-2 align-items-center">
                <div class="col-5"><input type="date" id="profit_from_date" class="form-control form-control-sm" value="<?php echo htmlspecialchars($from_date); ?>"></div>
                <div class="col-5"><input type="date" id="profit_to_date" class="form-control form-control-sm" value="<?php echo htmlspecialchars($to_date); ?>"></div>
                <div class="col-2"><button type="button" id="btn-filter-profit" class="btn btn-primary btn-sm w-100"><i class="fas fa-filter"></i></button></div>
            </div>
        </div>
    </div>
    
    <div class="row g-2 mb-3">
        <div class="col-4"><div class="profit-card"><div class="profit-label">Doanh số</div><div class="profit-value text-revenue"><?php echo number_format($total_revenue_card); ?></div></div></div>
        <div class="col-4"><div class="profit-card"><div class="profit-label">Tiền vốn</div><div class="profit-value text-cost"><?php echo number_format($total_cost_card); ?></div></div></div>
        <div class="col-4"><div class="profit-card"><div class="profit-label">Lợi nhuận</div><div class="profit-value text-profit"><?php echo number_format($gross_profit_card); ?></div></div></div>
    </div>
    
    <div class="chart-container">
        <h6 class="fw-bold text-secondary mb-3 small text-uppercase"><i class="fas fa-chart-line me-2"></i>Xu hướng lợi nhuận</h6>
        <div style="height: 200px;"><canvas id="profitLineChart"></canvas></div>
    </div>

    <div class="chart-container">
        <h6 class="fw-bold text-secondary mb-3 small text-uppercase"><i class="fas fa-chart-pie me-2"></i>Tỷ lệ Lợi nhuận / Vốn</h6>
        <div style="height: 180px; display: flex; justify-content: center;"><canvas id="profitDoughnutChart"></canvas></div>
    </div>
    
    <h6 class="fw-bold text-secondary mb-2 mt-3 small text-uppercase ps-1">Chi tiết đơn hàng (50 đơn mới nhất)</h6>
    <div class="profit-list pb-5">
    <?php if (empty($report_data)): ?>
        <div class="text-center text-muted py-4 small">Không có dữ liệu.</div>
    <?php else: ?>
        <?php foreach($report_data as $row): ?>
        <?php
            $margin = ($row['revenue'] > 0) ? ($row['profit'] / $row['revenue']) * 100 : 0;
            $color_class = ($margin >= 30) ? 'high' : (($margin >= 10) ? 'medium' : 'low');
        ?>
        <div class="list-item-profit <?php echo $color_class; ?>">
            <div class="d-flex justify-content-between align-items-center mb-1">
                <span class="fw-bold text-primary"><?php echo $row['output_code']; ?></span>
                <span class="fw-bold text-success">+<?php echo number_format($row['profit']); ?></span>
            </div>
            <div class="d-flex justify-content-between small text-muted">
                <span><?php echo $row['customer_name']; ?></span>
                <span><?php echo date('d/m H:i', strtotime($row['sell_date'])); ?></span>
            </div>
            <div class="d-flex justify-content-between small mt-1 border-top pt-1">
                <span>DS: <?php echo number_format($row['revenue']); ?></span>
                <span class="<?php echo ($margin < 10) ? 'text-danger' : 'text-success'; ?> fw-bold">Lãi: <?php echo round($margin, 1); ?>%</span>
            </div>
        </div>
        <?php endforeach; ?>
    <?php endif; ?>
    </div>
</div>

<script>
$(function() {
    // Xử lý Filter
    $('#btn-filter-profit').off('click').on('click', function() {
        let from = $('#profit_from_date').val();
        let to = $('#profit_to_date').val();
        // Gọi lại AJAX load
        let url = `/quanlybanhang/modules/pos/tabs/profit_tab.php?from=${from}&to=${to}`;
        $('#dynamic-content').load(url);
    });

    // Hủy biểu đồ cũ nếu tồn tại (để tránh lỗi đè hình)
    if (window.myProfitLineChart instanceof Chart) { window.myProfitLineChart.destroy(); }
    if (window.myProfitDoughnutChart instanceof Chart) { window.myProfitDoughnutChart.destroy(); }

    // Vẽ biểu đồ Line
    const ctxLine = document.getElementById('profitLineChart');
    if (ctxLine) {
        window.myProfitLineChart = new Chart(ctxLine, {
            type: 'line',
            data: {
                labels: <?php echo json_encode($chart_labels); ?>,
                datasets: [{
                    label: 'Lợi nhuận',
                    data: <?php echo json_encode($chart_data); ?>,
                    borderColor: '#198754',
                    backgroundColor: 'rgba(25, 135, 84, 0.1)',
                    tension: 0.3, fill: true, pointRadius: 3
                }]
            },
            options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true } } }
        });
    }

    // Vẽ biểu đồ Doughnut
    const ctxDoughnut = document.getElementById('profitDoughnutChart');
    if (ctxDoughnut) {
        window.myProfitDoughnutChart = new Chart(ctxDoughnut, {
            type: 'doughnut',
            data: {
                labels: ['Tiền Vốn', 'Lợi Nhuận'],
                datasets: [{
                    data: [<?php echo $total_cost_card; ?>, <?php echo $gross_profit_card; ?>],
                    backgroundColor: ['#fd7e14', '#198754'],
                    borderWidth: 0
                }]
            },
            options: { responsive: true, maintainAspectRatio: false, cutout: '65%', plugins: { legend: { position: 'right', labels: { boxWidth: 12, font: { size: 11 } } } } }
        });
    }
});
</script>