<?php
// app/Http\Controllers\Web\Admin\MenuManagementController.php

namespace App\Http\Controllers\Web\Admin;

use App\Http\Controllers\Web\Api\BaseApiController;
use Illuminate\Http\Request;

class MenuManagementController extends BaseApiController
{
public function index(Request $request)
{
    set_time_limit(120); 
    $params = $request->only(['search', 'category_id', 'is_available', 'page']);
    
    $response = $this->apiRequest('get', 'menu', $params);
    
    // Get categories for filter
    $categoriesResponse = $this->apiRequest('get', 'categories');
    
    if ($response['success']) {
        return view('admin.menu.index', [
            'menus' => $response['data']['data'] ?? [], // Ini adalah ARRAY
            'pagination' => $response['data']['meta'] ?? null, // Info pagination dari API
            'categories' => $categoriesResponse['success'] ? 
                ($categoriesResponse['data']['data'] ?? []) : [],
            'filters' => $params,
            'title' => 'Menu Management',
        ]);
    }
    
    return view('admin.menu.index', [
        'menus' => [],
        'pagination' => null,
        'categories' => [],
        'filters' => $params,
        'title' => 'Menu Management',
    ]);
}

    public function create()
    {
        $response = $this->apiRequest('get', 'categories');
        
        return view('admin.menu.create', [
            'categories' => $response['success'] ? 
                ($response['data']['data'] ?? []) : [],
        ]);
    }

    public function store(Request $request)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'price' => 'required|numeric|min:0',
            'description' => 'nullable|string',
            'stock' => 'nullable|integer|min:0',
            'is_available' => 'boolean',
            'is_special' => 'boolean',
            'is_best_seller' => 'boolean',
            'image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
        ]);
        
        $data = $request->except('image');
        $data['is_available'] = $request->boolean('is_available');
        $data['is_special'] = $request->boolean('is_special');
        $data['is_best_seller'] = $request->boolean('is_best_seller');
        
        // Handle image upload
        if ($request->hasFile('image')) {
            $uploadResponse = $this->apiRequest('post', 'upload', [
                'file' => $request->file('image'),
            ]);
            
            if ($uploadResponse['success']) {
                $data['image_url'] = $uploadResponse['data']['url'] ?? $uploadResponse['data']['path'];
            }
        }
        
        $response = $this->apiRequest('post', 'menu', $data);
        
        if ($response['success']) {
            return redirect()->route('admin.menu.index')
                ->with('success', 'Menu item created successfully');
        }
        
        return back()->withErrors(
            $response['data']['errors'] ?? ['error' => 'Failed to create menu item']
        )->withInput();
    }

    public function show($id)
    {
        $response = $this->apiRequest('get', "menu/{$id}");
        
        if ($response['success']) {
            return view('admin.menu.show', [
                'menu' => $response['data']['data'] ?? $response['data'],
            ]);
        }
        
        return redirect()->route('admin.menu.index')
            ->with('error', 'Menu item not found');
    }

    public function edit($id)
    {
        $menuResponse = $this->apiRequest('get', "menu/{$id}");
        $categoriesResponse = $this->apiRequest('get', 'categories');
        
        if ($menuResponse['success']) {
            return view('admin.menu.edit', [
                'menu' => $menuResponse['data']['data'] ?? $menuResponse['data'],
                'categories' => $categoriesResponse['success'] ? 
                    ($categoriesResponse['data']['data'] ?? []) : [],
            ]);
        }
        
        return redirect()->route('admin.menu.index')
            ->with('error', 'Menu item not found');
    }

    public function update(Request $request, $id)
    {
        $request->validate([
            'name' => 'required|string|max:255',
            'category_id' => 'required|exists:categories,id',
            'price' => 'required|numeric|min:0',
            'description' => 'nullable|string',
            'stock' => 'nullable|integer|min:0',
            'is_available' => 'boolean',
            'is_special' => 'boolean',
            'is_best_seller' => 'boolean',
            'image' => 'nullable|image|mimes:jpg,jpeg,png|max:2048',
        ]);
        
        $data = $request->except('image');
        $data['is_available'] = $request->boolean('is_available');
        $data['is_special'] = $request->boolean('is_special');
        $data['is_best_seller'] = $request->boolean('is_best_seller');
        
        if ($request->hasFile('image')) {
            $uploadResponse = $this->apiRequest('post', 'upload', [
                'file' => $request->file('image'),
            ]);
            
            if ($uploadResponse['success']) {
                $data['image_url'] = $uploadResponse['data']['url'] ?? $uploadResponse['data']['path'];
            }
        }
        
        $response = $this->apiRequest('put', "menu/{$id}", $data);
        
        if ($response['success']) {
            return redirect()->route('admin.menu.index')
                ->with('success', 'Menu item updated successfully');
        }
        
        return back()->withErrors(
            $response['data']['errors'] ?? ['error' => 'Failed to update menu item']
        )->withInput();
    }

    public function destroy($id)
    {
        $response = $this->apiRequest('delete', "menu/{$id}");
        
        if ($response['success']) {
            return redirect()->route('admin.menu.index')
                ->with('success', 'Menu item deleted successfully');
        }
        
        return back()->withErrors(
            $response['data']['errors'] ?? ['error' => 'Failed to delete menu item']
        );
    }

    public function toggleAvailability($id)
    {
        // Get current menu
        $menuResponse = $this->apiRequest('get', "menu/{$id}");
        
        if ($menuResponse['success']) {
            $menu = $menuResponse['data']['data'] ?? $menuResponse['data'];
            $newStatus = !$menu['is_available'];
            
            $response = $this->apiRequest('put', "menu/{$id}", [
                'is_available' => $newStatus,
            ]);
            
            if ($response['success']) {
                $status = $newStatus ? 'available' : 'unavailable';
                return redirect()->route('admin.menu.index')
                    ->with('success', "Menu item marked as {$status}");
            }
        }
        
        return redirect()->route('admin.menu.index')
            ->with('error', 'Failed to update availability');
    }
}