<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Setting;
use App\Models\Holiday;
use App\Models\TimeSlot;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Cache; // Add Cache facade

class SettingController extends Controller
{
    public function edit()
    {
        // For backwards compatibility - get settings
        $settingsData = Setting::all();
        $settings = [];
        
        // Convert settings to an easier-to-access format
        foreach ($settingsData as $setting) {
            $settings[$setting->key] = $setting->value;
        }
        
        // Get time slots for the new time slot management feature
        $timeSlots = TimeSlot::orderBy('display_order')->orderBy('time')->get();
        
        // Get holidays ordered by start_date if available, otherwise fallback to date column
        $holidays = Holiday::orderBy('start_date')->get();
        return view('admin.settings', compact('settings', 'holidays', 'timeSlots'));
    }

    public function update(Request $request)
    {

        // Handle password change if old_password is provided
        if ($request->filled('old_password')) {
            $request->validate([
                'old_password' => 'required',
                'new_password' => 'required|min:6|confirmed',
            ]);

            $admin = Auth::guard('admin')->user();
            
            if (!Hash::check($request->old_password, $admin->password)) {
                return redirect()
                    ->route('admin.settings')
                    ->withErrors(['old_password' => 'Password lama tidak sesuai']);
            }

            $admin->password = Hash::make($request->new_password);
            $admin->save();

            return redirect()
                ->route('admin.settings')
                ->with('success', 'Password berhasil diubah');
        }
        
        // Handle registration date range update if provided
        if ($request->filled('registration_start_date') || $request->filled('registration_end_date')) {
            // Log incoming request data for debugging
            \Log::info('Registration date range form data:', [
                'start_date' => $request->registration_start_date,
                'end_date' => $request->registration_end_date
            ]);
            
            $this->updateRegistrationDates($request);
            return redirect()
                ->route('admin.settings')
                ->with('success', 'Rentang tanggal registrasi berhasil diperbarui');
        }

        return redirect()
            ->route('admin.settings')
            ->with('success', 'Pengaturan berhasil diperbarui');
    }
    
    /**
     * Update registration date range settings
     */
    protected function updateRegistrationDates(Request $request)
    {
        // Validate date inputs
        $request->validate([
            'registration_start_date' => 'required|date',
            'registration_end_date' => 'required|date|after_or_equal:registration_start_date',
        ], [
            'registration_end_date.after_or_equal' => 'Tanggal akhir harus sama dengan atau setelah tanggal mulai'
        ]);
        
        // Logging untuk debug
        \Log::info('Updating registration dates', [
            'start_date' => $request->registration_start_date,
            'end_date' => $request->registration_end_date
        ]);
        
        // Gunakan Setting::where()->update untuk start date
        $startDateSetting = Setting::where('key', 'registration_start_date')->first();
        if ($startDateSetting) {
            $startDateSetting->value = $request->registration_start_date;
            $startDateSetting->save();
            \Log::info('Updated existing start date setting');
        } else {
            Setting::create([
                'key' => 'registration_start_date',
                'value' => $request->registration_start_date
            ]);
            \Log::info('Created new start date setting');
        }
        
        // Gunakan Setting::where()->update untuk end date
        $endDateSetting = Setting::where('key', 'registration_end_date')->first();
        if ($endDateSetting) {
            $endDateSetting->value = $request->registration_end_date;
            $endDateSetting->save();
            \Log::info('Updated existing end date setting');
        } else {
            Setting::create([
                'key' => 'registration_end_date',
                'value' => $request->registration_end_date
            ]);
            \Log::info('Created new end date setting');
        }
        
        // Clear all caches
        $this->clearAllCache();
        
        // Update cache version timestamp
        Cache::put('time_slot_version', now()->timestamp);
    }
    
    /**
     * Clear all date availability cache
     */
    protected function clearAllDateAvailabilityCache()
    {
        // Get all cache keys that start with date_availability_
        $keys = Cache::get('all_date_availability_cache_keys', []);
        
        // Clear each key
        foreach ($keys as $key) {
            Cache::forget($key);
        }
        
        // Reset the keys list
        Cache::put('all_date_availability_cache_keys', [], now()->addDays(1));
    }
    
