<?php

namespace App\Http\Controllers;

use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Routing\Controllers\HasMiddleware;
use Illuminate\Routing\Controllers\Middleware;

// Tambahkan "implements HasMiddleware" di sini
class CartController extends Controller implements HasMiddleware
{
    // =======================================================
    // CARA LARAVEL 11: BLOKIR AKSES ADMIN
    // =======================================================
    public static function middleware(): array
    {
        return [
            new Middleware(function ($request, $next) {
                if (auth()->check() && auth()->user()->is_admin) {
                    return redirect()->route('front.index')
                        ->with('error', 'Akses ditolak! Admin tidak diizinkan untuk menggunakan fitur keranjang dan belanja.');
                }

                return $next($request);
            }),
        ];
    }

    // Menampilkan halaman keranjang
    public function index()
    {
        // ---------------------------------------------------------
        // LOGIKA BARU: AUTO-SWEEP BARANG SOLD OUT DARI KERANJANG
        // ---------------------------------------------------------
        $cart = session()->get('cart', []);
        $removedItems = [];
        $isCartUpdated = false;

        if (! empty($cart)) {
            foreach ($cart as $id => $details) {
                $product = Product::find($id);

                // Cek apakah produk dihapus dari DB, atau statusnya sold/booked, atau stok habis
                if (! $product || $product->status == 'sold' || $product->status == 'booked' || ($product->stock !== null && $product->stock <= 0)) {
                    $removedItems[] = $details['name'] ?? 'Produk';
                    unset($cart[$id]);
                    $isCartUpdated = true;
                }
            }

            // Jika ada barang yang dihapus, simpan ulang keranjang dan refresh halaman bawa pesan error
            if ($isCartUpdated) {
                session()->put('cart', $cart);
                $names = implode(', ', $removedItems);

                // Redirect ke diri sendiri biar pesan SweetAlert/Error muncul dengan sempurna
                return redirect()->route('cart.index')->with('error', 'Waduh! Beberapa item dihapus otomatis dari keranjang karena keburu laku: '.$names);
            }
        }

        return view('front.cart');
    }

    // Tambah ke keranjang
    public function addToCart($id)
    {
        $product = Product::findOrFail($id);

        if ($product->status == 'sold' || $product->status == 'booked' || ($product->stock !== null && $product->stock <= 0)) {
            return redirect()->back()->with('error', 'Maaf, produk ini sudah terjual atau sedang dipesan orang lain!');
        }

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

        // LOGIKA BARU UNTUK THRIFT STORE (STOK 1)
        if (isset($cart[$id])) {
            // Tolak jika barang sudah ada di keranjang
            return redirect()->back()->with('error', 'Produk ini sudah ada di keranjang kamu!');
        } else {
            // Masukkan ke keranjang dengan kuantitas paten 1
            $cart[$id] = [
                'name' => $product->name,
                'quantity' => 1,
                'price' => $product->price,
                'image' => $imagePath,
                'brand' => $product->brand ?? 'No Brand',
                'stock' => $product->stock, // <--- TAMBAHAN: Simpan data stock ke session
            ];
        }

        session()->put('cart', $cart);

        return redirect()->back()->with('success', 'Produk ditambahkan ke keranjang!');
    }

    // Hapus 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);
            }
            session()->flash('success', 'Produk berhasil dihapus');
        }

        return redirect()->back();
    }

    // Proses checkout yang dipilih (Checkbox)
    public function checkoutSelected(Request $request)
    {
        $selectedIds = $request->input('selected_products');

        if (! $selectedIds || empty($selectedIds)) {
            return redirect()->back()->with('error', 'Silakan pilih minimal satu produk untuk checkout.');
        }

        $fullCart = session('cart', []);
        $checkoutItems = [];

        foreach ($selectedIds as $id) {
            $productCheck = Product::find($id);

            if (! $productCheck || $productCheck->status == 'sold' || $productCheck->status == 'booked' || ($productCheck->stock !== null && $productCheck->stock <= 0)) {

                if (isset($fullCart[$id])) {
                    unset($fullCart[$id]);
                    session()->put('cart', $fullCart);
                }

                return redirect()->back()->with('error', 'Maaf, item "'.($productCheck->name ?? 'Produk').'" baru saja terjual atau sedang dipesan orang lain.');
            }

            if (isset($fullCart[$id])) {
                $checkoutItems[$id] = $fullCart[$id];
            }
        }

        session(['checkout_items' => $checkoutItems]);
        session()->forget('buy_now_data');

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

    // Logic Beli Sekarang
    public function buyNow($id)
    {
        $product = Product::findOrFail($id);

        if ($product->status == 'sold' || $product->status == 'booked' || ($product->stock !== null && $product->stock <= 0)) {
            return redirect()->back()->with('error', 'Maaf, produk ini sudah terjual atau sedang dipesan orang lain!');
        }

        $buyNowData = [
            $id => [
                'name' => $product->name,
                'quantity' => 1,
                'price' => $product->price,
                'image' => $product->image,
                'brand' => $product->brand ?? 'No Brand',
                'stock' => $product->stock, // <--- TAMBAHAN: Simpan data stock ke session Buy Now juga buat jaga-jaga
            ],
        ];

        session(['buy_now_data' => $buyNowData]);
        session()->forget('checkout_items');

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