<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Setting;
use App\Models\Slider;
use App\Models\TrustBadge;
use App\Models\NavigationMenu;
use App\Models\Announcement;
use Illuminate\Support\Facades\Cache;

class SiteSettingsController extends Controller
{
    public function index()
    {
        $data = Cache::remember('site_settings_compiled', 3600, function () {
            // Flatten all settings into key-value pairs and decode JSON arrays/objects
            $settingsRaw = Setting::pluck('value', 'key')->toArray();
            $settings = [];
            foreach ($settingsRaw as $key => $value) {
                if (is_string($value) && (str_starts_with($value, '[') || str_starts_with($value, '{'))) {
                    $decoded = json_decode($value, true);
                    if (json_last_error() === JSON_ERROR_NONE) {
                        $settings[$key] = $decoded;
                        continue;
                    }
                }
                $settings[$key] = $value;
            }

            // Format reviewer images if present
            if (isset($settings['reviews_list']) && is_array($settings['reviews_list'])) {
                foreach ($settings['reviews_list'] as &$review) {
                    if (!empty($review['image'])) {
                        $review['image'] = \Illuminate\Support\Facades\Storage::url($review['image']);
                    }
                }
            }

            // Fetch sliders grouped by type
            $slidersList = Slider::where('is_active', true)
                ->orderBy('sort_order')
                ->get()
                ->map(function ($slider) {
                    if ($slider->image) {
                        $slider->image = \Illuminate\Support\Facades\Storage::url($slider->image);
                    }
                    return $slider;
                })
                ->toArray();
            $sliders = collect($slidersList)->groupBy('type');

            // Fetch active trust badges
            $trustBadges = TrustBadge::where('is_active', true)
                ->orderBy('sort_order')
                ->get()
                ->toArray();

            // Fetch navigation menus for all 4 positions
            $navQuery = function (string $position, bool $hierarchical = false) {
                $query = NavigationMenu::where('position', $position)
                    ->where('is_active', true)
                    ->orderBy('sort_order');

                if ($hierarchical) {
                    $query->whereNull('parent_id')
                        ->with(['children' => fn ($q) => $q->where('is_active', true)->orderBy('sort_order')]);
                }

                return $query->get()->toArray();
            };

            $headerMenus   = $navQuery('header', true);
            $mobileMenus   = $navQuery('mobile', true);
            $stickyBarMenus = $navQuery('sticky_bar');
            $footerMenus   = $navQuery('footer');
            $topBarMenus   = $navQuery('top_bar');
            $footerPoliciesMenus = $navQuery('footer_policies');
            $footerCustomerPolicyMenus = $navQuery('footer_customer_policy');

            // Fetch active announcements
            $announcements = Announcement::where('is_active', true)
                ->orderBy('created_at', 'desc')
                ->get()
                ->toArray();

            // Fetch visible categories
            $categories = \App\Models\Category::where('is_visible', true)
                ->orderBy('name')
                ->get()
                ->map(function ($category) {
                    $category->image_url = $category->getFirstMediaUrl('image', 'webp')
                        ?: ($category->getFirstMediaUrl('image') ?: null);
                    return $category;
                })
                ->toArray();

            return [
                'settings' => $settings,
                'sliders' => [
                    'hero'      => $sliders->get('hero', collect())->toArray(),
                    'hero_side' => $sliders->get('hero_side', collect())->toArray(),
                    'middle'    => $sliders->get('middle', collect())->toArray(),
                ],
                'trust_badges' => $trustBadges,
                'navigation' => [
                    'header'                 => $headerMenus,
                    'mobile'                 => $mobileMenus,
                    'sticky_bar'             => $stickyBarMenus,
                    'footer'                 => $footerMenus,
                    'top_bar'               => $topBarMenus,
                    'footer_policies'        => $footerPoliciesMenus,
                    'footer_customer_policy' => $footerCustomerPolicyMenus,
                ],
                'announcements' => $announcements,
                'categories' => $categories,
            ];
        });

        return response()->json([
            'success' => true,
            'data' => $data,
        ])->withHeaders([
            'Cache-Control' => 'no-store, no-cache, must-revalidate, max-age=0',
        ]);
    }
}
