<?php

namespace App\Http\Controllers;

use App\Supplier;
use App\supplier_brand;
use Illuminate\Http\Request;

class PurchaseorderController extends Controller
{
    public function index()
    {
        return view('purchase_order.index');
    }
    public function create()
    {
        $supplier = Supplier::all();
        return view('purchase_order.create', compact('supplier'));
    }

    public function store(Request $request)
    {
        // Validate the incoming request data
        dd($request);
        $request->validate([
            'supplier_name' => 'required',
            'date' => 'required',
            'products' => 'required|array',
            'products.*.productId' => 'required',
            'products.*.brand' => 'required',
            'products.*.product' => 'required',
            'products.*.currency' => 'required',
            'products.*.unitPrice' => 'required|numeric',
            'products.*.qty' => 'required|integer',
            'products.*.totalPrice' => 'required|numeric',
        ]);

        // Loop through the products and store them in the database
        foreach ($request->products as $product) {
            PurchaseOrder::create([
                'supplier_name' => $request->supplier_name,
                'date' => $request->date,
                'product_id' => $product['productId'],
                'brand' => $product['brand'],
                'product' => $product['product'],
                'currency' => $product['currency'],
                'unit_price' => $product['unitPrice'],
                'qty' => $product['qty'],
                'total_price' => $product['totalPrice'],
            ]);
        }

        // Redirect or return a response
        return redirect()->route('po.list')->with('success', 'Purchase Order created successfully.');
    }
}
