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

// Lấy danh sách nhân viên để hiển thị trong dropdown
$users = $conn->query("SELECT id, username FROM cms_users WHERE user_status = 1 ORDER BY username ASC")->fetch_all(MYSQLI_ASSOC);

$selected_user_id = $_GET['user_id'] ?? 0;
$from_date = $_GET['from_date'] ?? '';
$to_date = $_GET['to_date'] ?? '';
$selected_user_name = '';

$consolidated_items = [];

// Nếu người dùng đã chọn nhân viên và nhấn nút
if ($selected_user_id > 0) {
    // Tìm tên của user đã chọn
    foreach ($users as $user) {
        if ($user['id'] == $selected_user_id) {
            $selected_user_name = $user['username'];
            break;
        }
    }

    // Xây dựng câu lệnh SQL linh hoạt
    $sql_orders = "SELECT detail_order FROM cms_orders WHERE user_init = ? AND deleted = 0 AND order_status != 0";
    $params = [$selected_user_id];
    $types = 'i';

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

    $stmt_orders = $conn->prepare($sql_orders);
    $stmt_orders->bind_param($types, ...$params);
    $stmt_orders->execute();
    $result_orders = $stmt_orders->get_result();
    
    $temp_items = [];
    while ($order = $result_orders->fetch_assoc()) {
        $items = json_decode($order['detail_order'], true);
        if (is_array($items)) {
            foreach ($items as $item) {
                if (isset($item['id']) && isset($item['quantity'])) {
                    $product_id = intval($item['id']);
                    $quantity = intval($item['quantity']);
                    if (isset($temp_items[$product_id])) {
                        $temp_items[$product_id] += $quantity;
                    } else {
                        $temp_items[$product_id] = $quantity;
                    }
                }
            }
        }
    }
    $stmt_orders->close();

    if (!empty($temp_items)) {
        $product_ids = array_keys($temp_items);
        $sql_products = "SELECT id, prd_code, prd_name FROM cms_products WHERE id IN (". implode(',', array_fill(0, count($product_ids), '?')) .")";
        $stmt_products = $conn->prepare($sql_products);
        $stmt_products->bind_param(str_repeat('i', count($product_ids)), ...$product_ids);
        $stmt_products->execute();
        $products_result = $stmt_products->get_result();
        
        while ($product = $products_result->fetch_assoc()) {
            $product_id = $product['id'];
            $consolidated_items[] = [
                'id' => $product_id,
                'code' => $product['prd_code'],
                'name' => $product['prd_name'],
                'quantity' => $temp_items[$product_id]
            ];
        }
        $stmt_products->close();
    }
}
?>

<style>
    @media print {
        body * { visibility: hidden; }
        #print-area, #print-area * { visibility: visible; }
        #print-area { position: absolute; left: 0; top: 0; width: 100%; }
        .card-header, .card-body { border: none !important; box-shadow: none !important; }
    }
</style>

<div class="container-fluid">
    <div id="filter-section">
        <h1 class="h3 mb-2 text-gray-800">Tạo phiếu soạn hàng</h1>
        <div class="card shadow mb-4">
            <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Tùy chọn</h6></div>
            <div class="card-body">
                <form method="GET">
                    <div class="row align-items-end">
                        <div class="col-md-3">
                            <label for="user_id">Chọn nhân viên:</label>
                            <select name="user_id" id="user_id" class="form-control" required>
                                <option value="">-- Vui lòng chọn --</option>
                                <?php foreach ($users as $user): ?>
                                    <option value="<?php echo $user['id']; ?>" <?php echo ($selected_user_id == $user['id']) ? 'selected' : ''; ?>>
                                        <?php echo htmlspecialchars($user['username']); ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                        </div>
                        <div class="col-md-3">
                            <label for="from_date">Từ ngày:</label>
                            <input type="date" class="form-control" name="from_date" id="from_date" value="<?php echo htmlspecialchars($from_date); ?>">
                        </div>
                         <div class="col-md-3">
                            <label for="to_date">Đến ngày:</label>
                            <input type="date" class="form-control" name="to_date" id="to_date" value="<?php echo htmlspecialchars($to_date); ?>">
                        </div>
                        <div class="col-md-3">
                            <button type="submit" class="btn btn-primary">Tạo phiếu</button>
                            <?php if (!empty($consolidated_items)): ?>
                                <button type="button" class="btn btn-success" onclick="window.print();">
                                    <i class="fas fa-print"></i> In phiếu
                                </button>
                            <?php endif; ?>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <?php if ($selected_user_id > 0): ?>
        <?php if (!empty($consolidated_items)): ?>
        <div id="print-area">
            <div class="card shadow mb-4">
                <div class="card-header py-3 text-center">
                     <h4 class="m-0 font-weight-bold text-primary">PHIẾU SOẠN HÀNG</h4>
                     <p class="mb-0">
                        Thời gian: 
                        <strong>
                            <?php 
                                if($from_date && $to_date) echo date('d/m/Y', strtotime($from_date)) . ' - ' . date('d/m/Y', strtotime($to_date)); 
                                elseif($from_date) echo 'Từ ngày ' . date('d/m/Y', strtotime($from_date));
                                elseif($to_date) echo 'Đến ngày ' . date('d/m/Y', strtotime($to_date));
                                else echo 'Toàn thời gian';
                            ?>
                        </strong>
                     </p>
                     <p>Nhân viên: <strong><?php echo htmlspecialchars($selected_user_name); ?></strong></p>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-bordered" width="100%" cellspacing="0">
                            <thead><tr><th style="width: 5%;">STT</th><th style="width: 20%;">Mã sản phẩm</th><th>Tên sản phẩm</th><th style="width: 15%;">Số lượng</th></tr></thead>
                            <tbody>
                                <?php $stt = 1; foreach ($consolidated_items as $item): ?>
                                    <tr><td class="text-center"><?php echo $stt++; ?></td><td><?php echo htmlspecialchars($item['code']); ?></td><td><?php echo htmlspecialchars($item['name']); ?></td><td class="text-center font-weight-bold"><?php echo $item['quantity']; ?></td></tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        <?php else: ?>
            <div class="alert alert-info">Không tìm thấy đơn hàng nào cho nhân viên và khoảng thời gian đã chọn.</div>
        <?php endif; ?>
    <?php endif; ?>
</div>

<?php
require_once __DIR__ . '/../../templates/footer.php';
?>