<?php

namespace App\Http\Controllers\Admin;

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

class NewHomepageDefinitionsController extends Controller
{
    public static $settingName = 'premium_home_definitions';

    /** @var int */
    public static $maxFeatureCards = 6;

    public function index(Request $request)
    {
        removeContentLocale();

        $this->authorize('admin_settings_personalization');

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

        $values = [];
        if (!empty($settings)) {
            $defaultLocal = getDefaultLocale();
            if (!empty(getGeneralSettings('content_translate'))) {
                $locale = mb_strtolower($request->get('locale', $defaultLocal));
            } else {
                $locale = mb_strtolower(getDefaultLocale());
            }

            storeContentLocale($locale, $settings->getTable(), $settings->id);

            if (!empty($settings->value)) {
                $decoded = json_decode($settings->value, true);
                $values = is_array($decoded) ? $decoded : [];
                $values['locale'] = mb_strtoupper($settings->locale ?? $locale);
            }
        }

        $hadStoredTranslation = !empty($settings) && !empty($settings->value);
        if (!$hadStoredTranslation) {
            $values = array_merge(self::defaultDefinitionsSnapshot(), $values);
        }

        $values = self::prepareValuesForForm($values);

        return view('admin.new_homepage.definitions', [
            'pageTitle' => 'الصفحة الرئيسية الجديدة — سيكشن التعريفات',
            'itemValue' => $values,
        ]);
    }

    public function update(Request $request)
    {
        $this->authorize('admin_settings_personalization');

        if (!empty(getGeneralSettings('content_translate'))) {
            $locale = mb_strtolower($request->get('locale', getDefaultLocale()));
        } else {
            $locale = mb_strtolower(getDefaultLocale());
        }

        $input = $request->input('value', []);

        $values = [
            'accent_color' => isset($input['accent_color']) ? trim((string) $input['accent_color']) : '',
            'spotlight_eyebrow' => isset($input['spotlight_eyebrow']) ? (string) $input['spotlight_eyebrow'] : '',
            'spotlight_title' => isset($input['spotlight_title']) ? (string) $input['spotlight_title'] : '',
            'spotlight_cta_label' => isset($input['spotlight_cta_label']) ? (string) $input['spotlight_cta_label'] : '',
            'spotlight_cta_url' => isset($input['spotlight_cta_url']) ? trim((string) $input['spotlight_cta_url']) : '',
            'spotlight_image' => isset($input['spotlight_image']) ? trim((string) $input['spotlight_image']) : '',
            'spotlight_veil' => isset($input['spotlight_veil']) ? trim((string) $input['spotlight_veil']) : '',
            'feature_cards' => self::sanitizeFeatureCards($input['feature_cards'] ?? []),
        ];

        $settingId = DB::transaction(function () {
            $now = time();
            $row = DB::table('settings')->where('name', self::$settingName)->first();
            if ($row) {
                DB::table('settings')->where('id', $row->id)->update([
                    'page' => 'personalization',
                    'updated_at' => $now,
                ]);

                return (int) $row->id;
            }

            return (int) DB::table('settings')->insertGetId([
                'name' => self::$settingName,
                'page' => 'personalization',
                'updated_at' => $now,
            ]);
        });

        if ($settingId < 1) {
            abort(500, 'Could not save definitions section setting row.');
        }

        SettingTranslation::updateOrCreate(
            [
                'setting_id' => $settingId,
                'locale' => $locale,
            ],
            [
                'value' => json_encode($values, JSON_UNESCAPED_UNICODE),
            ]
        );

        cache()->forget('settings.' . self::$settingName);

        $redirectQs = [];
        if (!empty(getGeneralSettings('content_translate')) && $request->filled('locale')) {
            $redirectQs['locale'] = $request->get('locale');
        }

        return redirect()->to('/admin/new-homepage/definitions' . (count($redirectQs) ? '?' . http_build_query($redirectQs) : ''));
    }

    /**
     * @param array<string, mixed> $values
     *
     * @return array<string, mixed>
     */
    private static function prepareValuesForForm(array $values): array
    {
        $defaults = self::defaultFeatureCardsFromTranslations();
        if (empty($values['feature_cards']) || !is_array($values['feature_cards'])) {
            $values['feature_cards'] = $defaults;
        } else {
            $values['feature_cards'] = array_values($values['feature_cards']);
        }

        return $values;
    }

    /**
     * @return array<string, string>
     */
    private static function defaultDefinitionsSnapshot(): array
    {
        return [
            'accent_color' => '#5786c7',
            'spotlight_eyebrow' => trans('home.premium_features_eyebrow'),
            'spotlight_title' => trans('home.premium_spotlight_title'),
            'spotlight_cta_label' => trans('home.premium_spotlight_cta'),
            'spotlight_cta_url' => 'classes',
            'spotlight_image' => '',
            'spotlight_veil' => '',
        ];
    }

    /**
     * @return array<int, array{icon:string, icon_tone:string, title:string, description:string}>
     */
    private static function defaultFeatureCardsFromTranslations(): array
    {
        return [
            ['icon' => 'fas fa-book', 'icon_tone' => 'blue', 'title' => trans('home.premium_feature_course'), 'description' => trans('home.premium_feature_course_hint')],
            ['icon' => 'fas fa-star', 'icon_tone' => 'amber', 'title' => trans('home.premium_feature_materials'), 'description' => trans('home.premium_feature_materials_hint')],
            ['icon' => 'fas fa-chalkboard-teacher', 'icon_tone' => 'mint', 'title' => trans('home.premium_feature_schools'), 'description' => trans('home.premium_feature_schools_hint')],
            ['icon' => 'fas fa-users', 'icon_tone' => 'rose', 'title' => trans('home.premium_feature_parents'), 'description' => trans('home.premium_feature_parents_hint')],
        ];
    }

    /**
     * @param mixed $raw
     *
     * @return array<int, array{icon:string, icon_tone:string, title:string, description:string}>
     */
    private static function sanitizeFeatureCards($raw): array
    {
        if (!is_array($raw)) {
            return [];
        }

        $tones = ['blue', 'amber', 'mint', 'rose'];
        $out = [];
        foreach ($raw as $row) {
            if (!is_array($row)) {
                continue;
            }
            if (count($out) >= self::$maxFeatureCards) {
                break;
            }
            $title = trim((string) ($row['title'] ?? ''));
            $description = trim((string) ($row['description'] ?? ''));
            if ($title === '' && $description === '') {
                continue;
            }
            $tone = mb_strtolower(trim((string) ($row['icon_tone'] ?? 'blue')));
            if (!in_array($tone, $tones, true)) {
                $tone = 'blue';
            }
            $icon = trim((string) ($row['icon'] ?? ''));
            if ($icon === '') {
                $icon = 'fas fa-circle';
            }

            $out[] = [
                'icon' => $icon,
                'icon_tone' => $tone,
                'title' => $title,
                'description' => $description,
            ];
        }

        return $out;
    }
}
