<?php

namespace App\Service\User;

use App\Models\Orders;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\DB;

class UserOrderService
{
    /**
     * Create a new order.
     *
     * @param array $data
     * @return Order
     *
     * @throws \Exception
     */
    public function placeOrder(array $data): Orders
    {
        return DB::transaction(function () use ($data) {

            // Calculate total amount from items if not provided
            if (empty($data['total_amount']) && isset($data['items']) && is_array($data['items'])) {
                $data['total_amount'] = collect($data['items'])->sum(function ($item) {
                    return $item['quantity'] * $item['unit_price'];
                });
            }
            // Create the order record
            $order = Orders::create([
                'user_id'          => $data['user_id'],
                'vendor_id'        => $data['vendor_id'],
                'items'            => $data['items'],
                'total_amount'     => $data['total_amount'],
                'status'           => $data['status'] ?? 'pending',
                'payment_status'   => $data['payment_status'] ?? 'unpaid',
                'delivery_address' => $data['delivery_address'] ?? null,
                'notes'            => $data['notes'] ?? null,
            ]);

            return $order;
        });
    }


}
