<?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 DiplomaRegistrationSettingsController extends Controller
{
    public function index(Request $request)
    {
        $name = 'diploma_registration';
        $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.diploma_registration', $data);
    }

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

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

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

            $values = json_encode($values);
            $values = str_replace('record', rand(1, 600), $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(),
                ]);
            }

            // 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', 'تم الحفظ بنجاح');
    }
}

