<?php
ini_set('display_errors', 0);
error_reporting(E_ALL);

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

$user_id = $_SESSION['user_id'];
$store_id = $_SESSION['store_id'] ?? 0;

// 1. Xử lý bộ lọc ngày
$from_date = $_GET['from'] ?? date('Y-m-01');
$to_date   = $_GET['to'] ?? date('Y-m-d');

$sql_where_conditions = ["o.deleted = 0"]; 
if ($store_id > 0) {
    $sql_where_conditions[] = "o.store_id = $store_id";
}

$sql_where_conditions[] = "o.sell_date >= '$from_date 00:00:00'";
$sql_where_conditions[] = "o.sell_date <= '$to_date 23:59:59'";

$sql_where = " WHERE " . implode(" AND ", $sql_where_conditions);

// 2. Tổng quan
$sql_summary = "SELECT 
                    COUNT(CASE WHEN order_status = 1 THEN 1 END) as total_count, 
                    SUM(CASE WHEN order_status = 1 THEN total_money ELSE 0 END) as total_rev, 
                    SUM(CASE WHEN order_status = 1 THEN lack ELSE 0 END) as total_debt 
                FROM cms_orders o " . $sql_where;
$summary = $conn->query($sql_summary)->fetch_assoc();

// 3. Danh sách
$sql_list = "SELECT o.*, c.customer_name, c.customer_phone, c.customer_addr, c.customer_group 
             FROM cms_orders o 
             LEFT JOIN cms_customers c ON o.customer_id = c.ID " 
             . $sql_where . 
             " ORDER BY o.ID DESC LIMIT 50";

$stmt_orders = $conn->prepare($sql_list);
$stmt_orders->execute();
$orders = $stmt_orders->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_orders->close();
?>

