<?php

namespace App\Services\PurchaseOrders;

use App\Models\PurchaseOrder;
use App\Models\PurchaseOrderItem;
use Illuminate\Support\Facades\DB;
use RuntimeException;

class PurchaseOrderCreateService
{
    public function create(array $payload): PurchaseOrder
    {
        $itemsPayload = $payload['items'] ?? [];
        if (empty($itemsPayload) || !is_array($itemsPayload)) {
            throw new RuntimeException('Add at least one line item.');
        }

        $subtotal = 0.0;
        $items = [];

        foreach ($itemsPayload as $item) {
            $supplyId = (int) ($item['supply_id'] ?? 0);
            $qty = max(0, (int) ($item['quantity'] ?? 0));
            $unitCost = (float) ($item['unit_cost'] ?? 0);

            if ($supplyId <= 0 || $qty <= 0) {
                continue;
            }

            $line = $qty * $unitCost;
            $subtotal += $line;

            $items[] = [
                'supply_id' => $supplyId,
                'description' => trim((string) ($item['description'] ?? '')),
                'quantity' => $qty,
                'unit_cost' => $unitCost,
                'received_qty' => 0,
            ];
        }

        if (empty($items)) {
            throw new RuntimeException('Valid line items required.');
        }

        $status = (string) ($payload['status'] ?? 'ordered');
        $status = in_array($status, [PurchaseOrder::STATUS_DRAFT, PurchaseOrder::STATUS_ORDERED], true) ? $status : PurchaseOrder::STATUS_ORDERED;

        $tax = 0.0;
        $total = $subtotal + $tax;

        return DB::transaction(function () use ($payload, $items, $status, $subtotal, $tax, $total) {
            $po = PurchaseOrder::query()->create([
                'po_number' => $payload['po_number'] ?? null,
                'supplier_id' => $payload['supplier_id'] ?? null,
                'order_date' => $payload['order_date'] ?? null,
                'expected_date' => $payload['expected_date'] ?? null,
                'notes' => $payload['notes'] ?? null,
                'status' => $status,
                'subtotal' => $subtotal,
                'tax' => $tax,
                'total' => $total,
            ]);

            foreach ($items as $item) {
                $item['purchase_order_id'] = $po->id;
                PurchaseOrderItem::query()->create($item);
            }

            return $po->refresh();
        });
    }
}