    /**
     * Clear all application cache including routes, views, and general cache
     * Call this whenever making significant changes to settings
     */
    protected function clearAllCache()
    {
        \Log::info('Clearing all application cache');
        
        try {
            // Clear route cache
            \Artisan::call('route:clear');
            \Log::info('Route cache cleared successfully');
            
            // Clear view cache
            \Artisan::call('view:clear');
            \Log::info('View cache cleared successfully');
            
            // Clear application cache
            \Artisan::call('cache:clear');
            \Log::info('Application cache cleared successfully');
            
            // Clear date availability cache as well
            $this->clearAllDateAvailabilityCache();
            \Log::info('Date availability cache cleared successfully');
            
            return true;
        } catch (\Exception $e) {
            \Log::error('Error clearing caches: ' . $e->getMessage());
            return false;
        }
    }
    
    public function storeTimeSlot(Request $request)
    {
        // Log incoming request data for debugging
        \Log::info('TimeSlot Form Data:', $request->all());
        
        try {
            \Log::info('Validating timeslot data');
            $request->validate([
                'time' => ['required', 'string', 'regex:/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/'], // 24-hour time format validation
                'quota' => 'required|integer|min:0',
                'label' => 'required|string|max:50',
            ]);
            \Log::info('Validation passed');
            
            // Get the highest order number and add 1
            $maxOrder = TimeSlot::max('display_order') ?: 0;
            \Log::info('Max order found: ' . $maxOrder);
            
            $timeSlot = TimeSlot::create([
                'time' => $request->time,
                'quota' => $request->quota,
                'label' => $request->label,
                'is_active' => $request->has('is_active') ? 1 : 0,
                'display_order' => $maxOrder + 1,
             ]);
             \Log::info('TimeSlot created with ID: ' . ($timeSlot->id ?? 'unknown'));
             
             // Update cache version timestamp
             Cache::put('time_slot_version', now()->timestamp);
            
             // Clear all caches
             $this->clearAllCache();
 
             \Log::info('Redirecting with success message');
            return redirect()->route('admin.settings')->with('success', 'Slot waktu berhasil ditambahkan');
        } catch (\Exception $e) {
            \Log::error('Error creating timeslot: ' . $e->getMessage());
            \Log::error($e->getTraceAsString());
            return redirect()->route('admin.settings')->with('error', 'Terjadi kesalahan saat menambahkan slot waktu: ' . $e->getMessage());
        }
    }

    public function updateTimeSlot(Request $request, $id)
    {
        $request->validate([
            'time' => ['required', 'string', 'regex:/^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$/'], // 24-hour time format validation
            'quota' => 'required|integer|min:0',
            'label' => 'required|string|max:50',
        ]);

        $timeSlot = TimeSlot::findOrFail($id);
        $timeSlot->update([
            'time' => $request->time,
            'quota' => $request->quota,
            'label' => $request->label,
             'is_active' => $request->has('is_active') ? 1 : 0,
         ]);
 
         // Update cache version timestamp
         Cache::put('time_slot_version', now()->timestamp);
 
         // Clear all caches
         $this->clearAllCache();
 
         return redirect()->route('admin.settings')->with('success', 'Slot waktu berhasil diperbarui');
    }

    public function deleteTimeSlot($id)
    {
         $timeSlot = TimeSlot::findOrFail($id);
         $timeSlot->delete();
 
         // Update cache version timestamp
         Cache::put('time_slot_version', now()->timestamp);
 
         // Clear all caches
         $this->clearAllCache();
 
         return redirect()->route('admin.settings')->with('success', 'Slot waktu berhasil dihapus');
    }

    public function reorderTimeSlots(Request $request)
    {
        $request->validate([
            'ids' => 'required|array',
            'ids.*' => 'required|integer|exists:time_slots,id',
        ]);

        foreach ($request->ids as $order => $id) {
             TimeSlot::where('id', $id)->update(['display_order' => $order]);
         }
 
         // Update cache version timestamp
         Cache::put('time_slot_version', now()->timestamp);
 
         // Clear all caches
         $this->clearAllCache();
 
         return response()->json(['success' => true]);
    }
}
