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

// --- 1. KHỞI TẠO & LẤY DỮ LIỆU ĐẦU VÀO ---
$logged_in_user_id = $_SESSION['user_id'] ?? 0;
$logged_in_group_id = 0;
if ($logged_in_user_id > 0) {
    $stmt = $conn->prepare("SELECT group_id FROM cms_users WHERE id = ?");
    $stmt->bind_param('i', $logged_in_user_id);
    $stmt->execute();
    $res = $stmt->get_result()->fetch_assoc();
    if ($res) $logged_in_group_id = $res['group_id'];
    $stmt->close();
}

// Lấy danh sách hỗ trợ lọc
$customers = $conn->query("SELECT ID, customer_name FROM cms_customers ORDER BY customer_name ASC")->fetch_all(MYSQLI_ASSOC);
$users = $conn->query("SELECT id, display_name FROM cms_users WHERE user_status = 1 ORDER BY display_name ASC")->fetch_all(MYSQLI_ASSOC);
$stores = $conn->query("SELECT id, store_name FROM cms_stores ORDER BY store_name ASC")->fetch_all(MYSQLI_ASSOC);

// Tham số lọc
$group_by = $_GET['group_by'] ?? 'employee';
if ($logged_in_group_id != 1 && $group_by === 'employee') $group_by = 'order';

$from_date = $_GET['from'] ?? date('Y-m-01');
$to_date = $_GET['to'] ?? date('Y-m-d');
$customer_id = intval($_GET['customer_id'] ?? 0);
$user_id_filter = intval($_GET['user_id'] ?? 0);
$store_id = intval($_GET['store_id'] ?? 0);

// --- 2. LẤY THÔNG TIN SẢN PHẨM ĐỂ TÍNH VỐN (QUAN TRỌNG) ---
// Cache toàn bộ thông tin sản phẩm để tra cứu nhanh
$product_map = [];
$p_sql = "SELECT ID, prd_name, prd_type, prd_origin_price, prd_est_cost_percent FROM cms_products";
$p_res = $conn->query($p_sql);
while ($row = $p_res->fetch_assoc()) {
    $product_map[$row['ID']] = $row;
}

// --- 3. TRUY VẤN ĐƠN HÀNG & TÍNH TOÁN ---
$where = ["o.deleted = 0", "o.order_status = 1"]; // Chỉ đơn hoàn thành
$params = [];
$types = "";

if ($logged_in_group_id != 1) { $where[] = "o.user_init = ?"; $params[] = $logged_in_user_id; $types .= 'i'; }
$where[] = "DATE(o.sell_date) BETWEEN ? AND ?"; 
$params[] = $from_date; $params[] = $to_date; $types .= 'ss';

if ($customer_id > 0) { $where[] = "o.customer_id = ?"; $params[] = $customer_id; $types .= 'i'; }
if ($store_id > 0) { $where[] = "o.store_id = ?"; $params[] = $store_id; $types .= 'i'; }
if ($user_id_filter > 0) { $where[] = "o.user_init = ?"; $params[] = $user_id_filter; $types .= 'i'; }

$sql_orders = "SELECT o.id, o.output_code, o.sell_date, o.total_money, o.detail_order, 
                      o.user_init, u.display_name as user_name, 
                      o.customer_id, c.customer_name 
               FROM cms_orders o
               LEFT JOIN cms_users u ON o.user_init = u.id
               LEFT JOIN cms_customers c ON o.customer_id = c.ID
               WHERE " . implode(' AND ', $where) . " ORDER BY o.sell_date DESC";

$stmt = $conn->prepare($sql_orders);
if(!empty($types)) $stmt->bind_param($types, ...$params);
$stmt->execute();
$result_orders = $stmt->get_result();

// --- 4. XỬ LÝ DỮ LIỆU & GOM NHÓM (PHP CALCULATION) ---
$report_data = [];
$total_revenue_card = 0;
$total_cost_card = 0;

