<?php
namespace App\Modules\System\Models;

class UserSettingsModel extends \Core\Model {
    protected $moduleName = 'System'; // Put it under System
    protected $useSoftDeletes = false; // Upsert-only model, no delete operations

    public function getSettings($userId) {
        $settings = $this->query("SELECT * FROM user_settings WHERE user_id = ?", [$userId])->fetch();
        if (!$settings) {
            // Failsafe auto-create
            $this->query("INSERT IGNORE INTO user_settings (user_id) VALUES (?)", [$userId]);
            $settings = (object)[
                'theme' => 'light',
                'timezone' => 'Africa/Cairo',
                'currency' => 'EGP'
            ];
        }
        return $settings;
    }

    public function updateSettings($userId, $data) {
        return $this->query(
            "INSERT INTO user_settings (user_id, theme, timezone, currency, focus_mode, personality_mode) 
             VALUES (?, ?, ?, ?, ?, ?) 
             ON DUPLICATE KEY UPDATE 
             theme = VALUES(theme), 
             timezone = VALUES(timezone), 
             currency = VALUES(currency),
             focus_mode = VALUES(focus_mode),
             personality_mode = VALUES(personality_mode)",
            [
                $userId, 
                $data['theme'] ?? 'light', 
                $data['timezone'] ?? 'Africa/Cairo', 
                $data['currency'] ?? 'EGP',
                $data['focus_mode'] ?? 0,
                $data['personality_mode'] ?? 'strict'
            ]
        );
    }

    public function updateTheme($userId, $theme) {
        return $this->query(
            "INSERT INTO user_settings (user_id, theme) VALUES (?, ?) ON DUPLICATE KEY UPDATE theme = VALUES(theme)",
            [$userId, $theme]
        );
    }
}
