<?php

namespace App\Http\Controllers;

use App\Models\Cart;
use App\Models\MenuItem;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;

class CartController extends Controller
{
    public function index()
    {
        $cartItems = Cart::where('user_id', Auth::id())
            ->with('menu')
            ->get();
        
        $totals = Cart::calculateTotals($cartItems);

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

    public function add(Request $request)
    {
        try {
            Log::info('Add to Cart Request:', [
                'request_data' => $request->all(),
                'user_id' => Auth::id(),
                'is_authenticated' => Auth::check()
            ]);

            if (!Auth::check()) {
                Log::warning('Unauthorized attempt to add to cart');
                return response()->json([
                    'status' => 'error',
                    'message' => 'Silakan login terlebih dahulu'
                ], 401);
            }

            $menu = MenuItem::findOrFail($request->menu_id);
            Log::info('Found menu item:', [
                'menu_id' => $menu->id,
                'menu_name' => $menu->name,
                'menu_price' => $menu->price
            ]);
            
            DB::beginTransaction();
            
            try {
                $cart = Cart::where('user_id', Auth::id())
                    ->where('menu_id', $menu->id)
                    ->first();

                Log::info('Existing cart item:', [
                    'exists' => (bool)$cart,
                    'cart_data' => $cart ? $cart->toArray() : null
                ]);

                if ($cart) {
                    // Update existing cart item
                    $cart->quantity += 1;
                    $cart->subtotal = $cart->quantity * $menu->price;
                    $cart->save();
                    
                    Log::info('Updated existing cart item:', $cart->toArray());
                } else {
                    // Create new cart item
                    $cart = Cart::create([
                        'user_id' => Auth::id(),
                        'menu_id' => $menu->id,
                        'quantity' => 1,
                        'price' => $menu->price,
                        'subtotal' => $menu->price,
                    ]);
                    
                    Log::info('Created new cart item:', $cart->toArray());
                }

                $cartItems = Cart::where('user_id', Auth::id())
                    ->with('menu')
                    ->get();

                Log::info('All cart items after update:', [
                    'items_count' => $cartItems->count(),
                    'items' => $cartItems->toArray()
                ]);

                $mappedItems = $cartItems->map(function ($item) {
                    return [
                        'id' => $item->id,
                        'name' => $item->menu->name,
                        'price' => $item->price,
                        'quantity' => $item->quantity,
                        'subtotal' => $item->price * $item->quantity,
                        'image' => $item->menu->image
                    ];
                })->values();

                $totalItems = $cartItems->sum('quantity');
                $totalHarga = $cartItems->sum('subtotal');

                DB::commit();

                Log::info('Cart operation successful', [
                    'total_items' => $totalItems,
                    'total_harga' => $totalHarga
                ]);

                return response()->json([
                    'status' => 'success',
                    'message' => 'Item berhasil ditambahkan ke keranjang',
                    'cartCount' => $totalItems,
                    'cartItems' => $mappedItems,
                    'totalHarga' => $totalHarga
                ]);

            } catch (\Exception $e) {
                DB::rollback();
                Log::error('Database Error in add to cart:', [
                    'error' => $e->getMessage(),
                    'trace' => $e->getTraceAsString()
                ]);
                throw $e;
            }
        } catch (\Exception $e) {
            Log::error('Error in add to cart:', [
                'error' => $e->getMessage(),
                'trace' => $e->getTraceAsString(),
                'request_data' => $request->all()
            ]);
            
            return response()->json([
                'status' => 'error',
                'message' => 'Gagal menambahkan item ke keranjang: ' . $e->getMessage()
            ], 500);
        }
    }

    public function update(Request $request)
    {
        $request->validate([
            'cart_id' => 'required|exists:carts,id',
            'quantity' => 'required|integer|min:1'
        ]);

        $cart = Cart::where('user_id', Auth::id())
            ->where('id', $request->cart_id)
            ->firstOrFail();

        $cart->quantity = $request->quantity;
        $cart->subtotal = $cart->price * $cart->quantity;
        $cart->save();

        $cartItems = Cart::where('user_id', Auth::id())
            ->with('menu')
            ->get()
            ->map(function ($item) {
                return [
                    'id' => $item->id,
                    'menu_id' => $item->menu_id,
                    'name' => $item->menu->name,
                    'price' => $item->price,
                    'quantity' => $item->quantity,
                    'subtotal' => $item->price * $item->quantity,
                    'image' => $item->menu->image
                ];
            });

        $totals = Cart::calculateTotals($cartItems);

        return response()->json([
            'status' => 'success',
            'message' => 'Keranjang berhasil diupdate',
            'cartItems' => $cartItems,
            'cartCount' => $cartItems->sum('quantity'),
            'totalHarga' => $totals['total']
        ]);
    }

    public function remove(Request $request)
    {
        $cart = Cart::where('user_id', Auth::id())
            ->where('id', $request->cart_id)
            ->firstOrFail();

        $cart->delete();

        $cartItems = Cart::where('user_id', Auth::id())
            ->with('menu')
            ->get()
            ->map(function ($item) {
                return [
                    'id' => $item->id,
                    'menu_id' => $item->menu_id,
                    'name' => $item->menu->name,
                    'price' => $item->price,
                    'quantity' => $item->quantity,
                    'subtotal' => $item->subtotal,
                    'image' => $item->menu->image
                ];
            });

        $totals = Cart::calculateTotals($cartItems);

        return response()->json([
            'status' => 'success',
            'message' => 'Item berhasil dihapus dari keranjang',
            'cartCount' => $cartItems->sum('quantity'),
            'cartItems' => $cartItems,
            'totals' => $totals
        ]);
    }

    public function clear()
    {
        Cart::where('user_id', Auth::id())->delete();

        return response()->json([
            'status' => 'success',
            'message' => 'Keranjang berhasil dikosongkan'
        ]);
    }

    public function getCart()
    {
        $cartItems = Cart::where('user_id', Auth::id())
            ->with('menu')
            ->get();

        // Debug log
        Log::info('Cart Items:', [
            'raw' => $cartItems->toArray(),
        ]);

        $mappedItems = $cartItems->map(function ($item) {
            return [
                'id' => $item->id,
                'menu_id' => $item->menu_id,
                'name' => $item->menu->name,
                'price' => $item->price,
                'quantity' => $item->quantity,
                'subtotal' => $item->subtotal,
                'image' => $item->menu->image
            ];
        });

        // Debug log
        Log::info('Mapped Items:', [
            'mapped' => $mappedItems->toArray(),
        ]);

        $totals = Cart::calculateTotals($cartItems);

        return response()->json([
            'status' => 'success',
            'cartItems' => $mappedItems,
            'cartCount' => $cartItems->sum('quantity'),
            'totalHarga' => $totals['total']
        ]);
    }
}