while ($order = $result_orders->fetch_assoc()) {
    $order_revenue = floatval($order['total_money']);
    $order_cost = 0;
    
    // TÍNH LẠI VỐN TỪNG MÓN TRONG ĐƠN
    $items = json_decode($order['detail_order'], true);
    if (is_array($items)) {
        foreach ($items as $item) {
            $pid = intval($item['id'] ?? 0);
            $qty = floatval($item['quantity'] ?? $item['qty'] ?? 0);
            $price = floatval($item['price'] ?? 0); // Giá bán tại thời điểm đó
            
            if (isset($product_map[$pid])) {
                $p_info = $product_map[$pid];
                if ($p_info['prd_type'] == 1) {
                    // Hàng chế biến: Vốn = Giá Bán * % Vốn
                    $cost_per_unit = $price * (floatval($p_info['prd_est_cost_percent']) / 100);
                } else {
                    // Hàng hóa: Vốn = Giá Nhập
                    $cost_per_unit = floatval($p_info['prd_origin_price']);
                }
                $order_cost += ($qty * $cost_per_unit);
            }
        }
    }

    $total_revenue_card += $order_revenue;
    $total_cost_card += $order_cost;

    // GOM NHÓM DỮ LIỆU
    $key = '';
    $name = '';
    
    if ($group_by == 'employee') {
        $key = $order['user_init'];
        $name = $order['user_name'] ?? 'N/A';
    } elseif ($group_by == 'customer') {
        $key = $order['customer_id'];
        $name = $order['customer_name'] ?? 'Khách lẻ';
    } else { // Order
        $key = $order['id'];
        $name = $order['output_code'];
    }

    if (!isset($report_data[$key])) {
        $report_data[$key] = [
            'id' => $key,
            'name' => $name,
            'count' => 0,
            'revenue' => 0,
            'cost' => 0,
            'profit' => 0,
            // Dữ liệu phụ cho xem theo đơn
            'date' => $order['sell_date'],
            'customer' => $order['customer_name']
        ];
    }

    $report_data[$key]['count']++;
    $report_data[$key]['revenue'] += $order_revenue;
    $report_data[$key]['cost'] += $order_cost;
    $report_data[$key]['profit'] += ($order_revenue - $order_cost);
}

$stmt->close();
$gross_profit_card = $total_revenue_card - $total_cost_card;

// Sắp xếp giảm dần theo lợi nhuận
usort($report_data, function($a, $b) { return $b['profit'] <=> $a['profit']; });

