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

// --- LẤY DỮ LIỆU BỘ LỌC ---
$users = $conn->query("SELECT id, username FROM cms_users WHERE user_status = 1 ORDER BY username ASC")->fetch_all(MYSQLI_ASSOC);
$stores = $conn->query("SELECT id, store_name FROM cms_stores ORDER BY store_name ASC")->fetch_all(MYSQLI_ASSOC);

// --- XỬ LÝ THAM SỐ LỌC ---
$filter_from_date = $_GET['from_date'] ?? '';
$filter_to_date = $_GET['to_date'] ?? '';
$filter_user_id_get = $_GET['user_id'] ?? '';

// --- XÂY DỰNG CÂU TRUY VẤN ---
$sql = "SELECT 
            ps.ID, ps.output_code, ps.created, ps.date_order, ps.total_quantity, ps.total_money,
            ps.detail_order_id, ps.detail_product_id, u.username, s.store_name 
        FROM cms_output ps 
        JOIN cms_users u ON ps.user_init = u.id
        LEFT JOIN cms_stores s ON ps.store_id = s.id";

$where_clauses = [];
$params = [];
$types = '';

if ($filter_user_id_get !== '' && is_numeric($filter_user_id_get)) {
    $filter_user_id = intval($filter_user_id_get);
    $where_clauses[] = "ps.user_init = ?";
    $params[] = $filter_user_id;
    $types .= 'i';
} else {
    $filter_user_id = '';
}

if (!empty($filter_from_date)) {
    $where_clauses[] = "DATE(ps.created) >= ?";
    $params[] = $filter_from_date;
    $types .= 's';
}
if (!empty($filter_to_date)) {
    $where_clauses[] = "DATE(ps.created) <= ?";
    $params[] = $filter_to_date;
    $types .= 's';
}

if (!empty($where_clauses)) {
    $sql .= " WHERE " . implode(' AND ', $where_clauses);
}

$sql .= " ORDER BY ps.id DESC";

$stmt = $conn->prepare($sql);
if ($stmt === false) { die("Lỗi prepare SQL: " . $conn->error); }

// === THAY ĐỔI: Sử dụng phương pháp bind_param tương thích PHP cũ ===
if (!empty($types)) {
    $bind_names = [$types];
    foreach ($params as $key => &$param) {
        $bind_names[] = &$param;
    }
    call_user_func_array(array($stmt, 'bind_param'), $bind_names);
}

$stmt->execute();
$initial_picking_slips = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

// --- LOGIC LỌC CÁC PHIẾU KHÔNG HỢP LỆ ---
$valid_picking_slips = []; 
foreach ($initial_picking_slips as $slip) {
    $is_valid = true; 
    $orders_in_slip = json_decode($slip['detail_order_id'], true) ?: [];

    if (empty($orders_in_slip)) {
        $is_valid = false;
    } else {
        $order_ids = array_column($orders_in_slip, 'id');
        $order_ids = array_filter($order_ids, 'is_numeric');

        if (!empty($order_ids)) {
            $placeholders = implode(',', array_fill(0, count($order_ids), '?'));
            $sql_check = "SELECT COUNT(id) as live_count FROM cms_orders WHERE id IN ($placeholders) AND deleted = 0";
            $stmt_check = $conn->prepare($sql_check);
            
            if ($stmt_check) {
                // === THAY ĐỔI: Sử dụng phương pháp bind_param tương thích PHP cũ ===
                $check_types = str_repeat('i', count($order_ids));
                $check_params_ref = [];
                foreach($order_ids as $key => &$id) {
                    $check_params_ref[] = &$id;
                }
                call_user_func_array(array($stmt_check, 'bind_param'), array_merge(array($check_types), $check_params_ref));

                $stmt_check->execute();
                $live_count = (int) $stmt_check->get_result()->fetch_assoc()['live_count'];
                $stmt_check->close();
                if ($live_count < count($order_ids)) {
                    $is_valid = false;
                }
            } else {
                $is_valid = false;
            }
        }
    }
    
    if ($is_valid) {
        $valid_picking_slips[] = $slip;
    }
}
?>

