<?php
namespace App\Models;

class SystemModel extends BaseModel
{
    private static $schemaEnsured = false;

    public function get(): array
    {
        $this->ensureSchema();

        $stmt = $this->db->query('SELECT * FROM system_settings WHERE id = 1');
        $row = $stmt->fetch();
        if (!$row) {
            return [
                'id' => 1,
                'mod_name' => '',
                'mod_status' => 'on',
                'notice_text' => '',
                'notice_status' => '',
                'maintenance_reason' => '',
                'allow_self_unbind' => 0,
            ];
        }
        if (!isset($row['allow_self_unbind'])) {
            $row['allow_self_unbind'] = 0;
        }
        if ((string)($row['mod_name'] ?? '') === 'Default Mod') {
            $row['mod_name'] = '';
        }
        if ((string)($row['notice_status'] ?? '') === 'Safe') {
            $row['notice_status'] = '';
        }
        if ((string)($row['maintenance_reason'] ?? '') === 'Maintenance') {
            $row['maintenance_reason'] = '';
        }
        return $row;
    }

    public function update(array $data): bool
    {
        $this->ensureSchema();

        $stmt = $this->db->prepare('UPDATE system_settings SET mod_name = ?, mod_status = ?, notice_text = ?, notice_status = ?, maintenance_reason = ?, allow_self_unbind = ?, updated_at = NOW() WHERE id = 1');
        return $stmt->execute([
            $data['mod_name'],
            $data['mod_status'],
            $data['notice_text'],
            $data['notice_status'],
            $data['maintenance_reason'],
            !empty($data['allow_self_unbind']) ? 1 : 0,
        ]);
    }

    private function ensureSchema(): void
    {
        if (self::$schemaEnsured) {
            return;
        }

        try {
            $this->db->exec("ALTER TABLE system_settings ADD COLUMN allow_self_unbind TINYINT(1) NOT NULL DEFAULT 0 AFTER maintenance_reason");
        } catch (\Throwable $e) {
        }

        self::$schemaEnsured = true;
    }
}