// --- CẤU HÌNH BẢNG ---
$table_headers = [];
if ($group_by == 'employee') $table_headers = ['Nhân viên', 'Số đơn', 'Doanh thu', 'Tiền vốn', 'Lợi nhuận'];
elseif ($group_by == 'customer') $table_headers = ['Khách hàng', 'Số đơn', 'Doanh thu', 'Tiền vốn', 'Lợi nhuận'];
else $table_headers = ['Mã đơn', 'Ngày bán', 'Khách hàng', 'Doanh thu', 'Tiền vốn', 'Lợi nhuận'];
?>

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css">
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.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; }
    
    /* Filter & Table */
    .filter-bar { background:#fff; padding:20px; border-radius:12px; box-shadow:0 2px 10px rgba(0,0,0,0.05); margin-bottom:20px; }
    .btn-group-toggle .btn.active { background-color: #0d6efd; color: white; border-color: #0d6efd; }
    .btn-quick-date { font-size: 0.85rem; padding: 4px 8px; }
    
    #dataTable thead th { background-color:#4e73df !important; color:#ffffff !important; font-weight:bold; vertical-align: middle; }
    #dataTable tbody tr:nth-child(even) { background-color: #f8f9fc; }
    #dataTable tbody tr:hover { background-color: #eaecf4; }
    
    .val-revenue { color: #4e73df; font-weight: 600; }
    .val-profit { color: #1cc88a; font-weight: 800; }
    .val-cost { color: #858796; }
    
    .grand-total-row td { background-color: #eaecf4 !important; font-weight: bold; font-size: 1.1rem; }
</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"><i class="fas fa-chart-pie me-2"></i>Báo cáo Lợi nhuận</h1>
    </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:#4e73df;">DOANH THU BÁN HÀNG</div><div class="value text-gray-800"><?php echo number_format($total_revenue_card); ?> ₫</div></div><div class="icon-circle" style="background-color:#4e73df;"><i class="fas fa-coins"></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:#f6c23e;">TIỀN VỐN (GIÁ GỐC)</div><div class="value text-gray-800"><?php echo number_format($total_cost_card); ?> ₫</div></div><div class="icon-circle" style="background-color:#f6c23e;"><i class="fas fa-cubes"></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:#1cc88a;">LỢI NHUẬN GỘP</div><div class="value" style="color:#1cc88a;"><?php echo number_format($gross_profit_card); ?> ₫</div></div><div class="icon-circle" style="background-color:#1cc88a;"><i class="fas fa-chart-line"></i></div></div></div></div>
    </div>

    <div class="filter-bar">
        <form method="GET" id="filterForm">
            <div class="mb-3">
                <label class="fw-bold text-secondary small text-uppercase mb-2">Xem theo nhóm:</label><br>
                <div class="btn-group" role="group">
                    <?php if ($logged_in_group_id == 1): ?>
                    <input type="radio" class="btn-check" name="group_by" id="g_emp" value="employee" <?php echo $group_by=='employee'?'checked':''; ?> onchange="this.form.submit()">
                    <label class="btn btn-outline-primary" for="g_emp">Nhân viên</label>
                    <?php endif; ?>
                    
                    <input type="radio" class="btn-check" name="group_by" id="g_cus" value="customer" <?php echo $group_by=='customer'?'checked':''; ?> onchange="this.form.submit()">
                    <label class="btn btn-outline-primary" for="g_cus">Khách hàng</label>
                    
                    <input type="radio" class="btn-check" name="group_by" id="g_ord" value="order" <?php echo $group_by=='order'?'checked':''; ?> onchange="this.form.submit()">
                    <label class="btn btn-outline-primary" for="g_ord">Chi tiết Đơn hàng</label>
                </div>
            </div>
            
            <div class="row g-2 align-items-end">
                <div class="col-md-2">
                    <label class="fw-bold small text-secondary">Khách hàng</label>
                    <select class="form-select select2" name="customer_id">
                        <option value="">Tất cả</option>
                        <?php foreach($customers as $c) echo "<option value='{$c['ID']}' ".($customer_id==$c['ID']?'selected':'').">{$c['customer_name']}</option>"; ?>
                    </select>
                </div>
                <?php if ($logged_in_group_id == 1): ?>
                <div class="col-md-2">
                    <label class="fw-bold small text-secondary">Nhân viên</label>
                    <select class="form-select select2" name="user_id">
                        <option value="">Tất cả</option>
                        <?php foreach($users as $u) echo "<option value='{$u['id']}' ".($user_id_filter==$u['id']?'selected':'').">{$u['display_name']}</option>"; ?>
                    </select>
                </div>
                <?php endif; ?>
                <div class="col-md-2">
                    <label class="fw-bold small text-secondary">Cửa hàng</label>
                    <select class="form-select select2" name="store_id">
                        <option value="">Tất cả</option>
                        <?php foreach($stores as $s) echo "<option value='{$s['id']}' ".($store_id==$s['id']?'selected':'').">{$s['store_name']}</option>"; ?>
                    </select>
                </div>
                <div class="col-md-4">
                    <label class="fw-bold small text-secondary">Thời gian:</label>
                    <div class="input-group">
                        <input type="text" class="form-control flatpickr" name="from" id="dateFrom" value="<?php echo $from_date; ?>">
                        <span class="input-group-text">➜</span>
                        <input type="text" class="form-control flatpickr" name="to" id="dateTo" value="<?php echo $to_date; ?>">
                    </div>
                    <div class="mt-1">
                        <button type="button" class="btn btn-outline-secondary btn-quick-date" onclick="setRange('today')">Hôm nay</button>
                        <button type="button" class="btn btn-outline-secondary btn-quick-date" onclick="setRange('week')">Tuần này</button>
                        <button type="button" class="btn btn-outline-secondary btn-quick-date" onclick="setRange('month')">Tháng này</button>
                    </div>
                </div>
                <div class="col-md-2">
                    <button type="submit" class="btn btn-primary w-100" style="height: 38px;"><i class="fas fa-filter me-2"></i> Lọc dữ liệu</button>
                </div>
            </div>
        </form>
    </div>

    <div class="card shadow mb-4">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0" id="dataTable">
                    <thead>
                        <tr>
                            <?php foreach($table_headers as $h): 
                                $align = ($h=='Lợi nhuận'||$h=='Doanh thu'||$h=='Tiền vốn') ? 'text-end' : 'text-left';
                            ?>
                            <th class="<?= $align ?>"><?= $h ?></th>
                            <?php endforeach; ?>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if(empty($report_data)): ?>
                            <tr><td colspan="6" class="text-center py-5 text-muted">Không có dữ liệu.</td></tr>
                        <?php else: ?>
                            <?php foreach($report_data as $row): ?>
                            <tr>
                                <td class="text-primary fw-bold">
                                    <?php 
                                    if ($group_by == 'order') echo $row['name'] . ' <span class="small text-muted fw-normal">('.date('d/m H:i', strtotime($row['date'])).')</span>';
                                    else echo htmlspecialchars($row['name']); 
                                    ?>
                                </td>
                                
                                <?php if ($group_by == 'order'): ?>
                                    <td><?= htmlspecialchars($row['customer']) ?></td>
                                <?php else: ?>
                                    <td class="text-left"><?= number_format($row['count']) ?></td>
                                <?php endif; ?>

                                <td class="text-end val-revenue"><?= number_format($row['revenue']) ?></td>
                                <td class="text-end val-cost"><?= number_format($row['cost']) ?></td>
                                <td class="text-end val-profit"><?= number_format($row['profit']) ?></td>
                            </tr>
                            <?php endforeach; ?>
                            <tr class="grand-total-row">
                                <td>TỔNG CỘNG</td>
                                <?php if ($group_by == 'order'): ?>
                                    <td></td>
                                <?php else: ?>
                                    <td></td>
                                <?php endif; ?>
                                <td class="text-end text-primary"><?= number_format($total_revenue_card) ?></td>
                                <td class="text-end text-secondary"><?= number_format($total_cost_card) ?></td>
                                <td class="text-end text-success"><?= number_format($gross_profit_card) ?></td>
                            </tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </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 src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
<script>
$(document).ready(function() {
    $('.select2').select2({ theme: "bootstrap-5", width: '100%' });
    flatpickr(".flatpickr", { locale: "vn", dateFormat: "Y-m-d", allowInput: true });
});

function setRange(type) {
    const today = new Date();
    const formatDate = (d) => d.toISOString().split('T')[0];
    let from = '', to = '';

    if (type === 'today') {
        from = to = formatDate(today);
    } else if (type === 'week') {
        const day = today.getDay() || 7;
        if (day !== 1) today.setHours(-24 * (day - 1));
        from = formatDate(today);
        today.setHours(24 * 6);
        to = formatDate(today);
    } else if (type === 'month') {
        from = new Date(today.getFullYear(), today.getMonth(), 1).toISOString().split('T')[0];
        to = new Date(today.getFullYear(), today.getMonth() + 1, 0).toISOString().split('T')[0];
    }
    
    document.getElementById('dateFrom').value = from;
    document.getElementById('dateTo').value = to;
    document.getElementById('filterForm').submit();
}
</script>