<?php

namespace WMS\Repositories;

class PackingRepository extends BaseRepository
{
    protected string $table = 'packing_orders';

    public function getWithLines(int $packingId): ?array
    {
        $doc = $this->findById($packingId);
        if (!$doc) {
            return null;
        }

        $stmt = $this->db->prepare(
            "SELECT pol.*, pol.quantity AS expected_qty, i.item_code, i.item_name,
                    bt.batch_number, bt.expiry_date
             FROM packing_lines pol
             JOIN items i ON pol.item_id = i.id
             LEFT JOIN batches bt ON pol.batch_id = bt.id
             WHERE pol.packing_order_id = ?
             ORDER BY pol.line_num"
        );
        $stmt->execute([$packingId]);
        $doc['lines'] = $stmt->fetchAll();

        return $doc;
    }

    public function getPendingByWarehouse(int $warehouseId): array
    {
        $stmt = $this->db->prepare(
            "SELECT * FROM packing_orders
             WHERE warehouse_id = ? AND status IN ('OPEN','IN_PROGRESS')
             ORDER BY created_at ASC"
        );
        $stmt->execute([$warehouseId]);
        return $stmt->fetchAll();
    }
}
