<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\HeaderSetting;
use App\Models\ButtonSetting;
use App\Models\Language;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;

class HeaderSettingsController extends Controller
{
    /**
     * Display header settings form.
     */
    public function index(Request $request)
    {
        $languageCode = $request->get('lang', 'fa');
        $languages = Language::active()->get();
        
        // Get header settings
        $headerSettings = HeaderSetting::getAllForLanguage($languageCode);
        
        // Get button settings
        $buttonSettings = ButtonSetting::forLanguage($languageCode)->orderBy('sort_order')->get();

        return view('admin.header-settings.index', compact('headerSettings', 'buttonSettings', 'languages', 'languageCode'));
    }

    /**
     * Update header settings.
     */
    public function updateHeaderSettings(Request $request)
    {
        $validated = $request->validate([
            'language_code' => 'required|exists:languages,code',
            'settings' => 'required|array',
            'settings.show_search_box' => 'boolean',
            'settings.search_placeholder' => 'nullable|string|max:100',
            'settings.show_language_switcher' => 'boolean',
            'settings.show_user_menu' => 'boolean',
            'settings.header_style' => 'required|in:default,modern,minimal',
            'settings.sticky_header' => 'boolean',
            'settings.show_breadcrumb' => 'boolean',
        ]);

        $languageCode = $validated['language_code'];

        // Handle checkbox values (they don't get sent if unchecked)
        $checkboxSettings = ['show_search_box', 'show_language_switcher', 'show_user_menu', 'sticky_header', 'show_breadcrumb'];

        foreach ($checkboxSettings as $checkboxKey) {
            $validated['settings'][$checkboxKey] = isset($validated['settings'][$checkboxKey]) ? '1' : '0';
        }

        foreach ($validated['settings'] as $key => $value) {
            HeaderSetting::setValue($key, $value, $languageCode);
        }

        // Clear cache
        Cache::forget('header_settings_' . $languageCode);

        return redirect()->route('admin.header-settings.index', ['lang' => $languageCode])
            ->with('success', 'تنظیمات هدر با موفقیت به‌روزرسانی شد.');
    }

    /**
     * Update button settings.
     */
    public function updateButtonSettings(Request $request)
    {
        $validated = $request->validate([
            'language_code' => 'required|exists:languages,code',
            'buttons' => 'required|array',
            'buttons.*.button_key' => 'required|string|max:50',
            'buttons.*.button_text' => 'required|string|max:100',
            'buttons.*.button_url' => 'nullable|string|max:255',
            'buttons.*.button_icon' => 'nullable|string|max:50',
            'buttons.*.button_class' => 'nullable|string|max:100',
            'buttons.*.is_visible' => 'boolean',
            'buttons.*.show_for_guests' => 'boolean',
            'buttons.*.show_for_users' => 'boolean',
            'buttons.*.sort_order' => 'required|integer|min:0',
        ]);

        $languageCode = $validated['language_code'];

        foreach ($validated['buttons'] as $index => $buttonData) {
            // Handle checkbox values for buttons - convert to proper boolean values
            $buttonData['is_visible'] = isset($buttonData['is_visible']) && $buttonData['is_visible'] == '1' ? 1 : 0;
            $buttonData['show_for_guests'] = isset($buttonData['show_for_guests']) && $buttonData['show_for_guests'] == '1' ? 1 : 0;
            $buttonData['show_for_users'] = isset($buttonData['show_for_users']) && $buttonData['show_for_users'] == '1' ? 1 : 0;

            ButtonSetting::updateButton(
                $buttonData['button_key'],
                array_merge($buttonData, ['language_code' => $languageCode]),
                $languageCode
            );
        }

        // Clear cache
        Cache::forget('button_settings_' . $languageCode);

        return redirect()->route('admin.header-settings.index', ['lang' => $languageCode])
            ->with('success', 'تنظیمات دکمه‌ها با موفقیت به‌روزرسانی شد.');
    }

