<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Produk;

class CartController extends Controller
{
    // Menampilkan Halaman Keranjang
    public function index()
    {
        $cart = session()->get('cart', []);
        return view('landing.cart', compact('cart'));
    }

    // Menambahkan Produk ke Session Keranjang
    public function addToCart(Request $request)
    {
        $id = $request->id;
        $produk = Produk::findOrFail($id);

        $cart = session()->get('cart', []);

        // Validasi qty default ke 1 jika kosong
        $quantity = $request->qty ? $request->qty : 1;

        if (isset($cart[$id])) {
            $cart[$id]['quantity'] += $quantity;
        } else {
            $cart[$id] = [
                "name" => $produk->nama_produk,
                "quantity" => $quantity,
                "price" => $produk->harga,
                "photo" => $produk->foto_produk
            ];
        }

        session()->put('cart', $cart);
        return redirect()->back()->with('success', 'Produk berhasil masuk keranjang!');
    }

    public function updateCart(Request $request)
    {
        if ($request->id && $request->quantity) {
            $cart = session()->get('cart');
            $cart[$request->id]["quantity"] = $request->quantity;
            session()->put('cart', $cart);
            session()->flash('success', 'Keranjang berhasil diperbarui');
        }
    }

    // Menghapus Item dari Keranjang
    public function remove(Request $request)
    {
        if ($request->id) {
            $cart = session()->get('cart');
            if (isset($cart[$request->id])) {
                unset($cart[$request->id]);
                session()->put('cart', $cart);
            }
            return redirect()->back()->with('success', 'Produk dihapus dari keranjang');
        }
    }
}
