<?php

namespace App\Http\Controllers\Admin;

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

class ConfigurationController extends Controller
{
    /**
     * Display a listing of system configurations
     */
    public function index()
    {
        // Return improved configuration view with all settings organized by category
        return view('admin.configurations.improved');
    }


    /**
     * Bulk update configurations from improved form
     */
    public function bulkUpdate(Request $request)
    {
        try {
            $updates = [];
            \Log::info('Configuration update started', ['user' => auth()->id()]);

            // Process notifications settings
            if ($request->has('notifications')) {
                foreach ($request->input('notifications', []) as $type => $settings) {
                    foreach ($settings as $key => $value) {
                        $configKey = "notifications.{$type}.{$key}";
                        $updates[$configKey] = is_array($value) ? json_encode($value) : $value;
                    }
                }
            }

            // Process notification channels
            if ($request->has('channels')) {
                foreach ($request->input('channels', []) as $notificationType => $channels) {
                    $configKey = "notifications.channels.{$notificationType}";
                    $updates[$configKey] = json_encode($channels ?? []);
                }
            }

            // Process email settings
            if ($request->has('email')) {
                foreach ($request->input('email', []) as $key => $value) {
                    $configKey = "email.{$key}";
                    $updates[$configKey] = $value;
                }
            }

            // Process SMS settings
            if ($request->has('sms')) {
                foreach ($request->input('sms', []) as $key => $value) {
                    if (is_array($value)) {
                        foreach ($value as $subKey => $subValue) {
                            $configKey = "sms.{$key}.{$subKey}";
                            $updates[$configKey] = $subValue;
                        }
                    } else {
                        $configKey = "sms.{$key}";
                        $updates[$configKey] = $value;
                    }
                }
            }

            // Process payment settings - FIXED
            if ($request->has('payment')) {
                $paymentData = $request->input('payment', []);
                foreach ($paymentData as $key => $value) {
                    if (is_array($value)) {
                        foreach ($value as $subKey => $subValue) {
                            $configKey = "payment.{$key}.{$subKey}";
                            // Store checkboxes as 1 or 0
                            if ($subKey === 'enabled') {
                                $updates[$configKey] = $subValue === '1' || $subValue === 1 || $subValue === true ? '1' : '0';
                            } else {
                                $updates[$configKey] = $subValue;
                            }
                        }
                    } else {
                        $configKey = "payment.{$key}";
                        $updates[$configKey] = $value;
                    }
                }
            }

            // Process business settings
            if ($request->has('business')) {
                foreach ($request->input('business', []) as $key => $value) {
                    if (is_array($value)) {
                        foreach ($value as $subKey => $subValue) {
                            $configKey = "business.{$key}.{$subKey}";
                            $updates[$configKey] = $subValue;
                        }
                    } else {
                        $configKey = "business.{$key}";
                        $updates[$configKey] = $value;
                    }
                }
            }

            // Process security settings
            if ($request->has('security')) {
                foreach ($request->input('security', []) as $key => $value) {
                    $configKey = "security.{$key}";
                    $updates[$configKey] = $value;
                }
            }

            // Update all configurations with validation
            $updateCount = 0;
            foreach ($updates as $key => $value) {
                try {
                    SystemConfiguration::updateOrCreate(
                        ['key' => $key],
                        ['value' => $value]
                    );
                    $updateCount++;
                } catch (\Exception $e) {
                    \Log::error("Failed to update config key: {$key}", ['error' => $e->getMessage()]);
                    throw new \Exception("Failed to update {$key}: " . $e->getMessage());
                }
            }

            \Log::info('Configuration update completed', ['count' => $updateCount]);

            // Return appropriate response based on request type
            if ($request->expectsJson()) {
                return response()->json([
                    'success' => true,
                    'message' => "Configuration saved successfully! ({$updateCount} settings updated)",
                    'data' => $updates
                ], 200);
            }

            return back()->with('success', "Configuration saved successfully! ({$updateCount} settings updated)");
        } catch (\Exception $e) {
            \Log::error('Configuration update error: ' . $e->getMessage(), [
                'exception' => $e,
                'user' => auth()->id()
            ]);

            if ($request->expectsJson()) {
                return response()->json([
                    'success' => false,
                    'message' => 'Error updating configuration: ' . $e->getMessage()
                ], 422);
            }

            return back()->with('error', 'Error updating configuration: ' . $e->getMessage());
        }
    }

    /**
     * Update the specified configuration
     */
    public function update(Request $request, $key)
    {

        $configuration = SystemConfiguration::where('key', $key)->firstOrFail();

        $validated = $request->validate([
            'value' => 'required',
        ]);

        // Try to decode JSON if it looks like JSON
        $value = $validated['value'];
        if (is_string($value) && (json_decode($value) !== null)) {
            $value = json_decode($value, true);
        }

        $configuration->update(['value' => $value]);

        return redirect()->route('admin.configurations.index')
            ->with('success', 'Configuration updated successfully.');
    }
}

