<?php

declare(strict_types=1);

namespace common\models;

use yii\db\ActiveRecord;

/**
 * @property int    $id
 * @property string $content_key
 * @property string $content_value
 * @property string $label
 * @property string $section
 * @property int    $updated_at
 */
class SiteContent extends ActiveRecord
{
    /** In-memory cache so we don't hit the DB repeatedly per-request. */
    private static array $_cache = [];

    public static function tableName(): string
    {
        return '{{%site_content}}';
    }

    public function rules(): array
    {
        return [
            ['content_key',   'required'],
            ['content_key',   'string', 'max' => 100],
            ['content_value', 'string'],
            ['label',         'string', 'max' => 200],
            ['section',       'string', 'max' => 60],
        ];
    }

    public function attributeLabels(): array
    {
        return [
            'content_key'   => 'Key',
            'content_value' => 'Value',
            'label'         => 'Label',
            'section'       => 'Section',
        ];
    }

    public function beforeSave($insert): bool
    {
        $this->updated_at = time();
        return parent::beforeSave($insert);
    }

    /**
     * Get a content value by key, with an optional fallback default.
     * Results are cached in-memory for the duration of the request.
     */
    public static function getValue(string $key, string $default = ''): string
    {
        if (!array_key_exists($key, self::$_cache)) {
            $row = static::find()->where(['content_key' => $key])->one();
            self::$_cache[$key] = $row ? (string)$row->content_value : null;
        }
        return self::$_cache[$key] ?? $default;
    }

    /**
     * Load all content into the cache — call once per page load
     * to avoid N+1 queries.
     */
    public static function preload(): void
    {
        $rows = static::find()->all();
        foreach ($rows as $row) {
            self::$_cache[$row->content_key] = (string)$row->content_value;
        }
    }

    /**
     * Return all rows grouped by section for the CMS editor.
     */
    public static function getAllGrouped(): array
    {
        $rows = static::find()->orderBy(['section' => SORT_ASC, 'id' => SORT_ASC])->all();
        $grouped = [];
        foreach ($rows as $row) {
            $grouped[$row->section][] = $row;
        }
        return $grouped;
    }
}
