<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use App\Models\Restaurant;

class SettingsController extends Controller
{
    /**
     * Get printer settings
     */
    public function getPrinterSettings(): JsonResponse
    {
        try {
            $user = auth()->user();
            $restaurant = $user->restaurant;
            
            if (!$restaurant) {
                return response()->json([
                    'error' => 'Restaurant not found'
                ], 404);
            }

            $settings = $restaurant->settings ?? [];
            $printerId = $settings['printer_id'] ?? null;

            return response()->json([
                'printer_id' => $printerId,
                'settings' => $settings
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'error' => 'Failed to get printer settings',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Save printer settings
     */
    public function savePrinterSettings(Request $request): JsonResponse
    {
        try {
            $request->validate([
                'printer_id' => 'required|string'
            ]);

            $user = auth()->user();
            $restaurant = $user->restaurant;
            
            if (!$restaurant) {
                return response()->json([
                    'error' => 'Restaurant not found'
                ], 404);
            }

            // Get existing settings or create new array
            $settings = $restaurant->settings ?? [];
            
            // Update printer settings
            $settings['printer_id'] = $request->printer_id;
            $settings['printer_updated_at'] = now()->toISOString();
            $settings['printer_updated_by'] = $user->id;

            // Save to restaurant
            $restaurant->update([
                'settings' => $settings
            ]);

            return response()->json([
                'message' => 'Printer settings saved successfully',
                'printer_id' => $request->printer_id,
                'settings' => $settings
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'error' => 'Failed to save printer settings',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Get all restaurant settings
     */
    public function getSettings(): JsonResponse
    {
        try {
            $user = auth()->user();
            $restaurant = $user->restaurant;
            
            if (!$restaurant) {
                return response()->json([
                    'error' => 'Restaurant not found'
                ], 404);
            }

            return response()->json([
                'restaurant' => $restaurant,
                'settings' => $restaurant->settings ?? []
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'error' => 'Failed to get settings',
                'message' => $e->getMessage()
            ], 500);
        }
    }

    /**
     * Update restaurant settings
     */
    public function updateSettings(Request $request): JsonResponse
    {
        try {
            $user = auth()->user();
            $restaurant = $user->restaurant;
            
            if (!$restaurant) {
                return response()->json([
                    'error' => 'Restaurant not found'
                ], 404);
            }

            // Validate restaurant data
            $restaurantData = $request->validate([
                'name' => 'sometimes|string|max:255',
                'phone' => 'sometimes|string|max:20',
                'address' => 'sometimes|string|max:500',
                'vat_rate' => 'sometimes|numeric|min:0|max:100',
                'currency' => 'sometimes|string|in:KES,USD,EUR'
            ]);

            // Validate settings data
            $settingsData = $request->validate([
                'settings.auto_print_kitchen' => 'sometimes|boolean',
                'settings.sound_notifications' => 'sometimes|boolean',
                'settings.printer_id' => 'sometimes|string',
            ]);

            // Update restaurant basic info
            if (!empty($restaurantData)) {
                $restaurant->update($restaurantData);
            }

            // Update settings
            if (isset($settingsData['settings'])) {
                $currentSettings = $restaurant->settings ?? [];
                $newSettings = array_merge($currentSettings, $settingsData['settings']);
                $newSettings['updated_at'] = now()->toISOString();
                $newSettings['updated_by'] = $user->id;
                
                $restaurant->update(['settings' => $newSettings]);
            }

            return response()->json([
                'message' => 'Settings updated successfully',
                'restaurant' => $restaurant->fresh(),
                'settings' => $restaurant->fresh()->settings
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'error' => 'Failed to update settings',
                'message' => $e->getMessage()
            ], 500);
        }
    }
}