<?php
// app/Http/Controllers/CartController.php

namespace App\Http\Controllers;

use App\Models\Carts;
use App\Models\Product;
use Illuminate\Http\Request;

class CartController extends Controller
{
    private function blockAdmin()
    {
        if (!auth()->check() || auth()->user()->role === 'admin') {
            abort(403, 'Admin tidak boleh mengakses cart');
        }
    }

    /** Tampilkan isi keranjang */
    public function index()
    {
        $this->blockAdmin();

        $user  = auth()->user();
        $carts = Carts::with('product')->where('user_id', $user->id)->get();

        $total = $carts->sum(fn($c) => ($c->product->price ?? 0) * $c->quantity);

        return view('cart.index', compact('carts', 'total'));
    }

    /** Tambah ke keranjang */
    public function store(Request $request)
    {
        $this->blockAdmin();

        $request->validate([
            'product_id' => 'required|exists:tbl_product,product_id',
            'quantity'   => 'nullable|integer|min:1',
        ]);

        $product  = Product::findOrFail($request->product_id);
        $quantity = $request->quantity ?? 1;

        if ($product->stock < $quantity) {
            return back()->with('error', 'Stok tidak mencukupi');
        }

        $cart = Carts::where('user_id', auth()->id())
            ->where('product_id', $request->product_id)
            ->first();

        if ($cart) {
            $newQty = $cart->quantity + $quantity;
            if ($newQty > $product->stock) {
                return back()->with('error', 'Stok tidak mencukupi');
            }
            $cart->update(['quantity' => $newQty]);
        } else {
            Carts::create([
                'user_id'    => auth()->id(),
                'product_id' => $request->product_id,
                'quantity'   => $quantity,
            ]);
        }

        return back()->with('success', 'Produk berhasil ditambahkan ke keranjang');
    }    
    /** Tambah quantity */
    public function increase($cart_id)
    {
        $this->blockAdmin();

        $cart = Carts::with('product')->findOrFail($cart_id);
        if ($cart->user_id !== auth()->id()) abort(403);

        if ($cart->quantity >= ($cart->product->stock ?? 0)) {
            return back()->with('error', 'Stok tidak mencukupi');
        }

        $cart->increment('quantity');
        return back()->with('success', 'Quantity berhasil ditambah');
    }

    /** Kurangi quantity */
    public function decrease($cart_id)
    {
        $this->blockAdmin();

        $cart = Carts::findOrFail($cart_id);
        if ($cart->user_id !== auth()->id()) abort(403);

        if ($cart->quantity > 1) {
            $cart->decrement('quantity');
        } else {
            $cart->delete();
        }

        return back()->with('success', 'Quantity berhasil diubah');
    }

    /** Hapus item */
    public function destroy($cart_id)
    {
        $this->blockAdmin();

        $cart = Carts::with('product')->findOrFail($cart_id);
        if ($cart->user_id !== auth()->id()) abort(403);

        $productName = $cart->product->product_name ?? 'Produk';
        $cart->delete();

        if (request()->ajax() || request()->wantsJson()) {
            return response()->json([
                'success'    => true,
                'message'    => $productName . ' dihapus dari keranjang',
                'cart_total' => $this->calculateCartTotal(),
                'item_count' => $this->getItemCount(),
            ]);
        }

        return back()->with('success', $productName . ' dihapus dari keranjang');
    }

    /** Hapus batch */
    public function batchDelete(Request $request)
    {
        $this->blockAdmin();

        $request->validate([
            'cart_ids'   => 'required|array',
            'cart_ids.*' => 'integer',
        ]);

        $deleted = Carts::whereIn('cart_id', $request->cart_ids)
            ->where('user_id', auth()->id())
            ->delete();

        return response()->json([
            'success'       => true,
            'message'       => $deleted . ' item berhasil dihapus',
            'deleted_count' => $deleted,
        ]);
    }

    /**
     * Halaman preview checkout (BELUM masuk DB).
     * User memilih metode pembayaran dan alamat di sini,
     * lalu klik "Buat Pesanan" → OrderController@checkout
     */
    public function checkoutPreview(Request $request)
    {
        $this->blockAdmin();

        $user = auth()->user();

        // Cek dulu apakah ini flow buy now
        if (session('buynow_product_id')) {
            $productId = session('buynow_product_id');
            $product   = Product::find($productId);

            if (!$product) {
                return redirect()->route('product.index')
                    ->with('error', 'Produk tidak ditemukan.');
            }

            $fakeCartItem = (object)[
                'product'  => $product,
                'quantity' => 1,
                'cart_id'  => null,
            ];

            $addresses         = $user->addresses()->with(['province', 'city', 'district', 'village'])->latest()->get();
            $selectedAddressId = session('selected_address_id');

            return view('checkout.index', [
                'cartItems'         => collect([$fakeCartItem]),
                'selectedIds'       => [],
                'addresses'         => $addresses,
                'selectedAddressId' => $selectedAddressId,
                'isBuyNow'          => true,
                'buyNowProductId'   => $product->product_id,
            ]);
        }

        // Flow cart biasa
        $selectedIds = json_decode($request->input('selected_items', '[]'), true);

        if (empty($selectedIds)) {
            $selectedIds = session('checkout_selected_ids', []);
        }

        if (!empty($selectedIds)) {
            session(['checkout_selected_ids' => $selectedIds]);
        }

        if (empty($selectedIds)) {
            return redirect()->route('cart.index')
                ->with('error', 'Pilih minimal 1 produk untuk checkout!');
        }

        $cartItems = Carts::with('product.category')
            ->where('user_id', $user->id)
            ->whereIn('cart_id', $selectedIds)
            ->get();

        if ($cartItems->isEmpty()) {
            return redirect()->route('cart.index')
                ->with('error', 'Item tidak ditemukan di keranjang.');
        }

        foreach ($cartItems as $cart) {
            if (!$cart->product || $cart->product->stock < $cart->quantity) {
                return redirect()->route('cart.index')
                    ->with('error', "Stok {$cart->product->product_name} tidak mencukupi!");
            }
        }

        session(['checkout_selected_ids' => $selectedIds]);

        $addresses         = $user->addresses()->with(['province', 'city', 'district', 'village'])->latest()->get();
        $selectedAddressId = session('selected_address_id');

        return view('checkout.index', compact('cartItems', 'selectedIds', 'addresses', 'selectedAddressId'));
    }

    // -------- helpers --------
    private function calculateCartTotal()
    {
        $carts = Carts::with('product')->where('user_id', auth()->id())->get();
        return number_format(
            $carts->sum(fn($c) => ($c->product->price ?? 0) * $c->quantity),
            0, ',', '.'
        );
    }

    private function getItemCount()
    {
        return Carts::where('user_id', auth()->id())->count();
    }
}