<?php

namespace App\Services\PurchaseOrders;

use Illuminate\Support\Facades\DB;

class PurchaseOrderQueryService
{
    public function list(?string $q = null): array
    {
        $builder = DB::table('purchase_orders')
            ->select('purchase_orders.*', 'suppliers.name as supplier_name')
            ->leftJoin('suppliers', 'suppliers.id', '=', 'purchase_orders.supplier_id');

        if ($q !== null && trim($q) !== '') {
            $query = trim($q);
            $builder->where(function ($qbuilder) use ($query) {
                $qbuilder->where('purchase_orders.po_number', 'like', "%{$query}%")
                    ->orWhere('suppliers.name', 'like', "%{$query}%");
            });
        }

        return $builder->orderByDesc('purchase_orders.created_at')
            ->get()
            ->map(fn ($row) => (array) $row)
            ->all();
    }

    public function options(): array
    {
        $suppliers = DB::table('suppliers')->orderBy('name')->get()->map(fn ($r) => (array) $r)->all();
        $supplies = DB::table('supplies')->orderBy('name')->get()->map(fn ($r) => (array) $r)->all();

        return [
            'suppliers' => $suppliers,
            'supplies' => $supplies,
        ];
    }

    public function find(int $id): ?array
    {
        $po = DB::table('purchase_orders')
            ->select('purchase_orders.*', 'suppliers.name as supplier_name')
            ->leftJoin('suppliers', 'suppliers.id', '=', 'purchase_orders.supplier_id')
            ->where('purchase_orders.id', $id)
            ->first();

        if (!$po) {
            return null;
        }

        $items = DB::table('purchase_order_items')
            ->select('purchase_order_items.*', 'supplies.name as supply_name', 'supplies.unit as supply_unit')
            ->leftJoin('supplies', 'supplies.id', '=', 'purchase_order_items.supply_id')
            ->where('purchase_order_id', $id)
            ->get()
            ->map(fn ($row) => (array) $row)
            ->all();

        return [
            'purchase_order' => (array) $po,
            'items' => $items,
        ];
    }
}
