<?php

namespace App\Http\Controllers;

use App\Models\Setting;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AdminSettingsController extends Controller
{
    /**
     * Get all app settings.
     */
    public function getSettings()
    {
        $settings = [
            'base_fare' => Setting::get('base_fare', 300),
            'per_km_rate' => Setting::get('per_km_rate', 100),
            'per_minute_rate' => Setting::get('per_minute_rate', 20),
            'min_fare' => Setting::get('min_fare', 1200),
            'service_fee' => Setting::get('service_fee', 50),
            'surge_enabled' => Setting::get('surge_enabled', true),
            'surge_threshold_ratio' => Setting::get('surge_threshold_ratio', 1.5), // Demand/Supply ratio to trigger surge
            'surge_max_multiplier' => Setting::get('surge_max_multiplier', 2.5),
        ];

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

    /**
     * Update specified settings.
     */
    public function updateSettings(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'base_fare' => 'nullable|numeric|min:0',
            'per_km_rate' => 'nullable|numeric|min:0',
            'per_minute_rate' => 'nullable|numeric|min:0',
            'min_fare' => 'nullable|numeric|min:0',
            'service_fee' => 'nullable|numeric|min:0',
            'surge_enabled' => 'nullable|boolean',
            'surge_threshold_ratio' => 'nullable|numeric|min:1',
            'surge_max_multiplier' => 'nullable|numeric|min:1',
        ]);

        if ($validator->fails()) {
            return response()->json(['success' => false, 'errors' => $validator->errors()], 422);
        }

        foreach ($request->only([
            'base_fare', 'per_km_rate', 'per_minute_rate', 'min_fare', 
            'service_fee', 'surge_enabled', 'surge_threshold_ratio', 'surge_max_multiplier'
        ]) as $key => $value) {
            Setting::set($key, $value);
        }

        return response()->json([
            'success' => true,
            'message' => 'Settings updated successfully.'
        ]);
    }
}
