<?php

namespace App\Models;

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

class SystemSetting extends Model
{
    use HasFactory;

    protected $fillable = ['key', 'value', 'description'];

    // Konstanta untuk key setting
    const PERHITUNGAN_OPEN = 'perhitungan_open';
    
    /**
     * Cek apakah perhitungan/quiz terbuka
     */
    public static function isPerhitunganOpen()
    {
        // Gunakan cache untuk performa yang lebih baik
        return Cache::remember('perhitungan_open', 60, function () {
            $setting = self::where('key', self::PERHITUNGAN_OPEN)->first();
            return $setting ? (bool) $setting->value : false;
        });
    }

    /**
     * Update status perhitungan/quiz
     */
    public static function setPerhitunganOpen($status)
    {
        $setting = self::updateOrCreate(
            ['key' => self::PERHITUNGAN_OPEN],
            [
                'value' => $status ? '1' : '0',
                'description' => 'Status akses section perhitungan/quiz untuk user'
            ]
        );

        // Clear cache
        Cache::forget('perhitungan_open');

        return $setting;
    }

    /**
     * Toggle status perhitungan/quiz
     */
    public static function togglePerhitunganOpen()
    {
        $currentStatus = self::isPerhitunganOpen();
        $newStatus = !$currentStatus;
        
        self::setPerhitunganOpen($newStatus);
        
        return $newStatus;
    }
}