    /**
     * Add new button.
     */
    public function addButton(Request $request)
    {
        $validated = $request->validate([
            'button_key' => 'required|string|max:50|unique:button_settings,button_key',
            'button_text' => 'required|string|max:100',
            'button_url' => 'nullable|string|max:255',
            'button_icon' => 'nullable|string|max:50',
            'button_class' => 'nullable|string|max:100',
            'is_visible' => 'boolean',
            'show_for_guests' => 'boolean',
            'show_for_users' => 'boolean',
            'sort_order' => 'required|integer|min:0',
            'language_code' => 'required|exists:languages,code',
        ]);

        ButtonSetting::create($validated);

        // Clear cache
        Cache::forget('button_settings_' . $validated['language_code']);

        return redirect()->route('admin.header-settings.index', ['lang' => $validated['language_code']])
            ->with('success', 'دکمه جدید با موفقیت اضافه شد.');
    }

    /**
     * Delete button.
     */
    public function deleteButton(ButtonSetting $button)
    {
        $languageCode = $button->language_code;
        $button->delete();

        // Clear cache
        Cache::forget('button_settings_' . $languageCode);

        return redirect()->route('admin.header-settings.index', ['lang' => $languageCode])
            ->with('success', 'دکمه با موفقیت حذف شد.');
    }

    /**
     * Toggle button visibility via AJAX.
     */
    public function toggleButtonVisibility(ButtonSetting $button)
    {
        $button->update(['is_visible' => !$button->is_visible]);

        // Clear cache
        Cache::forget('button_settings_' . $button->language_code);

        return response()->json([
            'success' => true,
            'is_visible' => $button->is_visible,
            'message' => $button->is_visible ? 'دکمه نمایش داده می‌شود.' : 'دکمه مخفی شد.'
        ]);
    }

    /**
     * Reset to default settings.
     */
    public function resetToDefault(Request $request)
    {
        $languageCode = $request->get('lang', 'fa');

        // Reset header settings
        $defaultHeaderSettings = [
            'show_search_box' => '1',
            'search_placeholder' => 'جستجو...',
            'show_language_switcher' => '1',
            'show_user_menu' => '1',
            'header_style' => 'default',
            'sticky_header' => '1',
            'show_breadcrumb' => '1',
        ];

        foreach ($defaultHeaderSettings as $key => $value) {
            HeaderSetting::setValue($key, $value, $languageCode);
        }

        // Reset button settings
        ButtonSetting::forLanguage($languageCode)->delete();
        
        $defaultButtons = [
            ['button_key' => 'login', 'button_text' => 'ورود', 'button_url' => '/login', 'button_icon' => 'fas fa-sign-in-alt', 'show_for_guests' => 1, 'show_for_users' => 0, 'sort_order' => 1],
            ['button_key' => 'register', 'button_text' => 'ثبت نام', 'button_url' => '/register', 'button_icon' => 'fas fa-user-plus', 'show_for_guests' => 1, 'show_for_users' => 0, 'sort_order' => 2],
            ['button_key' => 'profile', 'button_text' => 'پروفایل', 'button_url' => '/profile', 'button_icon' => 'fas fa-user', 'show_for_guests' => 0, 'show_for_users' => 1, 'sort_order' => 1],
            ['button_key' => 'logout', 'button_text' => 'خروج', 'button_url' => '/logout', 'button_icon' => 'fas fa-sign-out-alt', 'show_for_guests' => 0, 'show_for_users' => 1, 'sort_order' => 2],
            ['button_key' => 'add_location', 'button_text' => 'ثبت مکان جدید', 'button_url' => '/user/locations/create', 'button_icon' => 'fas fa-plus-circle', 'show_for_guests' => 1, 'show_for_users' => 1, 'sort_order' => 3],
        ];

        foreach ($defaultButtons as $buttonData) {
            ButtonSetting::create(array_merge($buttonData, ['language_code' => $languageCode]));
        }

        // Clear cache
        Cache::forget('header_settings_' . $languageCode);
        Cache::forget('button_settings_' . $languageCode);

        return redirect()->route('admin.header-settings.index', ['lang' => $languageCode])
            ->with('success', 'تنظیمات به حالت پیش‌فرض بازگردانده شد.');
    }

