<?php

namespace App\Http\Controllers\Admin;

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

class SiteSettingController extends Controller
{
    public function index(Request $request)
    {
        // Ensure default settings exist
        SiteSetting::ensureDefaults();
        
        $query = SiteSetting::query();

        // Apply filters
        if ($request->filled('search')) {
            $search = $request->get('search');
            $query->where(function($q) use ($search) {
                $q->where('key', 'like', "%{$search}%")
                  ->orWhere('label', 'like', "%{$search}%")
                  ->orWhere('value', 'like', "%{$search}%")
                  ->orWhere('description', 'like', "%{$search}%");
            });
        }

        if ($request->filled('group')) {
            $query->where('group', $request->get('group'));
        }

        if ($request->filled('type')) {
            $query->where('type', $request->get('type'));
        }

        if ($request->has('status') && $request->get('status') !== '') {
            $query->where('is_active', (bool) $request->get('status'));
        }

        $settings = $query->orderBy('group')->orderBy('sort_order')->paginate(20);
        
        return view('admin.site-settings.index', compact('settings'));
    }

    // Create/Edit/Delete methods removed - settings are pre-defined via seeder
    // Only bulk update is allowed for production safety

    public function bulkUpdate(Request $request)
    {
        $settings = $request->input('settings', []);
        
        foreach ($settings as $id => $data) {
            $setting = SiteSetting::find($id);
            if ($setting) {
                $value = $data['value'] ?? $setting->value;
                
                // Handle file uploads
                if ($setting->type === 'file' && $request->hasFile("settings.{$id}.file")) {
                    $file = $request->file("settings.{$id}.file");
                    
                    // Validate file
                    if ($file->isValid()) {
                        // Delete old file if exists
                        if ($setting->value && file_exists(public_path($setting->value))) {
                            unlink(public_path($setting->value));
                        }
                        
                        // Determine upload path based on setting
                        $uploadPath = in_array($setting->key, ['favicon', 'site_favicon', 'admin_favicon']) ? 'images/' : 'images/';

                        // Generate filename
                        $filename = match($setting->key) {
                            'favicon' => 'favicon.' . $file->getClientOriginalExtension(),
                            'site_favicon' => 'favicon.' . $file->getClientOriginalExtension(),
                            'admin_favicon' => 'admin-favicon.' . $file->getClientOriginalExtension(),
                            default => $setting->key . '.' . $file->getClientOriginalExtension()
                        };
                        
                        // Move file
                        $file->move(public_path($uploadPath), $filename);
                        $value = $uploadPath . $filename;
                    }
                }
                
                $setting->update([
                    'value' => $value,
                    'is_active' => isset($data['is_active']) ? (bool) $data['is_active'] : $setting->is_active
                ]);
            }
        }

        return redirect()->route('admin.site-settings.index')
            ->with('success', 'Settings updated successfully.');
    }
}