<?php
session_start();
require_once __DIR__ . '/../../../core/init.php';

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

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

$whereClauses = ["o.deleted = 0", "o.order_status > 0", "o.user_init = ?"];
$params = [$logged_in_user_id];
$types = 'i';

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

$total_revenue_card = 0;
$total_cost_card = 0;
$gross_profit_card = 0;

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

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

$report_data = [];
$sql_report = "SELECT o.output_code, 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";
$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();
?>

<div class="container-fluid pt-3 pb-5">
    <h4 class="mb-3">Báo cáo Lợi nhuận</h4>

    <div class="accordion mb-3" id="profitFilterAccordion">
        <div class="accordion-item">
            <h2 class="accordion-header">
                <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseProfitFilter">
                    <i class="fas fa-filter me-2"></i> Lọc theo ngày
                </button>
            </h2>
            <div id="collapseProfitFilter" class="accordion-collapse collapse" data-bs-parent="#profitFilterAccordion">
                <div class="accordion-body">
                    <form id="profit-filter-form">
                        <div class="row g-2 align-items-end">
                            <div class="col"><input type="date" id="profit_from_date" name="from" class="form-control form-control-sm" value="<?php echo htmlspecialchars($from_date); ?>"></div>
                            <div class="col"><input type="date" id="profit_to_date" name="to" class="form-control form-control-sm" value="<?php echo htmlspecialchars($to_date); ?>"></div>
                            <div class="col-auto"><button type="button" id="btn-filter-profit" class="btn btn-primary btn-sm w-100">Lọc</button></div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    
    <div class="row g-2 mb-3">
        <div class="col-4">
            <div class="card p-2 text-center bg-light h-100">
                <div class="small text-muted">DOANH SỐ</div>
                <div class="fw-bold text-primary"><?php echo number_format($total_revenue_card); ?></div>
            </div>
        </div>
        <div class="col-4">
            <div class="card p-2 text-center bg-light h-100">
                <div class="small text-muted">TIỀN VỐN</div>
                <div class="fw-bold text-secondary"><?php echo number_format($total_cost_card); ?></div>
            </div>
        </div>
        <div class="col-4">
            <div class="card p-2 text-center bg-light h-100">
                <div class="small text-muted">LỢI NHUẬN</div>
                <div class="fw-bold text-success"><?php echo number_format($gross_profit_card); ?></div>
            </div>
        </div>
    </div>
    
    <div class="card shadow-sm mb-3">
        <div class="card-body">
            <h6 class="card-title text-center text-primary mb-3">Lợi nhuận theo ngày</h6>
            <canvas id="profitLineChart"></canvas>
            <script>
                window.profitChartData = {
                    labels: <?php echo json_encode($chart_labels); ?>,
                    data: <?php echo json_encode($chart_data); ?>
                };
            </script>
        </div>
    </div>

    <div class="card shadow-sm mb-3">
         <div class="card-body">
            <h6 class="card-title text-center text-primary mb-3">Cơ cấu Doanh số</h6>
            <div style="max-width: 200px; margin: auto;">
                <canvas id="profitDoughnutChart" data-profit="<?php echo $gross_profit_card; ?>" data-cost="<?php echo $total_cost_card; ?>"></canvas>
            </div>
        </div>
    </div>
    
    <h5 class="mb-2">Chi tiết theo đơn hàng</h5>
    <div class="list-group">
    <?php if (empty($report_data)): ?>
        <p class="text-center text-muted mt-3">Không có dữ liệu trong khoảng thời gian này.</p>
    <?php else: ?>
        <?php foreach($report_data as $row): ?>
        <?php
            $profit_margin = ($row['revenue'] > 0) ? ($row['profit'] / $row['revenue']) * 100 : 0;
            $margin_class = 'text-success';
            if ($profit_margin < 10) {
                $margin_class = 'text-danger';
            } elseif ($profit_margin < 25) {
                $margin_class = 'text-warning';
            }
        ?>
        <div class="list-group-item list-group-item-action mb-2 border rounded">
            <div class="d-flex w-100 justify-content-between">
                <h6 class="mb-1 fw-bold text-primary"><?php echo htmlspecialchars($row['output_code']); ?></h6>
                <strong class="text-success"><?php echo number_format($row['profit']); ?> đ</strong>
            </div>
            <p class="mb-1 small">KH: <strong><?php echo htmlspecialchars($row['customer_name'] ?? 'Khách lẻ'); ?></strong></p>
            <div class="d-flex w-100 justify-content-between">
                <small class="text-muted">DS: <?php echo number_format($row['revenue']); ?> - Vốn: <?php echo number_format($row['cost']); ?></small>
                <small class="fw-bold <?php echo $margin_class; ?>">Tỷ suất: <?php echo round($profit_margin, 1); ?>%</small>
            </div>
        </div>
        <?php endforeach; ?>
    <?php endif; ?>
    </div>
</div>