<?php

namespace WMS\Repositories;

class DispatchRepository extends BaseRepository
{
    protected string $table = 'dispatches';

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

        $stmt = $this->db->prepare(
            "SELECT dl.*, po.pack_number, po.status AS packing_status
             FROM dispatch_lines dl
             LEFT JOIN packing_orders po ON dl.packing_order_id = po.id
             WHERE dl.dispatch_id = ?
             ORDER BY dl.line_num"
        );
        $stmt->execute([$dispatchId]);
        $doc['lines'] = $stmt->fetchAll();

        return $doc;
    }

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