<?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 MontessoriMembershipSettingsController extends Controller
{
    public function index(Request $request)
    {
        $name = 'montessori_membership';
        $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);
            }
        }

        $data = [
            'pageTitle' => 'إعدادات صفحة عضوية المونتيسوري',
            'value' => $value,
            'selectedLocal' => $locale
        ];

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

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

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

        if (!empty($values)) {
            // Clean null bytes before encoding
            array_walk_recursive($values, function(&$value) {
                if (is_string($value)) {
                    $value = str_replace("\0", '', $value);
                    $value = trim($value);
                }
            });

            // Convert eligibility_items from text to array
            if (!empty($values['eligibility_items']) && is_string($values['eligibility_items'])) {
                $items = array_filter(array_map('trim', explode("\n", $values['eligibility_items'])));
                $values['eligibility_items'] = array_values($items);
            }

            // Filter out empty FAQs
            if (!empty($values['faqs']) && is_array($values['faqs'])) {
                $values['faqs'] = array_filter($values['faqs'], function ($faq) {
                    return !empty($faq['question']) && !empty($faq['answer']);
                });
                // Re-index array to avoid gaps
                $values['faqs'] = array_values($values['faqs']);
            }

            // Filter out empty benefits items
            if (!empty($values['benefits_items']) && is_array($values['benefits_items'])) {
                $values['benefits_items'] = array_filter($values['benefits_items'], function ($benefit) {
                    return !empty($benefit['title']);
                });
                // Re-index array to avoid gaps
                $values['benefits_items'] = array_values($values['benefits_items']);
            }

            // Process form fields options (convert text to array)
            if (!empty($values['form_fields']) && is_array($values['form_fields'])) {
                foreach ($values['form_fields'] as &$field) {
                    if (!empty($field['options']) && is_string($field['options'])) {
                        $options = array_filter(array_map('trim', explode("\n", $field['options'])));
                        $field['options'] = array_values($options);
                    }
                }
                unset($field);
                
                // Filter out empty form fields
                $values['form_fields'] = array_filter($values['form_fields'], function ($field) {
                    return !empty($field['name']) && !empty($field['label']);
                });
                // Re-index array to avoid gaps
                $values['form_fields'] = array_values($values['form_fields']);
            }

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

            $values = json_encode($values, JSON_UNESCAPED_UNICODE);
            $values = str_replace('record', rand(1, 600), $values);
            // Remove any null bytes from final JSON string (redundant but safe)
            $values = str_replace("\0", '', $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 {
                // If newly created, also set the value
                $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);
            }
        }

        removeContentLocale();

        return back()->with('msg', 'تم الحفظ بنجاح');
    }
}
