<?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 NewHomepageHeroController extends Controller
{
    public static $settingName = 'premium_home_hero';

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

    /** @var int */
    public static $maxTrustBoxes = 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);
            }
        }

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

        return view('admin.new_homepage.hero', [
            '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 = [
            'title' => isset($input['title']) ? (string) $input['title'] : '',
            'description' => isset($input['description']) ? (string) $input['description'] : '',
            'title_color' => isset($input['title_color']) ? trim((string) $input['title_color']) : '',
            'description_color' => isset($input['description_color']) ? trim((string) $input['description_color']) : '',
            'title_highlight_color' => isset($input['title_highlight_color']) ? trim((string) $input['title_highlight_color']) : '',
            'hero_badge_color' => isset($input['hero_badge_color']) ? trim((string) $input['hero_badge_color']) : '',
            'hero_image' => isset($input['hero_image']) ? trim((string) $input['hero_image']) : '',
            'hero_background' => isset($input['hero_background']) ? trim((string) $input['hero_background']) : '',
            'hero_buttons' => self::sanitizeHeroButtonsInput($input['hero_buttons'] ?? []),
            'trust_boxes' => self::sanitizeTrustBoxesInput($input['trust_boxes'] ?? []),
        ];

        $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 homepage hero 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/hero' . (count($redirectQs) ? '?' . http_build_query($redirectQs) : ''));
    }

    /**
     * @return array<string, mixed>
     */
    private static function prepareValuesForForm(array $values): array
    {
        if (!array_key_exists('hero_buttons', $values)) {
            $values['hero_buttons'] = self::migrateLegacyHeroButtons($values);
        } elseif (!is_array($values['hero_buttons'])) {
            $values['hero_buttons'] = [];
        } else {
            $values['hero_buttons'] = array_values($values['hero_buttons']);
        }

        if (!array_key_exists('trust_boxes', $values)) {
            $values['trust_boxes'] = self::migrateLegacyTrustBoxes($values);
        } elseif (!is_array($values['trust_boxes'])) {
            $values['trust_boxes'] = [];
        } else {
            $values['trust_boxes'] = array_values($values['trust_boxes']);
        }

        return $values;
    }

    /**
     * @return array<int, array{label:string,url:string,style:string,new_tab:bool}>
     */
    private static function defaultEmptyHeroButtonRows(): array
    {
        return [
            ['label' => '', 'url' => '', 'style' => 'primary', 'new_tab' => false],
            ['label' => '', 'url' => '', 'style' => 'secondary', 'new_tab' => false],
        ];
    }

    /**
     * @param array<string, mixed> $values
     *
     * @return array<int, array{label:string,url:string,style:string,new_tab:bool}>
     */
    private static function migrateLegacyHeroButtons(array $values): array
    {
        $rows = [];
        $pl = trim((string)($values['btn_primary_label'] ?? ''));
        $pu = trim((string)($values['btn_primary_url'] ?? ''));
        if ($pl !== '' || $pu !== '') {
            $rows[] = ['label' => $pl, 'url' => $pu, 'style' => 'primary', 'new_tab' => false];
        }
        $sl = trim((string)($values['btn_secondary_label'] ?? ''));
        $su = trim((string)($values['btn_secondary_url'] ?? ''));
        if ($sl !== '' || $su !== '') {
            $rows[] = ['label' => $sl, 'url' => $su, 'style' => 'secondary', 'new_tab' => false];
        }

        return count($rows) > 0 ? $rows : self::defaultEmptyHeroButtonRows();
    }

    /**
     * @param array<string, mixed> $values
     *
     * @return array<int, array{l1:string,l2:string,meta:string}>
     */
    private static function migrateLegacyTrustBoxes(array $values): array
    {
        $boxes = [];
        for ($t = 1; $t <= 3; $t++) {
            $l1 = trim((string)($values['trust_'.$t.'_l1'] ?? ''));
            $l2 = trim((string)($values['trust_'.$t.'_l2'] ?? ''));
            $meta = trim((string)($values['trust_'.$t.'_meta'] ?? ''));
            if ($l1 !== '' || $l2 !== '' || $meta !== '') {
                $boxes[] = ['l1' => $l1, 'l2' => $l2, 'meta' => $meta];
            }
        }

        if (count($boxes) === 0) {
            for ($t = 1; $t <= 3; $t++) {
                $boxes[] = ['l1' => '', 'l2' => '', 'meta' => ''];
            }
        }

        return $boxes;
    }

    /**
     * @param mixed $raw
     *
     * @return array<int, array{label:string,url:string,style:string,new_tab:bool}>
     */
    private static function sanitizeHeroButtonsInput($raw): array
    {
        if (!is_array($raw)) {
            return [];
        }

        $out = [];
        foreach ($raw as $row) {
            if (!is_array($row)) {
                continue;
            }
            if (count($out) >= self::$maxHeroButtons) {
                break;
            }
            $label = trim((string)($row['label'] ?? ''));
            $url = trim((string)($row['url'] ?? ''));
            if ($label === '' && $url === '') {
                continue;
            }
            if ($url === '') {
                continue;
            }
            if ($label === '') {
                $label = '—';
            }
            $style = (($row['style'] ?? '') === 'secondary') ? 'secondary' : 'primary';
            $newTab = !empty($row['new_tab']) && (string) $row['new_tab'] !== '0';

            $out[] = [
                'label' => $label,
                'url' => $url,
                'style' => $style,
                'new_tab' => $newTab,
            ];
        }

        return $out;
    }

    /**
     * @param mixed $raw
     *
     * @return array<int, array{l1:string,l2:string,meta:string}>
     */
    private static function sanitizeTrustBoxesInput($raw): array
    {
        if (!is_array($raw)) {
            return [];
        }

        $out = [];
        foreach ($raw as $row) {
            if (!is_array($row)) {
                continue;
            }
            if (count($out) >= self::$maxTrustBoxes) {
                break;
            }
            $l1 = trim((string)($row['l1'] ?? ''));
            $l2 = trim((string)($row['l2'] ?? ''));
            $meta = trim((string)($row['meta'] ?? ''));
            if ($l1 === '' && $l2 === '' && $meta === '') {
                continue;
            }
            $out[] = ['l1' => $l1, 'l2' => $l2, 'meta' => $meta];
        }

        return $out;
    }
}
