<?php

namespace App\Http\Controllers\API\Manager;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;

class RestaurantController extends Controller
{
    public function show(Request $request)
    {
        $user = $request->user();
        
        if (!$user->restaurant_id) {
            return response()->json([
                'success' => false,
                'message' => 'No restaurant assigned'
            ], 404);
        }
        
        $restaurant = \App\Models\Restaurant::find($user->restaurant_id);
        
        if (!$restaurant) {
            return response()->json([
                'success' => false,
                'message' => 'Restaurant not found'
            ], 404);
        }

        return response()->json([
            'success' => true,
            'data' => $restaurant
        ]);
    }

    public function update(Request $request)
    {
        $user = $request->user();
        
        if (!$user->restaurant_id) {
            return response()->json([
                'success' => false,
                'message' => 'No restaurant assigned'
            ], 404);
        }
        
        $restaurant = \App\Models\Restaurant::find($user->restaurant_id);
        
        if (!$restaurant) {
            return response()->json([
                'success' => false,
                'message' => 'Restaurant not found'
            ], 404);
        }

        $validated = $request->validate([
            'name' => 'sometimes|string|max:255',
            'phone' => 'sometimes|string|max:20',
            'email' => 'nullable|email',
            'description' => 'nullable|string',
            'address' => 'sometimes|string',
            'minimum_order' => 'nullable|numeric|min:0',
            'delivery_radius' => 'nullable|numeric|min:0',
            'opening_time' => 'nullable|date_format:H:i:s',
            'closing_time' => 'nullable|date_format:H:i:s',
            'operational_status' => 'nullable|in:open,closed,busy',
            'delivery_enabled' => 'nullable|boolean',
            'delivery_slots' => 'nullable|json'
        ]);

        // Remove delivery_fee from validated data if manager tries to change it
        unset($validated['delivery_fee']);
        
        // Convert time format if needed
        if (isset($validated['opening_time']) && strlen($validated['opening_time']) === 5) {
            $validated['opening_time'] .= ':00';
        }
        if (isset($validated['closing_time']) && strlen($validated['closing_time']) === 5) {
            $validated['closing_time'] .= ':00';
        }

        $restaurant->update($validated);

        return response()->json([
            'success' => true,
            'message' => 'Restaurant updated successfully',
            'data' => $restaurant
        ]);
    }
}
