<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Models\Translation\SettingTranslation;
use Illuminate\Http\Request;

class SuccessPartnersSettingsController extends Controller
{
    public function index(Request $request)
    {
        $name = 'success_partners';
        $this->authorize('admin_additional_pages');

        $value = [];

        $settings = Setting::where('name', $name)->first();

        $defaultLocale = getDefaultLocale();
        $locale = $request->get('locale', $defaultLocale);

        if (!empty($settings)) {
            storeContentLocale($locale, $settings->getTable(), $settings->id);

            if (!empty($settings->value)) {
                $value = json_decode($settings->value, true);
            }
            
            \Log::info('Loading Success Partners Settings:', [
                'setting_id' => $settings->id,
                'raw_value' => $settings->value,
                'decoded_value' => $value,
                'institutions_count' => !empty($value['institutions']) ? count($value['institutions']) : 0
            ]);
        }

        $data = [
            'pageTitle' => 'إعدادات صفحة شركاء النجاح',
            'value' => $value,
            'selectedLocal' => $locale,
        ];

        return view('admin.additional_pages.success_partners', $data);
    }

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

        $name = 'success_partners';
        $values = $request->get('value', null);
        $locale = $request->get('locale', getDefaultLocale());

        // Debug logging
        \Log::info('=== Success Partners Save Debug ===');
        \Log::info('Raw request data:', $request->all());
        \Log::info('Values before processing:', ['values' => $values]);

        $originalInstitutionsCount = 0;
        $filteredInstitutionsCount = 0;

        if (!empty($values)) {
            // Filter out empty institutions
            if (!empty($values['institutions']) && is_array($values['institutions'])) {
                \Log::info('Institutions before filter:', ['institutions' => $values['institutions']]);
                $originalInstitutionsCount = count($values['institutions']);
                
                $values['institutions'] = array_filter($values['institutions'], function ($institution) {
                    return !empty($institution['name']); // Keep only institutions with a name
                });
                // Re-index array to avoid gaps
                $values['institutions'] = array_values($values['institutions']);
                
                $filteredInstitutionsCount = count($values['institutions']);
                \Log::info('Institutions after filter:', ['institutions' => $values['institutions']]);
            }

            // Filter empty values
            $values = array_filter($values, function ($val) {
                if (is_array($val)) {
                    return count($val) > 0;
                } else {
                    return !empty($val);
                }
            });

            \Log::info('Values after filtering:', ['values' => $values]);

            $values = json_encode($values);
            $values = str_replace('record', rand(1, 600), $values);
            
            \Log::info('Final JSON to save:', ['json' => $values]);

            // Ensure setting exists first
            $setting = Setting::firstOrCreate(
                ['name' => $name],
                [
                    'page' => 'other',
                    'created_at' => time(),
                    'updated_at' => time(),
                ]
            );

            // Update if it already exists
            if ($setting->wasRecentlyCreated === false) {
                $setting->update([
                    'page' => 'other',
                    'updated_at' => time(),
                    'value' => $values, // keep base value in sync for read paths that don't load translations
                ]);
            } else {
                $setting->update([
                    'value' => $values,
                ]);
            }

            // Refresh to ensure we have the correct ID
            $setting->refresh();

            if ($setting->id) {
                SettingTranslation::updateOrCreate(
                    [
                        'setting_id' => $setting->id,
                        'locale' => mb_strtolower($locale)
                    ],
                    [
                        'value' => $values,
                    ]
                );

                cache()->forget('settings.' . $name);
                
                \Log::info('Setting saved successfully', ['setting_id' => $setting->id]);
                
                // Verify what was saved
                $saved = Setting::where('name', $name)->first();
                \Log::info('Verification - What is in database now:', ['saved_value' => $saved->value]);
            }
        }

        removeContentLocale();
        
        \Log::info('=== End Success Partners Save ===');

        // Add debug info to session for display
        $debugInfo = [
            'institutions_count' => isset($values) ? count(json_decode($values, true)['institutions'] ?? []) : 0,
            'raw_json_length' => isset($values) ? strlen($values) : 0,
        ];

        $message = 'تم الحفظ بنجاح';
        if ($originalInstitutionsCount > 0 && $filteredInstitutionsCount < $originalInstitutionsCount) {
            $message = 'تم الحذف بنجاح';
        }

        return back()
            ->with('msg', $message)
            ->with('debug_info', $debugInfo);
    }
}

