<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Cache;

class LandingSetting extends Model
{
    protected $fillable = [
        'section',
        'key',
        'value',
        'is_published',
    ];

    protected $casts = [
        'is_published' => 'boolean',
    ];

    /**
     * Get a landing setting value.
     */
    public static function getValue(string $section, string $key, mixed $default = null): mixed
    {
        $cacheKey = "landing_setting_{$section}_{$key}";
        
        return Cache::remember($cacheKey, 3600, function () use ($section, $key, $default) {
            $setting = self::where('section', $section)
                ->where('key', $key)
                ->where('is_published', true)
                ->first();

            if (!$setting) {
                return $default;
            }

            // Try to decode JSON
            $decoded = json_decode($setting->value, true);
            return json_last_error() === JSON_ERROR_NONE ? $decoded : $setting->value;
        });
    }

    /**
     * Set a landing setting value.
     */
    public static function setValue(string $section, string $key, mixed $value, bool $published = true): void
    {
        $encodedValue = is_array($value) || is_object($value) ? json_encode($value) : $value;

        self::updateOrCreate(
            ['section' => $section, 'key' => $key],
            ['value' => $encodedValue, 'is_published' => $published]
        );

        // Clear cache
        Cache::forget("landing_setting_{$section}_{$key}");
        Cache::forget("landing_all_settings");
    }

    /**
     * Get all settings for a section.
     */
    public static function getSection(string $section): array
    {
        return self::where('section', $section)
            ->where('is_published', true)
            ->pluck('value', 'key')
            ->map(function ($value) {
                $decoded = json_decode($value, true);
                return json_last_error() === JSON_ERROR_NONE ? $decoded : $value;
            })
            ->toArray();
    }

    /**
     * Get all published landing settings.
     */
    public static function getAllSettings(): array
    {
        return Cache::remember('landing_all_settings', 3600, function () {
            $settings = [];
            $records = self::where('is_published', true)->get();

            foreach ($records as $record) {
                if (!isset($settings[$record->section])) {
                    $settings[$record->section] = [];
                }
                
                $decoded = json_decode($record->value, true);
                $settings[$record->section][$record->key] = 
                    json_last_error() === JSON_ERROR_NONE ? $decoded : $record->value;
            }

            return $settings;
        });
    }

    /**
     * Clear all landing caches.
     */
    public static function clearCache(): void
    {
        Cache::forget('landing_all_settings');
        
        // Clear individual setting caches
        $settings = self::all();
        foreach ($settings as $setting) {
            Cache::forget("landing_setting_{$setting->section}_{$setting->key}");
        }
    }
}
