<?php
require_once __DIR__ . '/../../../core/init.php';

if (!isset($_SESSION['user_id'])) {
    echo '<div class="alert alert-danger">Không có quyền truy cập.</div>';
    exit();
}

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

$sql_base = "FROM cms_orders o LEFT JOIN cms_customers c ON o.customer_id = c.ID WHERE o.deleted = 0 AND o.user_init = ?";
$params = [$user_id];
$types = "i";

$sql_where_conditions = [];
if (!empty($from_date)) {
    $sql_where_conditions[] = "o.sell_date >= ?";
    $params[] = $from_date . " 00:00:00";
    $types .= "s";
}
if (!empty($to_date)) {
    $sql_where_conditions[] = "o.sell_date <= ?";
    $params[] = $to_date . " 23:59:59";
    $types .= "s";
}

$sql_where = "";
if (!empty($sql_where_conditions)) {
    $sql_where = " AND " . implode(" AND ", $sql_where_conditions);
}

$stmt_summary = $conn->prepare("SELECT COUNT(o.ID) as total_orders, SUM(o.total_money) as total_amount, SUM(o.lack) as total_debt " . $sql_base . $sql_where);
$stmt_summary->bind_param($types, ...$params);
$stmt_summary->execute();
$summary = $stmt_summary->get_result()->fetch_assoc();
$stmt_summary->close();

$stmt_orders = $conn->prepare("SELECT o.ID, o.output_code, o.sell_date, o.total_money, o.detail_order, c.customer_name " . $sql_base . $sql_where . " ORDER BY o.ID DESC");
$stmt_orders->bind_param($types, ...$params);
$stmt_orders->execute();
$orders = $stmt_orders->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_orders->close();

?>
<style>
.accordion-button::after {
    font-family: "Font Awesome 5 Free";
    font-weight: 900;
    content: "\f067";
    background-image: none;
    transform: rotate(0deg);
}
.accordion-button:not(.collapsed)::after {
    content: "\f068";
    transform: rotate(0deg);
}
</style>
<div class="page-container">
    <div class="page-header">
        <h4>Quản lý Hóa đơn</h4>
    </div>
    <div class="page-content">
        <div class="summary-cards">
            <div class="summary-card">
                <div class="value"><?php echo $summary['total_orders'] ?? 0; ?></div>
                <div class="label">Số đơn</div>
            </div>
            <div class="summary-card">
                <div class="value"><?php echo number_format($summary['total_amount'] ?? 0); ?></div>
                <div class="label">Tổng tiền</div>
            </div>
            <div class="summary-card">
                <div class="value text-danger"><?php echo number_format($summary['total_debt'] ?? 0); ?></div>
                <div class="label">Tổng nợ</div>
            </div>
        </div>

        <div class="accordion" id="filterAccordion">
            <div class="accordion-item filter-card">
                <h2 class="accordion-header" id="headingFilter">
                    <button class="accordion-button collapsed" type="button" data-bs-toggle="collapse" data-bs-target="#collapseFilter">
                        <i class="fas fa-filter me-2"></i> Bộ lọc và Tìm kiếm
                    </button>
                </h2>
                <div id="collapseFilter" class="accordion-collapse collapse" data-bs-parent="#filterAccordion">
                    <div class="accordion-body">
                        <form id="invoice-filter-form" method="GET" action="">
                            <input type="hidden" name="page" value="invoices">
                            <div class="row g-2 mb-2">
                                <div class="col">
                                    <label class="form-label small">Từ ngày</label>
                                    <input type="date" name="from" class="form-control form-control-sm" value="<?php echo htmlspecialchars($from_date); ?>">
                                </div>
                                <div class="col">
                                    <label class="form-label small">Đến ngày</label>
                                    <input type="date" name="to" class="form-control form-control-sm" value="<?php echo htmlspecialchars($to_date); ?>">
                                </div>
                            </div>
                            <button type="submit" class="btn btn-primary btn-sm w-100">Áp dụng</button>
                        </form>
                    </div>
                </div>
            </div>
        </div>

        <div class="accordion mt-3" id="ordersAccordion">
            <?php if (empty($orders)): ?>
                <div class="text-center p-5"><i class="fas fa-box-open fa-3x text-muted mb-3"></i><p>Không tìm thấy hóa đơn nào.</p></div>
            <?php else: ?>
                <?php foreach ($orders as $order): ?>
                    <div class="accordion-item order-card">
                        <h2 class="accordion-header" id="heading-<?php echo $order['ID']; ?>">
                            <button class="accordion-button collapsed p-2" type="button" data-bs-toggle="collapse" data-bs-target="#collapse-<?php echo $order['ID']; ?>">
                                <div class="w-100 d-flex justify-content-between align-items-center">
                                    <div>
                                        <div class="fw-bold text-primary"><?php echo htmlspecialchars($order['output_code']); ?></div>
                                        <div class="small">KH: <?php echo htmlspecialchars($order['customer_name'] ?? 'Khách lẻ'); ?></div>
                                        <div class="small text-muted"><?php echo date("d/m/Y H:i", strtotime($order['sell_date'])); ?></div>
                                    </div>
                                    <div class="text-end">
                                        <div class="fw-bold fs-6"><?php echo number_format($order['total_money']); ?> đ</div>
                                        <span class="badge rounded-pill bg-success">Hoàn thành</span>
                                    </div>
                                </div>
                            </button>
                        </h2>
                        <div id="collapse-<?php echo $order['ID']; ?>" class="accordion-collapse collapse" data-bs-parent="#ordersAccordion">
                            <div class="accordion-body p-2">
                                <table class="table table-sm table-bordered small mb-0">
                                    <thead class="table-light">
                                        <tr>
                                            <th scope="col">#</th>
                                            <th scope="col">Tên sản phẩm</th>
                                            <th scope="col" class="text-center">SL</th>
                                            <th scope="col" class="text-end">ĐG</th>
                                            <th scope="col" class="text-end">TT</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                    <?php 
                                        $products = json_decode($order['detail_order'], true);
                                        $stt = 1;
                                        if (is_array($products)): 
                                            foreach ($products as $p): 
                                    ?>
                                        <tr>
                                            <th scope="row"><?php echo $stt++; ?></th>
                                            <td><?php echo htmlspecialchars($p['name']); ?></td>
                                            <td class="text-center"><?php echo $p['quantity']; ?></td>
                                            <td class="text-end"><?php echo number_format($p['price'] ?? 0); ?></td>
                                            <td class="text-end fw-bold"><?php echo number_format(($p['price'] ?? 0) * ($p['quantity'] ?? 0)); ?></td>
                                        </tr>
                                    <?php 
                                            endforeach; 
                                        endif; 
                                    ?>
                                    </tbody>
                                </table>
                            </div>
                        </div>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>
        </div>
    </div>
</div>