<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Models\Cart;
use App\Models\Order;

class CheckoutController extends Controller
{
    public function process(Request $request)
{
    $request->validate([
        'nama_penerima' => 'required',
        'alamat' => 'required',
        'metode_pembayaran' => 'required',
    ]);

    $cartItems = Cart::where('user_id', Auth::id())->with('pizza')->get();

    foreach ($cartItems as $item) {
        Order::create([
            'user_id' => Auth::id(),
            'pizza_id' => $item->pizza_id,
            'nama_pelanggan' => $request->nama_penerima,
            'alamat' => $request->alamat,
            'metode_pembayaran' => $request->metode_pembayaran,
            'jumlah' => $item->jumlah,
            'total_harga' => $item->jumlah * $item->pizza->harga,
            'status' => 'pending',
        ]);
    }

    Cart::where('user_id', Auth::id())->delete();

    return redirect('/pesanan')->with('success', 'Pesanan berhasil dibuat!');
}

}
