<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Configuration;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;

class ConfigurationController extends Controller
{
    /**
     * Display a listing of the configurations.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $group = $request->get('group', 'Meta');
        $groups = Configuration::select('group')->distinct()->pluck('group');
        $configurations = Configuration::where('group', $group)->orderBy('key')->get();
        
        return view('admin.configurations.index', compact('configurations', 'groups', 'group'));
    }
    
    /**
     * Batch update configurations by group.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function batchUpdate(Request $request)
    {
        $group = $request->group;
        $configs = $request->configs ?? [];
        $fileConfigs = $request->file_configs ?? [];
        $existingFiles = $request->existing_files ?? [];
        
        // Get all configurations in the group to ensure we also process the ones not included in $configs
        $configurations = Configuration::where('group', $group)->get();

        foreach ($configurations as $config) {
            if ($config->type === 'boolean') {
                // For boolean types, explicitly set to '0' if not in the request
                $config->value = isset($configs[$config->id]) ? '1' : '0';
            } else {
                // For other types, only update if included in request
                if (isset($configs[$config->id])) {
                    $config->value = $configs[$config->id];
                }
            }
            $config->save();
        }

        // Handle file uploads
        foreach ($fileConfigs as $id => $file) {
            if ($file) {
                $config = Configuration::findOrFail($id);
                
                // Delete previous file if exists
                if (!empty($config->value) && Storage::disk('public')->exists($config->value)) {
                    Storage::disk('public')->delete($config->value);
                }
                
                // Store the new file
                $path = $file->store('configurations/' . $config->group, 'public');
                $config->value = Storage::url($path);
                $config->save();
            }
        }
        
        // Keep existing files for configs that didn't receive a new upload
        foreach ($existingFiles as $id => $path) {
            if (!isset($fileConfigs[$id])) {
                $config = Configuration::findOrFail($id);
                $config->value = $path;
                $config->save();
            }
        }
        
        // Clear config cache
        $this->refreshConfigCache();
        
        return redirect()->route('admin.configurations.index', ['group' => $group])
            ->with('success', 'Configurations updated successfully.');
    }

    /**
     * Refresh the configuration cache.
     *
     * @return void
     */
    private function refreshConfigCache()
    {
        Cache::forget('app_configurations');
        
        // Get all configurations
        $configurations = Configuration::all();
        
        // Transform into a more accessible format
        $configArray = [];
        foreach ($configurations as $config) {
            $configArray[$config->key] = $config->typed_value;
        }
        
        // Store in cache
        Cache::forever('app_configurations', $configArray);
    }
}