<?php

namespace App\Http\Controllers;

use App\Models\Category;
use App\Models\Product;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;

class MenuController extends Controller
{
    public function index()
    {
        $categories = Category::with(['products' => function($query) {
            $query->where('is_visible', true); 
        }])->where('is_active', true)->get();

        return view('menu.index', compact('categories'));
    }

    public function showItem($id)
    {
        $item = Product::with('addons')->where('is_visible', true)->findOrFail($id);
        return view('menu.item', compact('item'));
    }

    // ✅ دالة جديدة: تجهيز صفحة التعديل
    public function editItem($id, $key)
    {
        $cart = Session::get('cart', []);
        
        // إذا العنصر غير موجود، ارجع للسلة
        if (!isset($cart[$key])) {
            return redirect()->route('cart.index');
        }

        $item = Product::with('addons')->where('is_visible', true)->findOrFail($id);
        $existingItem = $cart[$key]; // البيانات المحفوظة سابقاً

        return view('menu.item', compact('item', 'existingItem', 'key'));
    }

    public function cartIndex()
    {
        try {
            $cart = Session::get('cart', []);
            if (!is_array($cart)) { Session::forget('cart'); $cart = []; }

            $total = 0;
            foreach($cart as $item) {
                $total += ($item['price'] * $item['quantity']);
            }

            return view('menu.cart', ['cart' => $cart, 'total' => $total]);

        } catch (\Throwable $e) {
            Session::forget('cart');
            return view('menu.cart', ['cart' => [], 'total' => 0]);
        }
    }

    // ✅ تعديل دالة الإضافة لتدعم التعديل (حذف القديم وإضافة الجديد)
    public function addToCart(Request $request)
    {
        try {
            $cart = Session::get('cart', []);
            if (!is_array($cart)) $cart = [];

            // 1. إذا كنا في وضع تعديل، نحذف العنصر القديم أولاً
            if ($request->has('old_key') && isset($cart[$request->old_key])) {
                unset($cart[$request->old_key]);
            }

            // 2. إنشاء مفتاح جديد للعنصر الجديد
            $itemKey = md5($request->id . json_encode($request->variant_label) . json_encode($request->addons) . json_encode($request->notes) . json_encode($request->exclusions));

            $price = (float)$request->price;
            $quantity = (int)$request->quantity;

            // 3. إضافة أو دمج
            if(isset($cart[$itemKey])) {
                $cart[$itemKey]['quantity'] += $quantity;
                $cart[$itemKey]['total_price'] = $cart[$itemKey]['quantity'] * $price;
            } else {
                $cart[$itemKey] = [
                    'id' => $request->id,
                    'name' => $request->name,
                    'price' => $price,
                    'quantity' => $quantity,
                    'total_price' => $price * $quantity,
                    'variant_label' => $request->variant_label,
                    'addons' => $request->addons ?? [],
                    'exclusions' => $request->exclusions ?? [],
                    'notes' => $request->notes ?? ''
                ];
            }

            Session::put('cart', $cart);
            return response()->json(['success' => true]);
            
        } catch (\Throwable $e) {
            return response()->json(['success' => false, 'msg' => $e->getMessage()]);
        }
    }

    public function updateCart(Request $request)
    {
        $cart = Session::get('cart', []);
        if(isset($cart[$request->key])) {
            $cart[$request->key]['quantity'] = (int)$request->quantity;
            $cart[$request->key]['total_price'] = $cart[$request->key]['quantity'] * (float)$cart[$request->key]['price'];
            Session::put('cart', $cart);
            
            $newTotal = 0;
            foreach($cart as $i) $newTotal += $i['total_price'];
            
            return response()->json([
                'success' => true, 
                'new_item_total' => number_format($cart[$request->key]['total_price'], 2),
                'cart_total' => number_format($newTotal, 2)
            ]);
        }
        return response()->json(['success' => false]);
    }

    public function removeFromCart(Request $request)
    {
        $cart = Session::get('cart', []);
        if(isset($cart[$request->key])) {
            unset($cart[$request->key]);
            Session::put('cart', $cart);
        }
        return response()->json(['success' => true]);
    }
}