<?php
// File: /quanlybanhang/modules/mobile/orders_list.php
require_once __DIR__ . '/../../core/init.php';
require_once __DIR__ . '/../../templates/header.php';

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

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

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

// 1. Xây dựng bộ lọc
$sql_where_conditions = ["o.deleted = 0"]; 

// Lọc theo kho (nếu có)
if ($store_id > 0) {
    $sql_where_conditions[] = "o.store_id = $store_id";
}

$params = [];
$types  = "";

// Lọc theo ngày
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 = " WHERE " . implode(" AND ", $sql_where_conditions);

// 2. Truy vấn dữ liệu
$sql_list = "SELECT o.ID, o.output_code, o.sell_date, o.total_money, o.lack, o.detail_order, o.order_status, c.customer_name 
             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);
if (!empty($types)) {
    $stmt_orders->bind_param($types, ...$params);
}
$stmt_orders->execute();
$orders = $stmt_orders->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt_orders->close();
?>

<style>
    body { background-color: #f0f2f5; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; }
    .page-header { background: #fff; padding: 15px; margin-bottom: 10px; border-bottom: 1px solid #ddd; }
    .order-card { background: #fff; margin-bottom: 10px; padding: 12px; border-top: 1px solid #e3e6f0; border-bottom: 1px solid #e3e6f0; }
    .order-top { display: flex; justify-content: space-between; margin-bottom: 5px; }
    .code { font-weight: bold; color: #4e73df; }
    .date { font-size: 12px; color: #888; }
    .customer { font-size: 14px; color: #333; font-weight: 500; }
    .money-row { display: flex; justify-content: space-between; align-items: center; margin-top: 8px; }
    .total { font-size: 16px; font-weight: bold; color: #2c3e50; }
    
    /* Badge Styles */
    .badge-stt { font-size: 11px; padding: 4px 8px; border-radius: 12px; font-weight: 600; display: inline-flex; align-items: center; gap: 4px; }
    .stt-success { background: #1cc88a; color: #fff; } /* Hoàn thành - Xanh lá */
    .stt-draft { background: #f6c23e; color: #fff; }   /* Khởi tạo - Vàng cam */
    .stt-debt { background: #e74a3b; color: #fff; }    /* Nợ - Đỏ */
    
    .btn-float { position: fixed; bottom: 20px; right: 20px; width: 54px; height: 54px; background: #4e73df; color: white; border-radius: 50%; display: flex; align-items: center; justify-content: center; box-shadow: 0 4px 12px rgba(78,115,223,0.4); font-size: 20px; text-decoration: none; z-index: 100; }
</style>

<div class="container-fluid p-0">
    <div class="page-header">
        <h5 class="m-0">Danh sách đơn hàng</h5>
        <div class="text-muted small">Kho: <?php echo $store_id == 0 ? 'Tất cả' : 'Kho #'.$store_id; ?></div>
        
        <form method="GET" class="mt-2 d-flex gap-2">
            <input type="date" name="from" class="form-control form-control-sm" value="<?php echo $from_date; ?>">
            <input type="date" name="to" class="form-control form-control-sm" value="<?php echo $to_date; ?>">
            <button class="btn btn-primary btn-sm"><i class="fas fa-filter"></i></button>
        </form>
    </div>

    <div class="order-list pb-5">
        <?php if (empty($orders)): ?>
            <div class="text-center p-5 text-muted">Chưa có đơn hàng nào.</div>
        <?php else: ?>
            <?php foreach ($orders as $order): 
                // Chuyển đổi status sang số nguyên để so sánh chính xác
                $status = intval($order['order_status']);
                $lack = floatval($order['lack']);

                // Mặc định
                $stt_class = 'stt-success';
                $stt_text = 'Hoàn thành';
                $icon = '<i class="fas fa-check-circle"></i>';

                // [LOGIC QUAN TRỌNG]
                // 1. Ưu tiên kiểm tra trạng thái "Khởi tạo" (Status = 0) trước tiên
                if ($status === 0) { 
                    $stt_class = 'stt-draft';
                    $stt_text = 'Khởi tạo';
                    $icon = '<i class="fas fa-clock"></i>';
                } 
                // 2. Nếu không phải Khởi tạo, mới kiểm tra xem có nợ không
                elseif ($lack > 0) {
                    $stt_class = 'stt-debt';
                    $stt_text = 'Còn nợ';
                    $icon = '<i class="fas fa-exclamation-circle"></i>';
                }
                // 3. Còn lại là Hoàn thành (mặc định)
            ?>
            <div class="order-card" onclick="location.href='/quanlybanhang/modules/pos/pos.php?order_id=<?php echo $order['ID']; ?>&action=edit'">
                <div class="order-top">
                    <span class="code"><?php echo $order['output_code']; ?></span>
                    <span class="date"><?php echo date('d/m H:i', strtotime($order['sell_date'])); ?></span>
                </div>
                <div class="customer"><?php echo $order['customer_name']; ?></div>
                <div class="money-row">
                    <span class="badge-stt <?php echo $stt_class; ?>"><?php echo $icon . ' ' . $stt_text; ?></span>
                    <span class="total"><?php echo number_format($order['total_money']); ?> đ</span>
                </div>
            </div>
            <?php endforeach; ?>
        <?php endif; ?>
    </div>

    <a href="/quanlybanhang/modules/pos/pos.php" class="btn-float"><i class="fas fa-plus"></i></a>
</div>
<?php require_once __DIR__ . '/../../templates/footer.php'; ?>