<?php
ini_set('display_errors', 1);
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>
    /* CSS Thẻ Thống Kê */
    .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; }

    /* CSS Bộ Lọc Nhanh */
    .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); }

    /* CSS Card Đơn Hàng */
    .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 trạng thái */
    .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; }

    /* Phần chi tiết */
    .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; }

    /* Bảng sản phẩm */
    .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; }

    /* Dòng tổng kết */
    .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; }
    
    /* Nút hành động */
    .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']);
                
                // --- LOGIC TÍNH TOÁN CHI TIẾT ---
                $items = json_decode($order['detail_order'], true);
                $total_gross = 0; 
                $total_item_disc_amt = 0; 
                $max_item_percent = 0;
                
                if(is_array($items)) {
                    foreach($items as $itm) {
                        $p = floatval($itm['price']);
                        $q = floatval($itm['quantity']);
                        $per = floatval($itm['percent'] ?? 0);
                        if($per > $max_item_percent) $max_item_percent = $per;
                        
                        $line_gross = $p * $q;
                        $line_disc = $line_gross * ($per / 100);
                        
                        $total_gross += $line_gross;
                        $total_item_disc_amt += $line_disc;
                    }
                }

                $order_disc_amt = floatval($order['discount_item']);
                $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']; ?>)">
                    <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_amt > 0): ?>
                                <div class="text-danger fw-bold" style="font-size: 0.7rem;">(Đơn <?php echo $order_disc_per > 0 ? $order_disc_per.'%' : number_format($order_disc_amt); ?>)</div>
                            <?php endif; ?>
                            <?php if($total_item_disc_amt > 0): ?>
                                <div class="text-danger fw-bold" style="font-size: 0.7rem;">(Sản phẩm <?php echo $max_item_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 class="customer-detail-box">
                        <div class="cust-row"><i class="fas fa-user"></i> <strong><?php echo $order['customer_name']; ?></strong></div>
                        <div class="cust-row"><i class="fas fa-phone-alt"></i> <?php echo !empty($order['customer_phone']) ? $order['customer_phone'] : '---'; ?></div>
                        <div class="cust-row"><i class="fas fa-map-marker-alt"></i> <?php echo !empty($order['customer_addr']) ? $order['customer_addr'] : '---'; ?></div>
                    </div>

                    <table class="stylish-table mb-3">
                        <thead><tr><th>Sản phẩm</th><th>SL/Giá</th><th>Thành tiền</th></tr></thead>
                        <tbody>
                            <?php if(is_array($items)): foreach($items as $item):
                                    $item_percent = floatval($item['percent'] ?? 0);
                                    $item_price = floatval($item['price']); 
                                    $item_qty = floatval($item['quantity']);
                                    $item_total_line = ($item_price - ($item_price * $item_percent / 100)) * $item_qty;
                            ?>
                            <tr>
                                <td>
                                    <span class="prod-name-detail"><?php echo $item['name']; ?></span>
                                    <span class="prod-meta-detail">Mã: <?php echo $item['code']; ?></span>
                                </td>
                                <td class="text-center">
                                    <div class="fw-bold text-dark">x<?php echo $item_qty; ?></div>
                                    <div class="prod-price-detail"><?php echo number_format($item_price); ?></div>
                                </td>
                                <td class="text-end">
                                    <div class="prod-total-detail"><?php echo number_format($item_total_line); ?></div>
                                </td>
                            </tr>
                            <?php endforeach; endif; ?>
                        </tbody>
                    </table>
                    
                    <div class="summary-row">
                        <span>Tổng tiền hàng:</span>
                        <span class="fw-bold"><?php echo number_format($total_gross); ?></span>
                    </div>
                    
                    <?php if($total_item_disc_amt > 0): ?>
                    <div class="summary-row text-danger">
                        <span>Giảm giá sản phẩm:</span>
                        <span class="fw-bold"><?php echo number_format($total_item_disc_amt); ?></span>
                    </div>
                    <?php endif; ?>

                    <?php if($order_disc_amt > 0): ?>
                    <div class="summary-row text-danger">
                        <span>Giảm giá đơn:</span>
                        <span class="fw-bold"><?php echo number_format($order_disc_amt); ?></span>
                    </div>
                    <?php endif; ?>

                    <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;"><?php echo number_format($final_money); ?></span>
                    </div>
                    
                    <?php if($status == 1): ?>
                    <div class="summary-row mt-2">
                        <span>Khách đã trả:</span>
                        <span class="fw-bold text-success"><?php echo number_format($order['customer_pay']); ?></span>
                    </div>
                    <div class="summary-row">
                        <span>Còn nợ:</span>
                        <span class="fw-bold text-danger"><?php echo number_format($order['lack']); ?></span>
                    </div>
                    <?php endif; ?>

                    <div class="action-btn-group">
                        <button class="btn-action btn-edit" onclick='window.editOrderFromList(<?php echo $orderJson; ?>)'><i class="fas fa-edit"></i> Sửa đơn</button>
                        <button class="btn-action btn-delete" onclick="window.deleteOrder(<?php echo $order['ID']; ?>, '<?php echo $order['output_code']; ?>')"><i class="fas fa-trash-alt"></i> Xóa đơn</button>
                    </div>
                </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 toggleOrderDetail(id) {
    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'); detail.slideDown(200); card.addClass('expanded'); }
}
$(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>