<?php
/**
 * SettingController - zarządzanie ustawieniami urządzeń
 */

require_once __DIR__ . '/BaseController.php';
require_once PANEL_PATH . '/classes/Setting.php';
require_once PANEL_PATH . '/classes/AuditLog.php';

class SettingController extends BaseController
{
    private Setting $settingModel;
    private AuditLog $auditLog;

    public function __construct()
    {
        parent::__construct();
        $this->settingModel = new Setting();
        $this->auditLog = new AuditLog();
    }

    /**
     * Loguj akcję do audit log
     */
    private function logSettingAction(string $action, array $data = []): void
    {
        $entityId = $data['definition_id'] ?? $data['preset_id'] ?? $data['device_id'] ?? $data['user_id'] ?? $data['reseller_id'] ?? 0;
        
        $this->auditLog->log(
            AuditLog::ENTITY_SETTINGS,
            (int)$entityId,
            $action,
            null,
            $data
        );
    }

    // ==================== DEFINICJE ====================

    /**
     * Lista definicji ustawień (tylko admin)
     */
    public function definitions(): void
    {
        if (!$this->auth->isAdmin()) { $this->redirect("dashboard", "danger", "Brak uprawnień."); return; }

        $group = get('group');
        $definitions = $this->settingModel->getDefinitions($group, false);
        $groups = $this->settingModel->getGroups();

        // Grupuj definicje
        $grouped = [];
        foreach ($definitions as $def) {
            $grouped[$def['group_name']][] = $def;
        }

        $this->render('settings/definitions.tpl', [
            'pageTitle' => 'Definicje ustawień',
            'definitions' => $definitions,
            'grouped' => $grouped,
            'groups' => $groups,
            'filterGroup' => $group,
            'groupLabels' => $this->getGroupLabels()
        ]);
    }

    /**
     * Formularz dodawania definicji
     */
    public function addDefinition(): void
    {
        if (!$this->auth->isAdmin()) { $this->redirect("dashboard", "danger", "Brak uprawnień."); return; }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!$this->verifyCsrf()) {
                return;
            }

            $data = $this->prepareDefinitionData();

            // Walidacja
            if (empty($data['key']) || empty($data['label']) || empty($data['type'])) {
                $this->redirect('settings/definitions', 'danger', 'Wypełnij wymagane pola.');
                return;
            }

            // Sprawdź unikalność klucza
            if ($this->settingModel->getDefinitionByKey($data['key'])) {
                $this->redirect('settings/definitions', 'danger', 'Klucz już istnieje.');
                return;
            }

            $id = $this->settingModel->createDefinition($data);

