<?php

namespace MtcPharmacy\Multisite\Classes;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Arr;

class MultisiteSite extends Model
{
    protected $table = 'multisite__sites';

    public function getConfig(): array
    {
        $config = [];

        require SITE_PATH.'/sites/sites.php';

        foreach ($sites as $temp_site_name => $temp_site_config) {
            if ($temp_site_config['site_id'] == $this->id) {
                break;
            }
        }

        if (! empty($temp_site_config['db_settings_overrides'])) {
            $config = Arr::get($temp_site_config, 'db_settings_overrides', []);
        }

        $config['SITE_URL'] = "https://{$temp_site_config['default_url']}";
        $config['THEME_PATH'] = "/sites/{$temp_site_name}";
        $config['SITE'] = $temp_site_name;

        return $config;
    }

    public function getSitemapFilePath()
    {
        $config = $this->getConfig();

        $theme_path = $config['THEME_PATH'] ?? '';

        return "{$theme_path}/sitemap.xml";
    }

    /**
     * Get either multisite config or default config
     *
     * @param $site
     * @return array
     */
    protected static array $configCache = [];

    public static function getSiteConfig($site)
    {
        if ($site instanceof self) {
            $siteId = $site->getKey();
            if ($siteId && isset(self::$configCache[$siteId])) {
                return self::$configCache[$siteId];
            }

            $config = $site->getConfig();
            if ($siteId) {
                self::$configCache[$siteId] = $config;
            }

            return $config;
        }

        if (is_numeric($site) && $site > 0) {
            $siteId = (int) $site;
            if (isset(self::$configCache[$siteId])) {
                return self::$configCache[$siteId];
            }

            $siteModel = self::query()->find($siteId);
            if ($siteModel) {
                return self::$configCache[$siteId] = $siteModel->getConfig();
            }
        }

        return [
            'THEME_PATH' => THEME_PATH,
            'SITE' => 'default',
            'SITE_NAME' => config('app.name'),
            'SITE_URL' => SITE_URL,
        ];
    }
}
