<?php

namespace App\Http\Controllers\User;

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

class CheckoutController extends Controller
{
    // Menampilkan halaman checkout
    public function index()
    {
        $cartItems = Cart::where('user_id', Auth::id())->with('pizza')->get();

        // Hitung total harga
        $total = 0;
        foreach ($cartItems as $item) {
            $total += $item->jumlah * $item->pizza->harga;
        }

        return view('user.checkout', compact('cartItems', 'total'));
    }

    // Memproses pesanan
    public function process(Request $request)
    {
        // Validasi
        $request->validate([
            'nama_pelanggan' => 'required|string|max:255',
            'alamat' => 'required|string',
            'metode_pembayaran' => 'required'
        ]);

        // Ambil data cart user
        $cartItems = Cart::where('user_id', Auth::id())->with('pizza')->get();

        if ($cartItems->isEmpty()) {
            return back()->with('error', 'Keranjang Anda kosong.');
        }

        // Simpan pesanan satu per satu
        foreach ($cartItems as $item) {

            Order::create([
                'user_id' => Auth::id(),
                'pizza_id' => $item->pizza_id,
                'nama_pelanggan' => $request->nama_pelanggan, // ← PENTING!
                'alamat' => $request->alamat,
                'metode_pembayaran' => $request->metode_pembayaran,
                'jumlah' => $item->jumlah,
                'total_harga' => $item->jumlah * $item->pizza->harga,
                'status' => 'pending',
            ]);
        }

        // Hapus cart setelah checkout
        Cart::where('user_id', Auth::id())->delete();

        return redirect()->route('user.orders')->with('success', 'Pesanan berhasil dibuat!');
    }
}
