<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\LoadingScreenSettings;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Validator;

class LoadingScreenController extends Controller
{
    /**
     * Display the loading screen settings page.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $settings = LoadingScreenSettings::getSettings();
        return view('admin.loading-screen.index', compact('settings'));
    }

    /**
     * Update the loading screen settings.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        try {
            $settings = LoadingScreenSettings::getSettings();
            
            // Validate the request
            $validator = Validator::make($request->all(), [
                'background_color' => 'nullable|string|max:7',
                'primary_color' => 'nullable|string|max:7',
                'music_volume' => 'required|numeric|between:0,1',
                'logo' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
                'background_image' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:5120',
                'music_file' => 'nullable|mimes:mp3,ogg,wav|max:10240',
                'server_rules' => 'nullable|array',
                'server_rules.*' => 'string|max:100',
                'tips' => 'nullable|array',
                'tips.*' => 'string|max:200',
                'community_links' => 'nullable|array',
                'custom_css' => 'nullable|string',
                'custom_js' => 'nullable|string',
            ]);

            if ($validator->fails()) {
                return redirect()->back()
                    ->withErrors($validator)
                    ->withInput()
                    ->with('error', 'Please fix the validation errors.');
            }
            
            // Handle file uploads
            if ($request->hasFile('logo')) {
                // Delete the old logo if it exists
                if ($settings->logo && Storage::disk('public')->exists($settings->logo)) {
                    Storage::disk('public')->delete($settings->logo);
                }
                
                $logoPath = $request->file('logo')->store('loading-screen', 'public');
                $settings->logo = $logoPath;
            }
            
            if ($request->hasFile('background_image')) {
                // Delete the old background if it exists
                if ($settings->background_image && Storage::disk('public')->exists($settings->background_image)) {
                    Storage::disk('public')->delete($settings->background_image);
                }
                
                $bgPath = $request->file('background_image')->store('loading-screen', 'public');
                $settings->background_image = $bgPath;
            }
            
            if ($request->hasFile('music_file')) {
                // Delete the old music file if it exists
                if ($settings->music_file && Storage::disk('public')->exists($settings->music_file)) {
                    Storage::disk('public')->delete($settings->music_file);
                }
                
                $musicPath = $request->file('music_file')->store('loading-screen', 'public');
                $settings->music_file = $musicPath;
            }
            
            // Update all other settings
            $settings->background_color = $request->background_color ?: '#1E1E1E';
            $settings->primary_color = $request->primary_color ?: '#4B8BFF';
            $settings->enable_music = $request->has('enable_music') ? 1 : 0;
            $settings->music_volume = (float) $request->music_volume;
            $settings->enable_tips = $request->has('enable_tips') ? 1 : 0;
            $settings->enable_server_info = $request->has('enable_server_info') ? 1 : 0;
            $settings->enable_loading_bar = $request->has('enable_loading_bar') ? 1 : 0;
            $settings->enable_player_info = $request->has('enable_player_info') ? 1 : 0;
            $settings->enable_map_info = $request->has('enable_map_info') ? 1 : 0;
            $settings->enable_community_links = $request->has('enable_community_links') ? 1 : 0;
            
            // Handle arrays - clean them up
            $settings->server_rules = $request->has('server_rules') 
                ? array_filter($request->server_rules, function($rule) { return !empty(trim($rule)); })
                : [];
            
            $settings->tips = $request->has('tips') 
                ? array_filter($request->tips, function($tip) { return !empty(trim($tip)); })
                : [];
            
            // Handle community links
            if ($request->has('community_links')) {
                $links = [];
                foreach ($request->community_links as $link) {
                    if (!empty($link['name']) && !empty($link['url'])) {
                        $links[] = [
                            'name' => $link['name'],
                            'url' => $link['url'],
                            'icon' => $link['icon'] ?? 'fas fa-globe'
                        ];
                    }
                }
                $settings->community_links = $links;
            } else {
                $settings->community_links = [];
            }
            
            // Handle custom code
            $settings->custom_css = $request->custom_css;
            $settings->custom_js = $request->custom_js;
            
            $settings->save();
            
            return redirect()->route('admin.loading-screen.index')
                ->with('success', 'Loading screen settings updated successfully.');
                
        } catch (\Exception $e) {
            \Log::error('Error updating loading screen settings: ' . $e->getMessage());
            
            return redirect()->back()
                ->withInput()
                ->with('error', 'An error occurred while saving the settings. Please try again.');
        }
    }

    /**
     * Preview the loading screen with current settings.
     *
     * @return \Illuminate\Http\Response
     */
    public function preview()
    {
        $settings = LoadingScreenSettings::getSettings();
        return view('loading', [
            'settings' => $settings,
            'steamId' => '76561198157318784',
            'map' => 'rp_downtown_v4c_v2',
            'preview' => true
        ]);
    }

    /**
     * Delete a file from the settings.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function deleteFile(Request $request)
    {
        try {
            $validator = Validator::make($request->all(), [
                'file_type' => 'required|in:logo,background_image,music_file',
            ]);

            if ($validator->fails()) {
                return response()->json(['error' => 'Invalid file type.'], 422);
            }

            $settings = LoadingScreenSettings::getSettings();
            $fileType = $request->file_type;

            if ($settings->$fileType && Storage::disk('public')->exists($settings->$fileType)) {
                Storage::disk('public')->delete($settings->$fileType);
                $settings->$fileType = null;
                $settings->save();
                
                return response()->json(['success' => true]);
            }

            return response()->json(['error' => 'File not found.'], 404);
        } catch (\Exception $e) {
            \Log::error('Error deleting file: ' . $e->getMessage());
            return response()->json(['error' => 'An error occurred while deleting the file.'], 500);
        }
    }

    /**
     * Reset settings to default values.
     *
     * @return \Illuminate\Http\Response
     */
    public function reset()
    {
        try {
            $settings = LoadingScreenSettings::getSettings();
            
            // Delete all uploaded files
            if ($settings->logo && Storage::disk('public')->exists($settings->logo)) {
                Storage::disk('public')->delete($settings->logo);
            }
            
            if ($settings->background_image && Storage::disk('public')->exists($settings->background_image)) {
                Storage::disk('public')->delete($settings->background_image);
            }
            
            if ($settings->music_file && Storage::disk('public')->exists($settings->music_file)) {
                Storage::disk('public')->delete($settings->music_file);
            }
            
            // Delete the settings record
            $settings->delete();
            
            return redirect()->route('admin.loading-screen.index')
                ->with('success', 'Loading screen settings have been reset to defaults.');
                
        } catch (\Exception $e) {
            \Log::error('Error resetting loading screen settings: ' . $e->getMessage());
            
            return redirect()->back()
                ->with('error', 'An error occurred while resetting the settings. Please try again.');
        }
    }
}