            if ($id) {
                $this->logSettingAction('setting_definition_create', [
                    'definition_id' => $id,
                    'key' => $data['key'],
                    'type' => $data['type']
                ]);
                $this->redirect('settings/definitions', 'success', 'Definicja została dodana.');
            } else {
                $this->redirect('settings/definitions', 'danger', 'Błąd podczas dodawania definicji.');
            }
            return;
        }

        $this->render('settings/definition_form.tpl', [
            'pageTitle' => 'Dodaj definicję',
            'definition' => null,
            'groupLabels' => $this->getGroupLabels(),
            'scopeLabels' => $this->getScopeLabels(),
            'typeLabels' => $this->getTypeLabels()
        ]);
    }

    /**
     * Formularz edycji definicji
     */
    public function editDefinition(): void
    {
        if (!$this->auth->isAdmin()) { $this->redirect("dashboard", "danger", "Brak uprawnień."); return; }

        $id = (int)get('id');
        $definition = $this->settingModel->getDefinitionById($id);

        if (!$definition) {
            $this->redirect('settings/definitions', 'danger', 'Definicja nie istnieje.');
            return;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!$this->verifyCsrf()) {
                return;
            }

            $data = $this->prepareDefinitionData();

            // Walidacja
            if (empty($data['key']) || empty($data['label']) || empty($data['type'])) {
                $this->redirect('settings/edit-definition?id=' . $id, 'danger', 'Wypełnij wymagane pola.');
                return;
            }

            // Sprawdź unikalność klucza (poza bieżącym)
            $existing = $this->settingModel->getDefinitionByKey($data['key']);
            if ($existing && $existing['id'] != $id) {
                $this->redirect('settings/edit-definition?id=' . $id, 'danger', 'Klucz już istnieje.');
                return;
            }

            $oldData = $definition;
            $result = $this->settingModel->updateDefinition($id, $data);

            if ($result) {
                $this->logSettingAction('setting_definition_update', [
                    'definition_id' => $id,
                    'key' => $data['key'],
                    'changes' => $this->getChanges($oldData, $data)
                ]);
                $this->redirect('settings/definitions', 'success', 'Definicja została zaktualizowana.');
            } else {
                $this->redirect('settings/edit-definition?id=' . $id, 'danger', 'Błąd podczas aktualizacji.');
            }
            return;
        }

        $this->render('settings/definition_form.tpl', [
            'pageTitle' => 'Edytuj definicję',
            'definition' => $definition,
            'groupLabels' => $this->getGroupLabels(),
            'scopeLabels' => $this->getScopeLabels(),
            'typeLabels' => $this->getTypeLabels()
        ]);
    }

    /**
     * Usuwanie definicji
     */
    public function deleteDefinition(): void
    {
        if (!$this->auth->isAdmin()) { $this->redirect("dashboard", "danger", "Brak uprawnień."); return; }

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->redirect('settings/definitions');
            return;
        }

        if (!$this->verifyCsrf()) {
            return;
        }

        $id = (int)post('id');
        $definition = $this->settingModel->getDefinitionById($id);

        if (!$definition) {
            $this->redirect('settings/definitions', 'danger', 'Definicja nie istnieje.');
            return;
        }

        $result = $this->settingModel->deleteDefinition($id);

        if ($result) {
            $this->logSettingAction('setting_definition_delete', [
                'definition_id' => $id,
                'key' => $definition['key']
            ]);
            $this->redirect('settings/definitions', 'success', 'Definicja została usunięta.');
        } else {
            $this->redirect('settings/definitions', 'danger', 'Błąd podczas usuwania.');
        }
    }

    // ==================== PRESETY ====================

    /**
     * Lista presetów
     */
    public function presets(): void
    {
        if (!$this->auth->isAdmin()) { $this->redirect("dashboard", "danger", "Brak uprawnień."); return; }

        $presets = $this->settingModel->getPresets(false);

        $this->render('settings/presets.tpl', [
            'pageTitle' => 'Zestawy ustawień',
            'presets' => $presets
        ]);
    }

    /**
     * Formularz dodawania presetu
     */
    public function addPreset(): void
    {
        if (!$this->auth->isAdmin()) { $this->redirect("dashboard", "danger", "Brak uprawnień."); return; }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!$this->verifyCsrf()) {
                return;
            }

            $name = trim(post('name'));
            $description = trim(post('description'));
            $isActive = post('is_active') ? 1 : 0;
            $items = post('items', []);

            if (empty($name)) {
                $this->redirect('settings/add-preset', 'danger', 'Podaj nazwę presetu.');
                return;
            }

            $presetId = $this->settingModel->createPreset([
                'name' => $name,
                'description' => $description,
                'is_active' => $isActive
            ], $this->currentUser['id']);

            if ($presetId) {
                // Zapisz elementy
                $validItems = [];
                foreach ($items as $defId => $value) {
                    if ($value !== '' && $value !== null) {
                        $validItems[$defId] = $value;
                    }
                }
                $this->settingModel->setPresetItems($presetId, $validItems);

                $this->logSettingAction('setting_preset_create', [
                    'preset_id' => $presetId,
                    'name' => $name,
                    'items_count' => count($validItems)
                ]);
                $this->redirect('settings/presets', 'success', 'Preset został utworzony.');
            } else {
                $this->redirect('settings/add-preset', 'danger', 'Błąd podczas tworzenia presetu.');
            }
            return;
        }

        $definitions = $this->settingModel->getDefinitions();

        // Grupuj definicje
        $grouped = [];
        foreach ($definitions as $def) {
            $grouped[$def['group_name']][] = $def;
        }

        $this->render('settings/preset_form.tpl', [
            'pageTitle' => 'Dodaj preset',
            'preset' => null,
            'definitions' => $definitions,
            'grouped' => $grouped,
            'groupLabels' => $this->getGroupLabels()
        ]);
    }

    /**
     * Formularz edycji presetu
     */
    public function editPreset(): void
    {
        if (!$this->auth->isAdmin()) { $this->redirect("dashboard", "danger", "Brak uprawnień."); return; }

        $id = (int)get('id');
        $preset = $this->settingModel->getPresetById($id);

        if (!$preset) {
            $this->redirect('settings/presets', 'danger', 'Preset nie istnieje.');
            return;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!$this->verifyCsrf()) {
                return;
            }

            $name = trim(post('name'));
            $description = trim(post('description'));
            $isActive = post('is_active') ? 1 : 0;
            $items = post('items', []);

            if (empty($name)) {
                $this->redirect('settings/edit-preset?id=' . $id, 'danger', 'Podaj nazwę presetu.');
                return;
            }

            $oldName = $preset['name'];
            $result = $this->settingModel->updatePreset($id, [
                'name' => $name,
                'description' => $description,
                'is_active' => $isActive
            ]);

            if ($result) {
                // Zapisz elementy
                $validItems = [];
                foreach ($items as $defId => $value) {
                    if ($value !== '' && $value !== null) {
                        $validItems[$defId] = $value;
                    }
                }
                $this->settingModel->setPresetItems($id, $validItems);

                $this->logSettingAction('setting_preset_update', [
                    'preset_id' => $id,
                    'name' => $name,
                    'old_name' => $oldName,
                    'items_count' => count($validItems)
                ]);
                $this->redirect('settings/presets', 'success', 'Preset został zaktualizowany.');
            } else {
                $this->redirect('settings/edit-preset?id=' . $id, 'danger', 'Błąd podczas aktualizacji.');
            }
            return;
        }

        $definitions = $this->settingModel->getDefinitions();

        // Grupuj definicje
        $grouped = [];
        foreach ($definitions as $def) {
            $grouped[$def['group_name']][] = $def;
        }

        // Mapuj wartości presetu
        $presetValues = [];
        foreach ($preset['items'] as $item) {
            $presetValues[$item['definition_id']] = $item['value'];
        }

        $this->render('settings/preset_form.tpl', [
            'pageTitle' => 'Edytuj preset',
            'preset' => $preset,
            'presetValues' => $presetValues,
            'definitions' => $definitions,
            'grouped' => $grouped,
            'groupLabels' => $this->getGroupLabels()
        ]);
    }

    /**
     * Usuwanie presetu
     */
    public function deletePreset(): void
    {
        if (!$this->auth->isAdmin()) { $this->redirect("dashboard", "danger", "Brak uprawnień."); return; }

        if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
            $this->redirect('settings/presets');
            return;
        }

        if (!$this->verifyCsrf()) {
            return;
        }

        $id = (int)post('id');
        $preset = $this->settingModel->getPresetById($id);

        if (!$preset) {
            $this->redirect('settings/presets', 'danger', 'Preset nie istnieje.');
            return;
        }

        $result = $this->settingModel->deletePreset($id);

        if ($result) {
            $this->logSettingAction('setting_preset_delete', [
                'preset_id' => $id,
                'name' => $preset['name']
            ]);
            $this->redirect('settings/presets', 'success', 'Preset został usunięty.');
        } else {
            $this->redirect('settings/presets', 'danger', 'Błąd podczas usuwania.');
        }
    }

    // ==================== WARTOŚCI GLOBALNE ====================

    /**
     * Ustawienia globalne
     */
    public function global(): void
    {
        if (!$this->auth->isAdmin()) { $this->redirect("dashboard", "danger", "Brak uprawnień."); return; }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!$this->verifyCsrf()) {
                return;
            }

            $action = post('action');

            if ($action === 'apply_preset') {
                $presetId = (int)post('preset_id');
                $result = $this->settingModel->applyPreset($presetId, 'global', null, $this->currentUser['id']);

                if ($result) {
                    $preset = $this->settingModel->getPresetById($presetId);
                    $this->logSettingAction('setting_global_apply_preset', [
                        'preset_id' => $presetId,
                        'preset_name' => $preset['name'] ?? 'unknown'
                    ]);
                    $this->redirect('settings/global', 'success', 'Preset został zastosowany.');
                } else {
                    $this->redirect('settings/global', 'danger', 'Błąd podczas aplikowania presetu.');
                }
                return;
            }

            if ($action === 'save') {
                $values = post('values', []);
                $result = $this->settingModel->setValues('global', null, $values, $this->currentUser['id']);

                if ($result) {
                    $this->logSettingAction('setting_global_update', [
                        'values_count' => count($values)
                    ]);
                    $this->redirect('settings/global', 'success', 'Ustawienia zostały zapisane.');
                } else {
                    $this->redirect('settings/global', 'danger', 'Błąd podczas zapisywania.');
                }
                return;
            }

            if ($action === 'reset') {
                $result = $this->settingModel->deleteAllValues('global', null);

                if ($result) {
                    $this->logSettingAction('setting_global_reset', []);
                    $this->redirect('settings/global', 'success', 'Ustawienia zostały zresetowane.');
                }
                return;
            }
        }

        $definitions = $this->settingModel->getDefinitionsWithValues('global', null);
        $presets = $this->settingModel->getPresets();
        $timestamp = $this->settingModel->getTimestamp('global', null);

        // Grupuj definicje
        $grouped = [];
        foreach ($definitions as $def) {
            $grouped[$def['group_name']][] = $def;
        }

        $this->render('settings/values.tpl', [
            'pageTitle' => 'Ustawienia globalne',
            'scope' => 'global',
            'scopeId' => null,
            'scopeLabel' => 'Globalne',
            'definitions' => $definitions,
            'grouped' => $grouped,
            'groupLabels' => $this->getGroupLabels(),
            'presets' => $presets,
            'timestamp' => $timestamp,
            'canEdit' => true
        ]);
    }

    // ==================== WARTOŚCI RESELLER ====================

    /**
     * Ustawienia resellera
     */
    public function reseller(): void
    {
        $resellerId = (int)get('id');

        // Admin może edytować dowolnego resellera, reseller tylko swoje
        if ($this->auth->isAdmin()) {
            if (!$resellerId) {
                $this->redirect('users', 'danger', 'Nie podano ID resellera.');
                return;
            }
        } elseif ($this->auth->isReseller()) {
            $resellerId = $this->currentUser['id'];
        } else {
            $this->redirect('dashboard', 'danger', 'Brak uprawnień.');
            return;
        }

        // Sprawdź czy to reseller
        $userModel = new User();
        $reseller = $userModel->getById($resellerId);

        if (!$reseller || $reseller['role'] !== 'reseller') {
            $this->redirect('users', 'danger', 'Użytkownik nie jest resellerem.');
            return;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!$this->verifyCsrf()) {
                return;
            }

            $action = post('action');

            if ($action === 'apply_preset') {
                $presetId = (int)post('preset_id');
                $result = $this->settingModel->applyPreset($presetId, 'reseller', $resellerId, $this->currentUser['id']);

                if ($result) {
                    $preset = $this->settingModel->getPresetById($presetId);
                    $this->logSettingAction('setting_reseller_apply_preset', [
                        'reseller_id' => $resellerId,
                        'preset_id' => $presetId,
                        'preset_name' => $preset['name'] ?? 'unknown'
                    ]);
                    $this->redirect('settings/reseller?id=' . $resellerId, 'success', 'Preset został zastosowany.');
                }
                return;
            }

            if ($action === 'save') {
                $values = post('values', []);
                $result = $this->settingModel->setValues('reseller', $resellerId, $values, $this->currentUser['id']);

                if ($result) {
                    $this->logSettingAction('setting_reseller_update', [
                        'reseller_id' => $resellerId,
                        'values_count' => count($values)
                    ]);
                    $this->redirect('settings/reseller?id=' . $resellerId, 'success', 'Ustawienia zostały zapisane.');
                }
                return;
            }

            if ($action === 'reset') {
                $result = $this->settingModel->deleteAllValues('reseller', $resellerId);

                if ($result) {
                    $this->logSettingAction('setting_reseller_reset', ['reseller_id' => $resellerId]);
                    $this->redirect('settings/reseller?id=' . $resellerId, 'success', 'Ustawienia zostały zresetowane.');
                }
                return;
            }
        }

        $definitions = $this->settingModel->getDefinitionsWithValues('reseller', $resellerId);
        $presets = $this->settingModel->getPresets();
        $timestamp = $this->settingModel->getTimestamp('reseller', $resellerId);

        // Grupuj definicje
        $grouped = [];
        foreach ($definitions as $def) {
            $grouped[$def['group_name']][] = $def;
        }

        $this->render('settings/values.tpl', [
            'pageTitle' => 'Ustawienia resellera: ' . $reseller['username'],
            'scope' => 'reseller',
            'scopeId' => $resellerId,
            'scopeLabel' => 'Reseller: ' . $reseller['username'],
            'definitions' => $definitions,
            'grouped' => $grouped,
            'groupLabels' => $this->getGroupLabels(),
            'presets' => $presets,
            'timestamp' => $timestamp,
            'canEdit' => true,
            'reseller' => $reseller
        ]);
    }

    // ==================== WARTOŚCI USER ====================

    /**
     * Ustawienia użytkownika
     */
    public function user(): void
    {
        $userId = (int)get('id');

        // Sprawdź uprawnienia
        if (!$this->canAccessUserSettings($userId)) {
            $this->redirect('dashboard', 'danger', 'Brak uprawnień.');
            return;
        }

        $userModel = new User();
        $user = $userModel->getById($userId);

        if (!$user) {
            $this->redirect('users', 'danger', 'Użytkownik nie istnieje.');
            return;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!$this->verifyCsrf()) {
                return;
            }

            $action = post('action');

            if ($action === 'apply_preset') {
                $presetId = (int)post('preset_id');
                $result = $this->settingModel->applyPreset($presetId, 'user', $userId, $this->currentUser['id']);

                if ($result) {
                    $preset = $this->settingModel->getPresetById($presetId);
                    $this->logSettingAction('setting_user_apply_preset', [
                        'user_id' => $userId,
                        'preset_id' => $presetId,
                        'preset_name' => $preset['name'] ?? 'unknown'
                    ]);
                    $this->redirect('settings/user?id=' . $userId, 'success', 'Preset został zastosowany.');
                }
                return;
            }

            if ($action === 'save') {
                $values = post('values', []);
                $result = $this->settingModel->setValues('user', $userId, $values, $this->currentUser['id']);

                if ($result) {
                    $this->logSettingAction('setting_user_update', [
                        'user_id' => $userId,
                        'values_count' => count($values)
                    ]);
                    $this->redirect('settings/user?id=' . $userId, 'success', 'Ustawienia zostały zapisane.');
                }
                return;
            }

            if ($action === 'reset') {
                $result = $this->settingModel->deleteAllValues('user', $userId);

                if ($result) {
                    $this->logSettingAction('setting_user_reset', ['user_id' => $userId]);
                    $this->redirect('settings/user?id=' . $userId, 'success', 'Ustawienia zostały zresetowane.');
                }
                return;
            }
        }

        $definitions = $this->settingModel->getDefinitionsWithValues('user', $userId);
        $presets = $this->settingModel->getPresets();
        $timestamp = $this->settingModel->getTimestamp('user', $userId);

        // Grupuj definicje
        $grouped = [];
        foreach ($definitions as $def) {
            $grouped[$def['group_name']][] = $def;
        }

        $this->render('settings/values.tpl', [
            'pageTitle' => 'Ustawienia użytkownika: ' . $user['username'],
            'scope' => 'user',
            'scopeId' => $userId,
            'scopeLabel' => 'Użytkownik: ' . $user['username'],
            'definitions' => $definitions,
            'grouped' => $grouped,
            'groupLabels' => $this->getGroupLabels(),
            'presets' => $presets,
            'timestamp' => $timestamp,
            'canEdit' => true,
            'user' => $user
        ]);
    }

    // ==================== WARTOŚCI DEVICE ====================

    /**
     * Ustawienia urządzenia
     */
    public function device(): void
    {
        $deviceId = (int)get('id');

        $deviceModel = new Device();
        $device = $deviceModel->getById($deviceId);

        if (!$device) {
            $this->redirect('devices', 'danger', 'Urządzenie nie istnieje.');
            return;
        }

        // Sprawdź uprawnienia
        if (!$this->canAccess($device['owner_id'])) {
            $this->redirect('devices', 'danger', 'Brak uprawnień.');
            return;
        }

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!$this->verifyCsrf()) {
                return;
            }

            $action = post('action');

            if ($action === 'apply_preset') {
                $presetId = (int)post('preset_id');
                $result = $this->settingModel->applyPreset($presetId, 'device', $deviceId, $this->currentUser['id']);

                if ($result) {
                    $preset = $this->settingModel->getPresetById($presetId);
                    $this->logSettingAction('setting_device_apply_preset', [
                        'device_id' => $deviceId,
                        'preset_id' => $presetId,
                        'preset_name' => $preset['name'] ?? 'unknown'
                    ]);
                    $this->redirect('settings/device?id=' . $deviceId, 'success', 'Preset został zastosowany.');
                }
                return;
            }

            if ($action === 'save') {
                $values = post('values', []);
                $result = $this->settingModel->setValues('device', $deviceId, $values, $this->currentUser['id']);

                if ($result) {
                    $this->logSettingAction('setting_device_update', [
                        'device_id' => $deviceId,
                        'device_name' => $device['name'] ?: $device['mac'],
                        'values_count' => count($values)
                    ]);
                    $this->redirect('settings/device?id=' . $deviceId, 'success', 'Ustawienia zostały zapisane.');
                }
                return;
            }

            if ($action === 'reset') {
                $result = $this->settingModel->deleteAllValues('device', $deviceId);

                if ($result) {
                    $this->logSettingAction('setting_device_reset', [
                        'device_id' => $deviceId,
                        'device_name' => $device['name'] ?: $device['mac']
                    ]);
                    $this->redirect('settings/device?id=' . $deviceId, 'success', 'Ustawienia zostały zresetowane.');
                }
                return;
            }
        }

        $definitions = $this->settingModel->getDefinitionsWithValues('device', $deviceId);
        $presets = $this->settingModel->getPresets();
        $timestamp = $this->settingModel->getTimestamp('device', $deviceId);

        // Grupuj definicje
        $grouped = [];
        foreach ($definitions as $def) {
            $grouped[$def['group_name']][] = $def;
        }

        $this->render('settings/values.tpl', [
            'pageTitle' => 'Ustawienia urządzenia: ' . ($device['name'] ?: $device['mac']),
            'scope' => 'device',
            'scopeId' => $deviceId,
            'scopeLabel' => 'Urządzenie: ' . ($device['name'] ?: $device['mac']),
            'definitions' => $definitions,
            'grouped' => $grouped,
            'groupLabels' => $this->getGroupLabels(),
            'presets' => $presets,
            'timestamp' => $timestamp,
            'canEdit' => true,
            'device' => $device
        ]);
    }

    // ==================== MOJE USTAWIENIA ====================

    /**
     * Moje ustawienia (dla zalogowanego użytkownika)
     */
    public function my(): void
    {
        $userId = $this->currentUser['id'];

        if ($_SERVER['REQUEST_METHOD'] === 'POST') {
            if (!$this->verifyCsrf()) {
                return;
            }

            $action = post('action');

            if ($action === 'apply_preset') {
                $presetId = (int)post('preset_id');
                $result = $this->settingModel->applyPreset($presetId, 'user', $userId, $this->currentUser['id']);

                if ($result) {
                    $preset = $this->settingModel->getPresetById($presetId);
                    $this->logSettingAction('setting_my_apply_preset', [
                        'user_id' => $userId,
                        'preset_id' => $presetId,
                        'preset_name' => $preset['name'] ?? 'unknown'
                    ]);
                    $this->redirect('settings/my', 'success', 'Preset został zastosowany.');
                }
                return;
            }

            if ($action === 'save') {
                $values = post('values', []);
                $result = $this->settingModel->setValues('user', $userId, $values, $this->currentUser['id']);

                if ($result) {
                    $this->logSettingAction('setting_my_update', [
                        'user_id' => $userId,
                        'values_count' => count($values)
                    ]);
                    $this->redirect('settings/my', 'success', 'Ustawienia zostały zapisane.');
                }
                return;
            }

            if ($action === 'reset') {
                $result = $this->settingModel->deleteAllValues('user', $userId);

                if ($result) {
                    $this->logSettingAction('setting_my_reset', ['user_id' => $userId]);
                    $this->redirect('settings/my', 'success', 'Ustawienia zostały zresetowane do domyślnych.');
                }
                return;
            }
        }

        $definitions = $this->settingModel->getDefinitionsWithValues('user', $userId);
        $presets = $this->settingModel->getPresets();
        $timestamp = $this->settingModel->getTimestamp('user', $userId);

        // Grupuj definicje
        $grouped = [];
        foreach ($definitions as $def) {
            $grouped[$def['group_name']][] = $def;
        }

        $this->render('settings/values.tpl', [
            'pageTitle' => 'Moje ustawienia',
            'scope' => 'user',
            'scopeId' => $userId,
            'scopeLabel' => 'Twoje ustawienia',
            'definitions' => $definitions,
            'grouped' => $grouped,
            'groupLabels' => $this->getGroupLabels(),
            'presets' => $presets,
            'timestamp' => $timestamp,
            'canEdit' => true,
            'isMySettings' => true
        ]);
    }

    // ==================== HELPERS ====================

    /**
     * Przygotuj dane definicji z POST
     */
    private function prepareDefinitionData(): array
    {
        $options = [];
        $optionsRaw = post('options', '');

        if (!empty($optionsRaw)) {
            // Próbuj sparsować jako JSON
            $decoded = json_decode($optionsRaw, true);
            if (is_array($decoded)) {
                $options = $decoded;
            }
        }

        return [
            'key' => trim(post('key')),
            'type' => post('type'),
            'default_value' => post('default_value'),
            'label' => trim(post('label')),
            'description' => trim(post('description')),
            'group_name' => post('group_name', 'general'),
            'min_scope' => post('min_scope', 'device'),
            'options' => $options,
            'sort_order' => (int)post('sort_order', 0),
            'is_active' => post('is_active') ? 1 : 0
        ];
    }

    /**
     * Sprawdź czy użytkownik może edytować ustawienia usera
     */
    private function canAccessUserSettings(int $userId): bool
    {
        if ($this->auth->isAdmin()) {
            return true;
        }

        if ($this->auth->isReseller()) {
            $userModel = new User();
            $user = $userModel->getById($userId);
            return $user && $user['parent_id'] == $this->currentUser['id'];
        }

        return $userId == $this->currentUser['id'];
    }

    /**
     * Pobierz zmiany między starymi a nowymi danymi
     */
    private function getChanges(array $old, array $new): array
    {
        $changes = [];
        $keys = ['key', 'type', 'default_value', 'label', 'group_name', 'min_scope', 'is_active'];

        foreach ($keys as $key) {
            if (($old[$key] ?? '') !== ($new[$key] ?? '')) {
                $changes[$key] = ['from' => $old[$key] ?? '', 'to' => $new[$key] ?? ''];
            }
        }

        return $changes;
    }

    /**
     * Etykiety grup
     */
    private function getGroupLabels(): array
    {
        return [
            'general' => 'Ogólne',
            'epg' => 'EPG / Przewodnik TV',
            'clock' => 'Zegar',
            'ui' => 'Interfejs',
            'channels' => 'Kanały',
            'player' => 'Odtwarzacz',
            'info_panel' => 'Panel informacyjny',
            'programs' => 'Programy',
            'catchup' => 'Catchup / Historia',
            'vod' => 'VOD / Filmy',
            'system' => 'System'
        ];
    }

    /**
     * Etykiety scope
     */
    private function getScopeLabels(): array
    {
        return [
            'global' => 'Globalny (tylko admin)',
            'reseller' => 'Reseller (admin + reseller)',
            'user' => 'Użytkownik (admin + reseller + user)',
            'device' => 'Urządzenie (wszyscy)'
        ];
    }

    /**
     * Etykiety typów
     */
    private function getTypeLabels(): array
    {
        return [
            'boolean' => 'Boolean (tak/nie)',
            'int' => 'Integer (liczba całkowita)',
            'long' => 'Long (duża liczba)',
            'string' => 'String (tekst)'
        ];
    }
}