    /**
     * Reset all settings to default (header settings + user menu buttons).
     */
    public function resetAllToDefault(Request $request)
    {
        $languageCode = $request->get('lang', 'fa');

        // Validate language code
        $supportedLanguages = ['fa', 'en', 'ar'];
        if (!in_array($languageCode, $supportedLanguages)) {
            $languageCode = 'fa';
        }

        // 1. Reset Header Settings
        HeaderSetting::forLanguage($languageCode)->delete();

        $defaultHeaderSettings = $this->getDefaultHeaderSettings($languageCode);

        foreach ($defaultHeaderSettings as $setting) {
            HeaderSetting::create(array_merge($setting, [
                'language_code' => $languageCode,
                'is_active' => 1
            ]));
        }

        // 2. Reset Button Settings (User Menu)
        ButtonSetting::forLanguage($languageCode)->delete();

        $defaultButtons = $this->getDefaultButtons($languageCode);

        foreach ($defaultButtons as $buttonData) {
            ButtonSetting::create(array_merge($buttonData, ['language_code' => $languageCode]));
        }

        // 3. Clear all caches
        Cache::forget('header_settings_' . $languageCode);
        Cache::forget('button_settings_' . $languageCode);
        Cache::flush(); // Clear all cache for safety

        return redirect()->route('admin.header-settings.index', ['lang' => $languageCode])
            ->with('success', '✅ تمام تنظیمات (هدر، منو و دکمه‌های کاربری) به حالت پیش‌فرض بازگردانده شدند.');
    }

    /**
     * Get default header settings based on language
     */
    private function getDefaultHeaderSettings($languageCode)
    {
        $settings = [
            'fa' => [
                'site_title' => 'اَلو ایران',
                'search_placeholder' => 'جستجو در مکان‌ها...',
                'login_text' => 'ورود',
                'logout_text' => 'خروج',
                'add_location_text' => 'ثبت مکان جدید',
            ],
            'en' => [
                'site_title' => 'Alo Iran',
                'search_placeholder' => 'Search locations...',
                'login_text' => 'Login',
                'logout_text' => 'Logout',
                'add_location_text' => 'Add New Location',
            ],
            'ar' => [
                'site_title' => 'ألو إيران',
                'search_placeholder' => 'البحث في المواقع...',
                'login_text' => 'تسجيل الدخول',
                'logout_text' => 'تسجيل الخروج',
                'add_location_text' => 'إضافة موقع جديد',
            ],
        ];

        $langSettings = $settings[$languageCode] ?? $settings['fa'];

        return [
            ['setting_key' => 'site_logo', 'setting_value' => '/images/logo.png'],
            ['setting_key' => 'site_title', 'setting_value' => $langSettings['site_title']],
            ['setting_key' => 'show_search_box', 'setting_value' => '1'],
            ['setting_key' => 'search_placeholder', 'setting_value' => $langSettings['search_placeholder']],
            ['setting_key' => 'show_language_switcher', 'setting_value' => '1'],
            ['setting_key' => 'show_user_menu', 'setting_value' => '1'],
            ['setting_key' => 'header_style', 'setting_value' => 'default'],
            ['setting_key' => 'sticky_header', 'setting_value' => '1'],
            ['setting_key' => 'show_breadcrumb', 'setting_value' => '1'],
            ['setting_key' => 'login_text', 'setting_value' => $langSettings['login_text']],
            ['setting_key' => 'logout_text', 'setting_value' => $langSettings['logout_text']],
            ['setting_key' => 'add_location_text', 'setting_value' => $langSettings['add_location_text']],
            ['setting_key' => 'add_location_url', 'setting_value' => '/user/locations/create'],
            ['setting_key' => 'show_add_location_button', 'setting_value' => '1'],
        ];
    }