<div class="container-fluid">
    <h1 class="h3 mb-2 text-gray-800">Danh sách phiếu soạn hàng</h1>

    <?php if(isset($_GET['success'])): ?>
        <div class="alert alert-success"><?php echo htmlspecialchars($_GET['success']); ?></div>
    <?php endif; ?>
    <?php if(isset($_GET['error'])): ?>
        <div class="alert alert-danger"><?php echo htmlspecialchars($_GET['error']); ?></div>
    <?php endif; ?>

    <div class="card shadow mb-4">
        <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Lọc và Tạo phiếu</h6></div>
        <div class="card-body">
            <form action="create_picking_slip.php" method="POST" class="mb-4 border-bottom pb-4">
                 <h6 class="mb-3">Tạo phiếu mới</h6>
                <div class="row align-items-end">
                    <div class="col-md-3"><label>Chọn nhân viên bán hàng:</label><select name="user_id" class="form-control" required><option value="">-- Chọn nhân viên --</option><?php foreach($users as $user): ?><option value="<?php echo $user['id']; ?>"><?php echo htmlspecialchars($user['username']); ?></option><?php endforeach; ?></select></div>
                    <div class="col-md-3"><label>Tại kho:</label><select name="store_id" class="form-control" required><option value="">-- Chọn kho --</option><?php foreach($stores as $store): ?><option value="<?php echo $store['id']; ?>"><?php echo htmlspecialchars($store['store_name']); ?></option><?php endforeach; ?></select></div>
                    <div class="col-md-3"><label>Chọn ngày của các đơn hàng:</label><input type="date" name="date" class="form-control" value="<?php echo date('Y-m-d'); ?>" required></div>
                    <div class="col-md-3"><button type="submit" class="btn btn-primary"><i class="fas fa-plus-circle"></i> Tạo phiếu soạn hàng</button></div>
                </div>
            </form>
            
            <form method="GET" class="mt-4">
                <h6 class="mb-3">Tìm kiếm phiếu đã tạo</h6>
                <div class="row align-items-end">
                    <div class="col-md-3"><label>Nhân viên:</label><select name="user_id" class="form-control"><option value="">-- Tất cả --</option><?php foreach($users as $user): ?><option value="<?php echo $user['id']; ?>" <?php echo ($filter_user_id_get !== '' && $filter_user_id_get == $user['id']) ? 'selected' : ''; ?>><?php echo htmlspecialchars($user['username']); ?></option><?php endforeach; ?></select></div>
                    <div class="col-md-3"><label>Từ ngày:</label><input type="date" name="from_date" class="form-control" value="<?php echo htmlspecialchars($filter_from_date); ?>"></div>
                    <div class="col-md-3"><label>Đến ngày:</label><input type="date" name="to_date" class="form-control" value="<?php echo htmlspecialchars($filter_to_date); ?>"></div>
                    <div class="col-md-3"><button type="submit" class="btn btn-info btn-block"><i class="fas fa-search"></i> Tìm kiếm</button></div>
                </div>
            </form>
        </div>
    </div>

    <div class="card shadow mb-4">
        <div class="card-header py-3"><h6 class="m-0 font-weight-bold text-primary">Kết quả</h6></div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                    <thead>
                        <tr>
                            <th class="text-center">STT</th>
                            <th>Mã phiếu</th>
                            <th>Kho xuất</th>
                            <th>Ngày tạo</th>
                            <th>Ngày bán</th>
                            <th>Nhân viên bán hàng</th>
                            <th class="text-right">Tổng SL</th>
                            <th class="text-right">Tổng tiền</th>
                            <th class="text-center">Hành động</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php if (empty($valid_picking_slips)): ?>
                            <tr><td colspan="9" class="text-center">Không tìm thấy phiếu soạn hàng nào phù hợp.</td></tr>
                        <?php else: ?>
                            <?php $stt = 1; foreach($valid_picking_slips as $slip): ?>
                            <tr>
                                <td class="text-center"><?php echo $stt++; ?></td>
                                <td><?php echo htmlspecialchars($slip['output_code'] ?? 'N/A'); ?></td>
                                <td><?php echo htmlspecialchars($slip['store_name'] ?? 'N/A'); ?></td>
                                <td><?php echo date('H:i d/m/Y', strtotime($slip['created'])); ?></td>
                                <td><?php echo (!empty($slip['date_order']) && $slip['date_order'] !== '0000-00-00') ? date('d/m/Y', strtotime($slip['date_order'])) : 'N/A'; ?></td>
                                <td><?php echo htmlspecialchars($slip['username']); ?></td>
                                <td class="text-right"><?php echo number_format($slip['total_quantity']); ?></td>
                                <td class="text-right"><?php echo number_format($slip['total_money']); ?></td>
                                <td class="text-center">
                                    <a href="print_picking_slip.php?id=<?php echo $slip['ID']; ?>" class="btn btn-info btn-sm" target="_blank" title="In phiếu"><i class="fas fa-print"></i></a>
                                    <a href="delete_picking_slip.php?id=<?php echo $slip['ID']; ?>" class="btn btn-danger btn-sm" title="Xóa phiếu" onclick="return confirm('Bạn có chắc chắn muốn xóa phiếu <?php echo htmlspecialchars($slip['output_code'] ?? 'này'); ?>?');"><i class="fas fa-trash"></i></a>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>
<?php require_once __DIR__ . '/../../templates/footer.php'; ?>
<script>
    $(document).ready(function() {
        $('#dataTable').DataTable({
            "order": [], 
            "columnDefs": [ { "orderable": false, "targets": 8 } ],
            "language": { "url": "/quanlybanhang/assets/libs/datatables/vietnamese.json" }
        });
    });
</script>