<?php

namespace App\Http\Controllers\Admin\Store;

use App\Http\Controllers\Controller;
use App\Models\Product;
use App\Models\ProductCategory;
use App\Models\Setting;
use App\Models\Translation\SettingTranslation;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;

class ToolsOfIlmonsteryController extends Controller
{
    public function index()
    {
        $this->authorize('admin_store_settings');

        removeContentLocale();

        // Clear cache first to ensure fresh data
        cache()->forget('settings.tools_of_ilmonstery_settings');
        
        $setting = Setting::where('page', 'general')
            ->where('name', 'tools_of_ilmonstery_settings')
            ->first();

        $settingValue = [];
        if (!empty($setting) && !empty($setting->value)) {
            $settingValue = is_string($setting->value) ? json_decode($setting->value, true) : $setting->value;
            if (!is_array($settingValue)) {
                $settingValue = [];
            }
        }

        // Get all products
        $allProducts = Product::where('status', Product::$active)
            ->orderBy('created_at', 'desc')
            ->get();

        // Get selected products
        $selectedProducts = [];
        if (!empty($settingValue['tools_of_ilmonstery_products']) && is_array($settingValue['tools_of_ilmonstery_products'])) {
            $selectedProducts = $settingValue['tools_of_ilmonstery_products'];
        }

        // Get categories
        $categories = ProductCategory::whereNull('parent_id')
            ->with([
                'subCategories' => function ($query) {
                    $query->orderBy('order', 'asc');
                },
            ])
            ->get();

        // Get selected category
        $selectedCategoryId = !empty($settingValue['tools_of_ilmonstery_category_id']) ? $settingValue['tools_of_ilmonstery_category_id'] : null;

        // Get products per page
        $perPage = !empty($settingValue['tools_of_ilmonstery_per_page']) ? (int)$settingValue['tools_of_ilmonstery_per_page'] : 24;

        // Get status
        $status = !empty($settingValue['tools_of_ilmonstery_status']) ? $settingValue['tools_of_ilmonstery_status'] : 0;

        $data = [
            'pageTitle' => 'إدارة أدوات المونتيسوري',
            'itemValue' => $settingValue,
            'allProducts' => $allProducts,
            'selectedProducts' => $selectedProducts,
            'categories' => $categories,
            'selectedCategoryId' => $selectedCategoryId,
            'perPage' => $perPage,
            'status' => $status,
        ];

        return view('admin.store.tools_of_ilmonstery.index', $data);
    }