    /**
     * Get default button settings based on language
     */
    private function getDefaultButtons($languageCode)
    {
        $buttons = [
            'fa' => [
                'login' => 'ورود',
                'register' => 'ثبت نام',
                'dashboard' => 'داشبورد',
                'profile' => 'پروفایل کاربری',
                'my_locations' => 'مکان‌های من',
                'favorites' => 'علاقه‌مندی‌ها',
                'settings' => 'تنظیمات',
                'logout' => 'خروج',
                'add_location' => 'ثبت مکان جدید',
            ],
            'en' => [
                'login' => 'Login',
                'register' => 'Register',
                'dashboard' => 'Dashboard',
                'profile' => 'User Profile',
                'my_locations' => 'My Locations',
                'favorites' => 'Favorites',
                'settings' => 'Settings',
                'logout' => 'Logout',
                'add_location' => 'Add New Location',
            ],
            'ar' => [
                'login' => 'تسجيل الدخول',
                'register' => 'إنشاء حساب',
                'dashboard' => 'لوحة التحكم',
                'profile' => 'الملف الشخصي',
                'my_locations' => 'مواقعي',
                'favorites' => 'المفضلة',
                'settings' => 'الإعدادات',
                'logout' => 'تسجيل الخروج',
                'add_location' => 'إضافة موقع جديد',
            ],
        ];

        $langButtons = $buttons[$languageCode] ?? $buttons['fa'];

        return [
            // Guest buttons
            ['button_key' => 'login', 'button_text' => $langButtons['login'], 'button_url' => '/login', 'button_icon' => 'fas fa-sign-in-alt', 'button_class' => 'btn-auth', 'is_visible' => 1, 'show_for_guests' => 1, 'show_for_users' => 0, 'sort_order' => 1],
            ['button_key' => 'register', 'button_text' => $langButtons['register'], 'button_url' => '/register', 'button_icon' => 'fas fa-user-plus', 'button_class' => 'btn-auth', 'is_visible' => 1, 'show_for_guests' => 1, 'show_for_users' => 0, 'sort_order' => 2],

            // User buttons
            ['button_key' => 'dashboard', 'button_text' => $langButtons['dashboard'], 'button_url' => '/user/dashboard', 'button_icon' => 'fas fa-tachometer-alt', 'button_class' => 'dropdown-item', 'is_visible' => 1, 'show_for_guests' => 0, 'show_for_users' => 1, 'sort_order' => 1],
            ['button_key' => 'profile', 'button_text' => $langButtons['profile'], 'button_url' => '/user/profile', 'button_icon' => 'fas fa-user-edit', 'button_class' => 'dropdown-item', 'is_visible' => 1, 'show_for_guests' => 0, 'show_for_users' => 1, 'sort_order' => 2],
            ['button_key' => 'my_locations', 'button_text' => $langButtons['my_locations'], 'button_url' => '/user/locations', 'button_icon' => 'fas fa-map-marker-alt', 'button_class' => 'dropdown-item', 'is_visible' => 1, 'show_for_guests' => 0, 'show_for_users' => 1, 'sort_order' => 3],
            ['button_key' => 'favorites', 'button_text' => $langButtons['favorites'], 'button_url' => '/user/favorites', 'button_icon' => 'fas fa-heart', 'button_class' => 'dropdown-item', 'is_visible' => 1, 'show_for_guests' => 0, 'show_for_users' => 1, 'sort_order' => 4],
            ['button_key' => 'settings', 'button_text' => $langButtons['settings'], 'button_url' => '/user/settings', 'button_icon' => 'fas fa-cog', 'button_class' => 'dropdown-item', 'is_visible' => 1, 'show_for_guests' => 0, 'show_for_users' => 1, 'sort_order' => 5],
            ['button_key' => 'logout', 'button_text' => $langButtons['logout'], 'button_url' => '/user/logout', 'button_icon' => 'fas fa-sign-out-alt', 'button_class' => 'dropdown-item', 'is_visible' => 1, 'show_for_guests' => 0, 'show_for_users' => 1, 'sort_order' => 6],

            // Shared buttons
            ['button_key' => 'add_location', 'button_text' => $langButtons['add_location'], 'button_url' => '/user/locations/create', 'button_icon' => 'fas fa-plus-circle', 'button_class' => 'btn-add-place', 'is_visible' => 1, 'show_for_guests' => 1, 'show_for_users' => 1, 'sort_order' => 10],
        ];
    }
}