<style>
    .stat-card { background: #fff; border-radius: 12px; padding: 12px; text-align: center; border: 1px solid #f0f0f0; box-shadow: 0 2px 6px rgba(0,0,0,0.03); height: 100%; }
    .stat-label { font-size: 0.7rem; color: #6c757d; text-transform: uppercase; font-weight: 800; margin-bottom: 5px; }
    .stat-value { font-size: 1.1rem; font-weight: 800; word-break: break-word; line-height: 1.2; }
    .text-rev { color: #0d6efd; } .text-debt { color: #dc3545; } .text-count { color: #198754; }

    .quick-filter-container { overflow-x: auto; white-space: nowrap; padding-bottom: 5px; -webkit-overflow-scrolling: touch; scrollbar-width: none; }
    .quick-filter-container::-webkit-scrollbar { display: none; }
    .quick-filter-btn { display: inline-block; font-size: 0.85rem; padding: 6px 14px; border-radius: 20px; border: 1px solid #dee2e6; background: #fff; color: #666; margin-right: 8px; text-decoration: none; font-weight: 500; transition: all 0.2s; }
    .quick-filter-btn.active { background: #0d6efd; color: #fff; border-color: #0d6efd; box-shadow: 0 2px 6px rgba(13, 110, 253, 0.3); }

    .order-card { background: #fff; border-radius: 10px; margin-bottom: 12px; border: 1px solid #eee; box-shadow: 0 2px 5px rgba(0,0,0,0.02); overflow: hidden; }
    .order-header { padding: 12px; cursor: pointer; position: relative; }
    .order-header:active { background-color: #f9f9f9; }
    
    .code-text { font-weight: 900; color: #0d6efd; font-size: 1rem; }
    .date-text { font-size: 0.75rem; color: #999; }
    .customer-text { font-weight: 700; color: #333; font-size: 0.95rem; margin-bottom: 4px; }
    
    .badge-stt { font-size: 0.7rem; padding: 4px 10px; border-radius: 4px; font-weight: 900; text-transform: uppercase; letter-spacing: 0.5px; }
    .stt-draft { background: #fff3cd; color: #856404; border: 1px solid #ffeeba; }
    .stt-success { background: #d1e7dd; color: #0f5132; border: 1px solid #badbcc; }
    .stt-debt { background: #f8d7da; color: #842029; border: 1px solid #f5c2c7; }

    .toggle-icon { transition: transform 0.3s ease; color: #aaa; }
    .order-card.expanded .toggle-icon { transform: rotate(180deg); color: #0d6efd; }

    .order-details { display: none; border-top: 1px solid #f0f0f0; background-color: #fff; padding: 15px; }
    .customer-detail-box { background: #f8f9fa; border-radius: 8px; padding: 10px; margin-bottom: 15px; border: 1px solid #eee; }
    .cust-row { display: flex; align-items: center; font-size: 0.9rem; color: #555; margin-bottom: 4px; }
    .cust-row i { width: 20px; text-align: center; margin-right: 8px; color: #0d6efd; }

    .stylish-table { width: 100%; font-size: 0.9rem; border-collapse: collapse; }
    .stylish-table thead th { background-color: #0d6efd; color: #fff; font-weight: 700; padding: 8px; text-transform: uppercase; font-size: 0.75rem; text-align: center; }
    .stylish-table thead th:first-child { border-top-left-radius: 6px; text-align: left; }
    .stylish-table thead th:last-child { border-top-right-radius: 6px; text-align: right; }
    .stylish-table tbody td { padding: 10px 8px; border-bottom: 1px solid #f0f0f0; vertical-align: middle; }
    
    .prod-name-detail { font-weight: 700; color: #333; font-size: 0.95rem; margin-bottom: 2px; display: block; }
    .prod-meta-detail { font-size: 0.8rem; color: #888; }
    .prod-price-detail { font-weight: 600; color: #666; font-size: 0.9rem; }
    .prod-total-detail { font-weight: 800; color: #fd7e14; font-size: 1rem; }
    .prod-discount-tag { font-size: 0.7rem; background: #dc3545; color: white; padding: 1px 5px; border-radius: 4px; font-weight: bold; margin-left: 5px; vertical-align: middle; }

    .summary-row { display: flex; justify-content: space-between; font-size: 0.9rem; margin-bottom: 6px; color: #555; }
    .summary-row.total-row { border-top: 1px dashed #ddd; padding-top: 10px; margin-top: 10px; font-size: 1.1rem; color: #333; }
    
    .action-btn-group { display: flex; gap: 10px; margin-top: 15px; }
    .btn-action { flex: 1; font-size: 0.95rem; padding: 10px; border-radius: 8px; font-weight: 700; display: flex; align-items: center; justify-content: center; gap: 6px; box-shadow: 0 2px 5px rgba(0,0,0,0.1); border: none; }
    .btn-edit { background-color: #0d6efd; color: white; }
    .btn-delete { background-color: #dc3545; color: white; }
    .btn-float-invoices { position: fixed; bottom: 80px; right: 20px; width: 50px; height: 50px; background: #fff; color: #0d6efd; border: 1px solid #0d6efd; border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 12px rgba(0,0,0,0.1); font-size: 20px; text-decoration: none; z-index: 99; }
</style>

<div class="container-fluid p-0 pb-5">
    <div class="bg-white p-3 shadow-sm mb-3">
        <h5 class="fw-bold text-primary mb-3">Quản lý Hóa đơn</h5>
        <div class="row g-2 mb-3">
            <div class="col-4"><div class="stat-card"><div class="stat-label">Số đơn</div><div class="stat-value text-count"><?php echo number_format($summary['total_count'] ?? 0); ?></div></div></div>
            <div class="col-4"><div class="stat-card"><div class="stat-label">Doanh số</div><div class="stat-value text-rev"><?php echo number_format($summary['total_rev'] ?? 0); ?></div></div></div>
            <div class="col-4"><div class="stat-card"><div class="stat-label">Công nợ</div><div class="stat-value text-debt"><?php echo number_format($summary['total_debt'] ?? 0); ?></div></div></div>
        </div>
        <div class="row g-2 align-items-center mb-2">
            <div class="col-5"><input type="date" id="inv_from" class="form-control form-control-sm" value="<?php echo $from_date; ?>"></div>
            <div class="col-5"><input type="date" id="inv_to" class="form-control form-control-sm" value="<?php echo $to_date; ?>"></div>
            <div class="col-2"><button class="btn btn-primary btn-sm w-100" id="btn-filter-invoices"><i class="fas fa-search"></i></button></div>
        </div>
        <div class="quick-filter-container">
            <?php 
                $ranges = ['today' => 'Hôm nay', 'week' => 'Tuần này', 'month' => 'Tháng này', 'quarter' => 'Quý này', 'year' => 'Năm nay'];
                $current_range = $_GET['range'] ?? 'month';
            ?>
            <?php foreach($ranges as $key => $label): ?>
                <a href="#" class="quick-filter-btn <?php echo $current_range == $key ? 'active' : ''; ?>" data-range="<?php echo $key; ?>"><?php echo $label; ?></a>
            <?php endforeach; ?>
        </div>
    </div>

    <div class="order-list px-2">
        <?php if (empty($orders)): ?>
            <div class="text-center p-5 text-muted"><i class="fas fa-box-open fa-3x mb-3 text-light"></i><p>Không tìm thấy hóa đơn nào.</p></div>
        <?php else: ?>
            <?php foreach ($orders as $order): 
                $status = intval($order['order_status']);
                $lack = floatval($order['lack']);
                $items = json_decode($order['detail_order'], true);
                
                // CÁC BIẾN HIỂN THỊ SƠ LƯỢC BÊN NGOÀI
                $has_prod_discount = false;
                $max_prod_percent = 0;
                $total_prod_discount_amount = 0; // Biến mới: Tổng tiền giảm giá SP

                if(is_array($items)) {
                    foreach($items as $itm) {
                        $p_price = floatval($itm['price']);
                        $p_qty = floatval($itm['quantity']);
                        $per = floatval($itm['percent'] ?? 0);

                        if ($per > 0) {
                            $has_prod_discount = true;
                            if ($per > $max_prod_percent) $max_prod_percent = $per;
                            // Tính tiền giảm cho dòng này và cộng dồn
                            $total_prod_discount_amount += ($p_price * $p_qty) * ($per / 100);
                        }
                    }
                }

                // Lấy thông tin giảm giá đơn
                $order_disc_per = floatval($order['discount_percent']);
                $final_money = floatval($order['total_money']);

                if ($status === 0) { 
                    $stt_class = 'stt-draft'; $stt_text = 'Khởi tạo';
                } elseif ($lack > 0) {
                    $stt_class = 'stt-debt'; $stt_text = 'Còn nợ';
                } else {
                    $stt_class = 'stt-success'; $stt_text = 'Hoàn thành';
                }
                
                $orderJson = htmlspecialchars(json_encode($order), ENT_QUOTES, 'UTF-8');
            ?>
            
            <div class="order-card" id="card-<?php echo $order['ID']; ?>">
                <div class="order-header" onclick="toggleOrderDetail(<?php echo $order['ID']; ?>, <?php echo $orderJson; ?>)">
                    <div class="d-flex justify-content-between align-items-start">
                        <div>
                            <div class="code-text"><?php echo $order['output_code']; ?></div>
                            <div class="date-text"><?php echo date('d/m/Y H:i', strtotime($order['sell_date'])); ?></div>
                        </div>
                        <div class="text-end">
                            <div class="fw-bold text-dark"><?php echo number_format($final_money); ?> đ</div>
                            
                            <?php if($order_disc_per > 0): ?>
                                <div class="text-danger fw-bold" style="font-size: 0.7rem;">(Đơn <?php echo $order_disc_per; ?>%)</div>
                            <?php endif; ?>

                            <?php if($has_prod_discount): ?>
                                <div class="text-danger fw-bold" style="font-size: 0.7rem;">
                                    (SP <?php echo $max_prod_percent; ?>%)
                                </div>
                            <?php endif; ?>
                            
                            <span class="badge-stt <?php echo $stt_class; ?>"><?php echo $stt_text; ?></span>
                        </div>
                    </div>
                    <div class="d-flex justify-content-between align-items-center mt-2">
                        <div class="customer-text"><i class="fas fa-user text-muted me-1"></i><?php echo $order['customer_name']; ?></div>
                        <i class="fas fa-chevron-down toggle-icon"></i>
                    </div>
                </div>

                <div class="order-details" id="detail-<?php echo $order['ID']; ?>">
                    </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>
    
    <a href="#" class="btn-float-invoices" onclick="$('html, body').animate({scrollTop:0}, 'fast'); return false;"><i class="fas fa-arrow-up"></i></a>
</div>

<script>
function formatNumber(num) {
    return new Intl.NumberFormat('vi-VN').format(num);
}

function toggleOrderDetail(id, orderData) {
    const detail = $('#detail-' + id); 
    const card = $('#card-' + id);

    if (detail.is(':visible')) { 
        detail.slideUp(200); 
        card.removeClass('expanded'); 
    } else { 
        $('.order-details').slideUp(200); 
        $('.order-card').removeClass('expanded'); 
        renderDetailContent(id, orderData);
        detail.slideDown(200); 
        card.addClass('expanded'); 
    }
}

function renderDetailContent(id, order) {
    const detailBox = $('#detail-' + id);
    let items = [];
    try { items = JSON.parse(order.detail_order); } catch(e) {}
    
    let html = `
    <div class="customer-detail-box">
        <div class="cust-row"><i class="fas fa-user"></i> <strong>${order.customer_name}</strong></div>
        <div class="cust-row"><i class="fas fa-phone-alt"></i> ${order.customer_phone || '---'}</div>
        <div class="cust-row"><i class="fas fa-map-marker-alt"></i> ${order.customer_addr || '---'}</div>
    </div>
    <table class="stylish-table mb-3">
        <thead><tr><th>Sản phẩm</th><th class="text-center">SL/Giá</th><th class="text-end">Thành tiền</th></tr></thead>
        <tbody>`;

    let totalGross = 0;
    let totalDiscountSP = 0;

    items.forEach(item => {
        let price = parseFloat(item.price);
        let qty = parseFloat(item.quantity);
        let percent = parseFloat(item.percent || 0);
        
        let lineGross = price * qty;
        let lineDisc = lineGross * (percent / 100);
        let lineTotal = lineGross - lineDisc;
        
        totalGross += lineGross;
        totalDiscountSP += lineDisc;

        html += `<tr>
            <td>
                <span class="prod-name-detail">${item.name}</span>
                <span class="prod-meta-detail">Mã: ${item.code}</span>
                ${percent > 0 ? `<span class="prod-discount-tag">${percent}%</span>` : ''}
            </td>
            <td class="text-center">
                <div class="fw-bold text-dark">x${qty}</div>
                <div class="prod-price-detail">${formatNumber(price)}</div>
            </td>
            <td class="text-end">
                <div class="prod-total-detail">${formatNumber(lineTotal)}</div>
            </td>
        </tr>`;
    });

    html += `</tbody></table>`;

    let subTotalAfterSP = totalGross - totalDiscountSP;
    let orderDiscPercent = parseFloat(order.discount_percent || 0);
    let orderDiscAmount = 0;

    if (orderDiscPercent > 0) {
        orderDiscAmount = subTotalAfterSP * (orderDiscPercent / 100);
    } else {
        orderDiscAmount = parseFloat(order.discount_item || 0);
    }

    let finalTotal = subTotalAfterSP - orderDiscAmount;
    let vatPercent = parseFloat(order.vat || 0);
    let vatAmount = finalTotal * (vatPercent / 100);
    finalTotal += vatAmount;

    html += `
    <div class="summary-row">
        <span>Tổng tiền hàng:</span>
        <span class="fw-bold">${formatNumber(totalGross)}</span>
    </div>`;

    if (totalDiscountSP > 0) {
        html += `<div class="summary-row text-danger">
            <span>Giảm giá sản phẩm:</span>
            <span class="fw-bold">-${formatNumber(Math.round(totalDiscountSP))}</span>
        </div>`;
    }

    if (orderDiscAmount > 0) {
        let label = orderDiscPercent > 0 ? `Giảm giá đơn (${orderDiscPercent}%):` : `Giảm giá đơn:`;
        html += `<div class="summary-row text-danger">
            <span>${label}</span>
            <span class="fw-bold">-${formatNumber(Math.round(orderDiscAmount))}</span>
        </div>`;
    }
    
    if (vatPercent > 0) {
         html += `<div class="summary-row">
            <span>VAT (${vatPercent}%):</span>
            <span class="fw-bold">${formatNumber(Math.round(vatAmount))}</span>
        </div>`;
    }

    html += `<div class="summary-row total-row">
        <span class="fw-bold">TỔNG CỘNG:</span>
        <span class="fw-bold text-primary" style="font-size: 1.3rem;">${formatNumber(Math.round(finalTotal))}</span>
    </div>`;

    if (order.order_status == 1) {
        html += `
        <div class="summary-row mt-2">
            <span>Khách đã trả:</span>
            <span class="fw-bold text-success">${formatNumber(order.customer_pay)}</span>
        </div>
        <div class="summary-row">
            <span>Còn nợ:</span>
            <span class="fw-bold text-danger">${formatNumber(order.lack)}</span>
        </div>`;
    }

    let orderString = JSON.stringify(order).replace(/"/g, '&quot;');
    html += `<div class="action-btn-group">
        <button class="btn-action btn-edit" onclick='window.editOrderFromList(${orderString})'><i class="fas fa-edit"></i> Sửa đơn</button>
        <button class="btn-action btn-delete" onclick="window.deleteOrder(${order.ID}, '${order.output_code}')"><i class="fas fa-trash-alt"></i> Xóa đơn</button>
    </div>`;

    detailBox.html(html);
}

$(document).ready(function() {
    function reloadInvoices(params) { $('#dynamic-content').load('/quanlybanhang/modules/pos/tabs/invoices_tab.php?' + params); }
    $('#btn-filter-invoices').click(function() { let from = $('#inv_from').val(); let to = $('#inv_to').val(); reloadInvoices(`from=${from}&to=${to}`); });
    $('.quick-filter-btn').click(function(e) {
        e.preventDefault(); let range = $(this).data('range'); let today = new Date(); let formatDate = (d) => d.toISOString().split('T')[0]; let from, to;
        switch(range) {
            case 'today': from = to = formatDate(today); break;
            case 'week': let day = today.getDay() || 7; if(day !== 1) today.setHours(-24 * (day - 1)); from = formatDate(today); to = formatDate(new Date()); break;
            case 'month': from = formatDate(new Date(today.getFullYear(), today.getMonth(), 1)); to = formatDate(new Date(today.getFullYear(), today.getMonth() + 1, 0)); break;
            case 'quarter': let q = Math.floor((today.getMonth() + 3) / 3); from = formatDate(new Date(today.getFullYear(), (q - 1) * 3, 1)); to = formatDate(new Date(today.getFullYear(), q * 3, 0)); break;
            case 'year': from = formatDate(new Date(today.getFullYear(), 0, 1)); to = formatDate(new Date(today.getFullYear(), 11, 31)); break;
        }
        reloadInvoices(`from=${from}&to=${to}&range=${range}`);
    });
});
</script>