    public function store(Request $request)
    {
        $this->authorize('admin_store_settings');

        Log::info('=== ToolsOfIlmonstery Store Method Started ===');
        Log::info('Request Method: ' . $request->method());
        Log::info('Request All Data: ', $request->all());
        
        $data = $request->all();
        $newValues = $data['value'] ?? [];
        
        Log::info('New Values from Request: ', $newValues);

        $validator = Validator::make($newValues, [
            'tools_of_ilmonstery_per_page' => 'nullable|integer|min:1|max:100',
        ]);

        if ($validator->fails()) {
            Log::error('Validation Failed: ', $validator->errors()->toArray());
            return back()->withErrors($validator)->withInput();
        }

        $settings = Setting::where('name', 'tools_of_ilmonstery_settings')->first();
        Log::info('Existing Settings: ', $settings ? ['exists' => true, 'value' => $settings->value] : ['exists' => false]);
        
        $values = [];

        if (!empty($settings) && !empty($settings->value)) {
            $values = json_decode($settings->value, true);
            if (!is_array($values)) {
                $values = [];
            }
            Log::info('Decoded Existing Values: ', $values);
        }

        // Handle status checkbox - always set it
        $statusValue = isset($newValues['tools_of_ilmonstery_status']) && $newValues['tools_of_ilmonstery_status'] == '1' ? 1 : 0;
        $values['tools_of_ilmonstery_status'] = $statusValue;
        Log::info('Status Value: ' . $statusValue);

        // Handle per page
        if (isset($newValues['tools_of_ilmonstery_per_page']) && $newValues['tools_of_ilmonstery_per_page'] !== '') {
            $values['tools_of_ilmonstery_per_page'] = (int)$newValues['tools_of_ilmonstery_per_page'];
            Log::info('Per Page Value: ' . $values['tools_of_ilmonstery_per_page']);
        } else {
            // Keep existing value or set default
            if (!isset($values['tools_of_ilmonstery_per_page'])) {
                $values['tools_of_ilmonstery_per_page'] = 24;
            }
            Log::info('Per Page Value (default/kept): ' . $values['tools_of_ilmonstery_per_page']);
        }

        // Handle category
        if (isset($newValues['tools_of_ilmonstery_category_id']) && $newValues['tools_of_ilmonstery_category_id'] !== '') {
            $values['tools_of_ilmonstery_category_id'] = (int)$newValues['tools_of_ilmonstery_category_id'];
            Log::info('Category ID Value: ' . $values['tools_of_ilmonstery_category_id']);
        } else {
            $values['tools_of_ilmonstery_category_id'] = null;
            Log::info('Category ID Value: null');
        }

        // Handle products array - always set it, even if empty
        if (isset($newValues['tools_of_ilmonstery_products']) && is_array($newValues['tools_of_ilmonstery_products'])) {
            Log::info('Products Array Received: ', $newValues['tools_of_ilmonstery_products']);
            // Filter out empty values and convert to integers
            $products = array_filter($newValues['tools_of_ilmonstery_products'], function($value) {
                return $value !== '' && $value !== null;
            });
            $values['tools_of_ilmonstery_products'] = array_values(array_map('intval', $products));
            Log::info('Products Array After Processing: ', $values['tools_of_ilmonstery_products']);
        } else {
            $values['tools_of_ilmonstery_products'] = [];
            Log::info('Products Array: empty (not set in request)');
        }

        Log::info('Final Values to Save: ', $values);
        
        $jsonValue = json_encode($values);
        Log::info('JSON Value to Save: ' . $jsonValue);

        try {
            $locale = Setting::$defaultSettingsLocale;
            
            // First, create or update the setting record
            $setting = Setting::updateOrCreate(
                ['name' => 'tools_of_ilmonstery_settings'],
                [
                    'page' => 'general',
                    'updated_at' => time(),
                ]
            );

            Log::info('Setting Record: ', [
                'id' => $setting->id,
                'name' => $setting->name,
                'page' => $setting->page
            ]);

            // Then, save the value in setting_translations table
            $translation = SettingTranslation::updateOrCreate(
                [
                    'setting_id' => $setting->id,
                    'locale' => mb_strtolower($locale)
                ],
                [
                    'value' => $jsonValue,
                ]
            );

            Log::info('Setting Translation Save Result: ', [
                'id' => $translation->id,
                'setting_id' => $translation->setting_id,
                'locale' => $translation->locale,
                'value' => $translation->value
            ]);

            // Clear cache - multiple ways to ensure it's cleared
            try {
                cache()->forget('settings.tools_of_ilmonstery_settings');
            } catch (\Exception $cacheException) {
                Log::warning('Cache clear warning: ' . $cacheException->getMessage());
            }

            // Force refresh the setting from database
            $savedSetting = Setting::where('name', 'tools_of_ilmonstery_settings')
                ->with('translations')
                ->first();
            
            Log::info('Verified Saved Setting: ', [
                'exists' => $savedSetting ? true : false,
                'id' => $savedSetting ? $savedSetting->id : null,
                'value' => $savedSetting ? $savedSetting->value : 'not found',
                'translation_exists' => $savedSetting && $savedSetting->translations ? true : false
            ]);

            // Double check the translation was saved
            $savedTranslation = SettingTranslation::where('setting_id', $setting->id)
                ->where('locale', mb_strtolower($locale))
                ->first();
            
            Log::info('Verified Saved Translation: ', [
                'exists' => $savedTranslation ? true : false,
                'value' => $savedTranslation ? $savedTranslation->value : 'not found'
            ]);

            if ($setting && $translation && $savedTranslation) {
                Log::info('=== ToolsOfIlmonstery Store Method Completed Successfully ===');
                return back()->with('msg', trans('admin/main.success_update'));
            } else {
                Log::error('=== ToolsOfIlmonstery Store Method Failed ===', [
                    'setting_exists' => $setting ? true : false,
                    'translation_exists' => $translation ? true : false,
                    'saved_translation_exists' => $savedTranslation ? true : false
                ]);
                return back()->with('error', 'حدث خطأ أثناء الحفظ - يرجى التحقق من الـ logs');
            }
        } catch (\Exception $e) {
            Log::error('=== ToolsOfIlmonstery Store Method Exception ===');
            Log::error('Exception Message: ' . $e->getMessage());
            Log::error('Exception Trace: ' . $e->getTraceAsString());
            return back()->with('error', 'حدث خطأ: ' . $e->getMessage());
        }
    }
}

