<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Product;
use Illuminate\Support\Facades\Auth;

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

    /**
     * Tambah produk ke keranjang (Biasa)
     */
    public function add(Request $request, $id)
    {
        $product = Product::findOrFail($id);
        $cart = session()->get('cart', []);

        if (isset($cart[$id])) {
            $cart[$id]['quantity']++;
        } else {
            $cart[$id] = [
                "name"     => $product->name,
                "quantity" => 1,
                "price"    => $product->price,
                "image"    => $product->image
            ];
        }

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

    /**
     * Fitur BELI LANGSUNG (Skip Keranjang)
     * Pakai session 'buy_now' terpisah agar keranjang tidak terkontaminasi
     */
    public function buyNow(Request $request, $id)
    {
        $product = Product::findOrFail($id);

        // Simpan ke session TERPISAH, bukan ke 'cart'
        session()->put('buy_now', [
            $id => [
                "name"     => $product->name,
                "quantity" => 1,
                "price"    => $product->price,
                "image"    => $product->image
            ]
        ]);

        // Tandai bahwa ini mode beli langsung
        session()->put('checkout_mode', 'buy_now');

        return redirect()->route('user.cart.checkout');
    }

    /**
     * Halaman Checkout
     * - Jika dari beli langsung (via ID atau session buy_now): pakai session buy_now
     * - Jika dari keranjang biasa: pakai session cart
     */
    public function checkout(Request $request, $id = null)
    {
        // Mode beli langsung via URL param (dari halaman produk)
        if ($id) {
            $product = Product::findOrFail($id);

            session()->put('buy_now', [
                $product->id => [
                    'name'     => $product->name,
                    'quantity' => 1,
                    'price'    => $product->price,
                    'image'    => $product->image,
                ]
            ]);
            session()->put('checkout_mode', 'buy_now');
        }

        // Tentukan cart yang dipakai berdasarkan mode
        $mode = session()->get('checkout_mode', 'cart');

        if ($mode === 'buy_now') {
            $cart = session()->get('buy_now', []);
        } else {
            $cart = session()->get('cart', []);
        }

        if (empty($cart)) {
            return redirect()->route('user.cart.index')
                ->with('error', 'Keranjang kamu kosong!');
        }

        // Ambil semua alamat user
        $addresses = \App\Models\Address::where('user_id', Auth::id())->latest()->get();

        // Hitung ongkir default: pakai alamat utama jika ada
        $defaultAddress  = $addresses->where('is_default', true)->first() ?? $addresses->first();
        $defaultShipping = $defaultAddress
            ? \App\Helpers\ShippingCalculator::calculate(
                $defaultAddress->province_code,
                $defaultAddress->city_code
              )
            : \App\Helpers\ShippingCalculator::BASE_FEE;

        return view('cart.checkout', compact('cart', 'addresses', 'defaultShipping'));
    }

    /**
     * Hapus satu item dari keranjang (AJAX)
     */
    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 response()->json(['success' => true]);
        }
    }

    /**
     * Update quantity di keranjang
     */
    public function update(Request $request)
    {
        if ($request->id && $request->quantity) {
            $cart = session()->get('cart');
            $cart[$request->id]["quantity"] = $request->quantity;
            session()->put('cart', $cart);
            return response()->json(['success' => true]);
        }
    }
}