<?php

namespace App\Http\Controllers;

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

class AdminSettingsController extends Controller
{
    public function index()
    {
        $settings = [
            'patient_registration_enabled' => Setting::get('patient_registration_enabled', false),
        ];

        // Get carousel images
        $carouselImages = $this->getCarouselImages();

        return view('admin.settings', compact('settings', 'carouselImages'));
    }

    public function update(Request $request)
    {
        $validated = $request->validate([
            'patient_registration_enabled' => 'nullable|boolean',
        ]);

        Setting::set('patient_registration_enabled', $validated['patient_registration_enabled'] ?? false, 'boolean');

        return back()->with('success', 'Settings updated successfully.');
    }

    public function uploadCarouselImage(Request $request)
    {
        $request->validate([
            'carousel_image' => 'required|image|mimes:jpeg,jpg,png,gif|max:5120', // 5MB max
        ]);

        $path = $request->file('carousel_image')->store('carousel', 'public');
        
        // Get current carousel images
        $carouselImages = $this->getCarouselImages();
        $carouselImages[] = $path;
        
        // Save updated list
        Setting::set('carousel_images', json_encode($carouselImages), 'string');

        return back()->with('success', 'Carousel image uploaded successfully.');
    }

    public function deleteCarouselImage(Request $request, $index)
    {
        $carouselImages = $this->getCarouselImages();
        
        if (isset($carouselImages[$index])) {
            // Delete the file
            Storage::disk('public')->delete($carouselImages[$index]);
            
            // Remove from array
            unset($carouselImages[$index]);
            $carouselImages = array_values($carouselImages); // Re-index array
            
            // Save updated list
            Setting::set('carousel_images', json_encode($carouselImages), 'string');
            
            return back()->with('success', 'Carousel image deleted successfully.');
        }

        return back()->with('error', 'Image not found.');
    }

    private function getCarouselImages()
    {
        $imagesJson = Setting::get('carousel_images', '[]');
        $images = json_decode($imagesJson, true);
        
        // If no images in settings, check for default banner files
        if (empty($images) || !is_array($images)) {
            $images = [];
            // Check if default banners exist
            if (file_exists(public_path('banner 1.jpeg'))) {
                $images[] = 'banner 1.jpeg';
            }
            if (file_exists(public_path('banner 2.jpeg'))) {
                $images[] = 'banner 2.jpeg';
            }
        }
        
        return $images;
    }
}

