<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Cart;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\Wishlist;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;

class CartController extends Controller
{
    /**
     * Menampilkan halaman keranjang belanja
     */
    public function index()
    {
        $cartItems = Cart::with(['product.images', 'variant'])
            ->where('user_id', Auth::id())
            ->latest()
            ->get();

        $total = $cartItems->where('is_selected', true)->sum(function ($item) {
            return $item->quantity * $item->price_at_add;
        });

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

    /**
     * Tambah produk ke keranjang (AJAX / Stay on Page)
     */
    public function store(Request $request)
    {
        $result = $this->processCartLogic($request);
        
        // Jika result adalah string, berarti ada pesan error
        if (is_string($result)) {
            if ($request->ajax()) {
                return response()->json(['success' => false, 'message' => $result], 422);
            }
            return back()->with('error', $result);
        }
        
        // Jika request berasal dari AJAX (Stay on Page)
        if ($request->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Produk berhasil ditambahkan ke keranjang!',
                'cart_count' => Cart::where('user_id', Auth::id())->count()
            ]);
        }

        return redirect()->route('cart.index')->with('success', 'Produk ditambahkan ke keranjang!');
    }

    /**
     * Beli Sekarang (Langsung ke Checkout)
     */
    public function directCheckout(Request $request)
    {
        // 1. Unselect semua barang lain agar fokus ke barang "Beli Sekarang"
        Cart::where('user_id', Auth::id())->update(['is_selected' => false]);

        // 2. Proses masuk keranjang
        $result = $this->processCartLogic($request);

        if (is_string($result)) {
            return back()->with('error', $result);
        }

        // 3. Langsung arahkan ke halaman checkout
        return redirect()->route('checkout.index')->with('info', 'Silakan selesaikan pesanan Anda.');
    }

    /**
     * Logika utama pemrosesan data keranjang
     * Return TRUE jika sukses, Return STRING pesan error jika gagal
     */
    private function processCartLogic(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'product_variant_id' => 'required|exists:product_variants,id',
            'quantity' => 'required|integer|min:1'
        ]);

        $userId = Auth::id();
        $variant = ProductVariant::with('product')->find($request->product_variant_id);

        if (!$variant) return 'Varian produk tidak ditemukan.';

        // Penentuan Harga
        $finalPrice = ($variant->price && $variant->price > 0) 
                      ? $variant->price 
                      : $variant->product->base_price;

        if (!$finalPrice || $finalPrice == 0) {
            return 'Gagal: Harga produk tidak valid.';
        }

        // Cek stok variant
        if ($variant->stock < $request->quantity) {
            return 'Maaf, stok tidak mencukupi. Tersisa: ' . $variant->stock;
        }

        // Cari apakah produk sudah ada di keranjang
        $cart = Cart::where('user_id', $userId)
            ->where('product_id', $request->product_id)
            ->where('product_variant_id', $variant->id)
            ->first();

        if ($cart) {
            $cart->update([
                'quantity' => $cart->quantity + $request->quantity,
                'price_at_add' => $finalPrice, 
                'is_selected' => true
            ]);
        } else {
            Cart::create([
                'user_id' => $userId,
                'product_id' => $request->product_id,
                'product_variant_id' => $variant->id,
                'quantity' => $request->quantity,
                'price_at_add' => $finalPrice, 
                'is_selected' => true
            ]);
        }

        // Hapus dari wishlist
        Wishlist::where('user_id', $userId)
            ->where('product_id', $request->product_id)
            ->delete();
            
        return true;
    }

    /**
     * Update quantity via halaman keranjang
     */
    public function updateQuantity(Request $request, $id)
    {
        $request->validate(['quantity' => 'required|integer|min:1']);
        
        $cart = Cart::with('variant')->where('user_id', Auth::id())->findOrFail($id);
        
        if ($cart->variant && $request->quantity > $cart->variant->stock) {
            return back()->with('error', 'Stok hanya tersedia ' . $cart->variant->stock . ' unit.');
        }

        $cart->update(['quantity' => $request->quantity]);
        return back()->with('success', 'Jumlah belanja diperbarui.');
    }

    /**
     * Menghapus item dari keranjang
     */
    public function remove($id)
    {
        $cart = Cart::where('user_id', Auth::id())->findOrFail($id);
        $cart->delete();

        if (request()->ajax()) {
            return response()->json([
                'success' => true,
                'message' => 'Item berhasil dihapus dari keranjang.',
                'cart_count' => Cart::where('user_id', Auth::id())->sum('quantity')
            ]);
        }

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

    /**
     * Toggle centang (is_selected) untuk checkout
     */
    public function toggleSelect($id)
    {
        $cart = Cart::where('user_id', Auth::id())->findOrFail($id);
        $cart->update(['is_selected' => !$cart->is_selected]);
        return back();
    }

    public function toggleAll(Request $request)
    {
        $cartItems = Cart::where('user_id', auth()->id())->get();
        
        // Cek apakah saat ini semua sudah terpilih atau belum
        $allSelected = $cartItems->every('is_selected', true);

        // Jika semua sudah terpilih, maka uncheck semua. Jika belum, maka check semua.
        Cart::where('user_id', auth()->id())->update([
            'is_selected' => !$allSelected
        ]);

        return back()->with('success', $allSelected ? 'Semua item batal dipilih' : 'Semua item dipilih');
    }
}