<?php
namespace App\Http\Controllers\User;

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

class CartController extends Controller
{
    public function index()
    {
        $cartItems = Cart::where('user_id', Auth::id())->with('pizza')->get();
        return view('user.cart.index', compact('cartItems'));
    }

    public function add(Request $request, $id)
    {
        Cart::create([
            'user_id' => Auth::id(),
            'pizza_id' => $id,
            'jumlah' => $request->quantity ?? 1,
        ]);
        return redirect()->route('user.cart.index')->with('success','Berhasil ditambahkan!');
    }

    public function delete($id)
    {
        Cart::where('id',$id)->where('user_id',Auth::id())->delete();
        return back()->with('success','Item dihapus!');
    }

    public function showCheckout()
    {
        $cartItems = Cart::where('user_id', Auth::id())->with('pizza')->get();
        if($cartItems->isEmpty()) return redirect()->route('user.cart.index')->with('error','Keranjang kosong!');
        $total = $cartItems->sum(fn($item)=>$item->jumlah*$item->pizza->harga);
        return view('user.checkout.index', compact('cartItems','total'));
    }

   public function processCheckout(Request $request)
{
    $request->validate([
        'nama_pelanggan' => 'required|string',
        'alamat' => 'required|string',
        'metode_pembayaran' => 'required|in:cod,qris'
    ]);

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

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

    Cart::where('user_id', $userId)->delete();

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