<?php

namespace App\Models;

use CodeIgniter\Model;

class ConsentModel extends Model
{
    protected $table = 'user_consents';
    protected $primaryKey = 'id';
    
    protected $useAutoIncrement = true;
    
    protected $returnType = 'array';
    protected $useSoftDeletes = false;
    
    protected $allowedFields = [
        'user_id',
        'device_uuid',
        'kvkk_consent',
        'gdpr_consent',
        'privacy_consent',
        'marketing_consent',
        'analytics_consent',
        'push_consent',
        'device_info_consent',
        'membership_agreement',
        'electronic_communication',
        'explicit_consent',
        'consent_version',
        'consent_text_versions',
        'previous_consent_versions',
        'version_upgrade_history',
        'reconfirmation_required',
        'last_version_check',
        'is_authenticated',
        'ip_address',
        'user_agent',
        'platform',
        'country_code',
        'country',
        'region',
        'language',
        'device_info',
        'browser',
        'os',
        'legal_consents_group',
        'communication_consents_group',
        'experience_consents_group',
        'created_at',
        'updated_at',
        'consent_expires_at',
        'legal_basis',
        'data_processing_purposes'
    ];
    
    protected $useTimestamps = false;
    
    protected $validationRules = [
        'device_uuid' => 'required',
        'kvkk_consent' => 'required|in_list[0,1]',
        'gdpr_consent' => 'required|in_list[0,1]',
        'privacy_consent' => 'required|in_list[0,1]',
        'explicit_consent' => 'required|in_list[0,1]',
    ];

    // Güncel versiyon tanımları - v1.0 sabit
    private const CURRENT_CONSENT_VERSIONS = [
        'kvkk_consent' => '1.0',
        'gdpr_consent' => '1.0',
        'privacy_consent' => '1.0',
        'marketing_consent' => '1.0',
        'analytics_consent' => '1.0',
        'push_consent' => '1.0',
        'device_info_consent' => '1.0',
        'membership_agreement' => '1.0',
        'electronic_communication' => '1.0',
        'explicit_consent' => '1.0',
    ];

    // İzin metin versiyonları - v1.0 sabit
    private const CONSENT_TEXT_VERSIONS = [
        'kvkk_text_version' => '1.0.0',
        'gdpr_text_version' => '1.0.0',
        'privacy_text_version' => '1.0.0',
        'marketing_text_version' => '1.0.0',
        'analytics_text_version' => '1.0.0',
        'push_text_version' => '1.0.0',
        'device_info_text_version' => '1.0.0',
        'membership_text_version' => '1.0.0',
        'electronic_communication_text_version' => '1.0.0',
        'explicit_consent_text_version' => '1.0.0',
    ];

    /**
     * Kurucu
     */
    public function __construct()
    {
        parent::__construct();
        $this->_checkAndUpdateTable();
    }
    
    /**
     * Kullanıcı ID'sine göre en son izin kaydını getir
     */
    public function getConsentsByUserId($userId)
    {
        $record = $this->where('user_id', $userId)
                      ->orderBy('updated_at', 'DESC')
                      ->first();
        
        return $record ? [$record] : [];
    }
    
    /**
     * Cihaz UUID'sine göre en son izin kaydını getir
     */
    public function getConsentsByDeviceUuid($deviceUuid)
    {
        $record = $this->where('device_uuid', $deviceUuid)
                      ->orderBy('updated_at', 'DESC')
                      ->first();
        
        return $record ? [$record] : [];
    }
    
    /**
     * Kullanıcının en son izin kaydını getir
     */
    public function getLatestConsent($userId)
    {
        return $this->where('user_id', $userId)
                   ->orderBy('updated_at', 'DESC')
                   ->first();
    }

    /**
     * Cihaz için en son izin kaydını getir
     */
    public function getLatestConsentByDevice($deviceUuid)
    {
        return $this->where('device_uuid', $deviceUuid)
                   ->orderBy('updated_at', 'DESC')
                   ->first();
    }

    /**
     * Kullanıcı veya cihaz için en son izin kaydını getir
     */
    public function getLatestConsentRecord($userId, $deviceUuid)
    {
        $query = $this->orderBy('updated_at', 'DESC');
        
        if ($userId !== null) {
            $query->where('user_id', $userId);
        } else {
            $query->where('device_uuid', $deviceUuid)
                  ->where('user_id IS NULL');
        }
        
        return $query->first();
    }

    /**
     * İzinleri güncelle veya ekle (UPSERT işlemi) - TEK SATIR GÜNCELLEME
     */
    public function upsertConsent($consentData)
    {
        $db = \Config\Database::connect();
        $db->transStart();

        try {
            $userId = $consentData['user_id'] ?? null;
            $deviceUuid = $consentData['device_uuid'];

            // Mevcut kaydı bul
            $existingRecord = null;
            
            if ($userId !== null) {
                // Kullanıcı giriş yapmışsa user_id ile ara
                $existingRecord = $this->where('user_id', $userId)->first();
            } else {
                // Misafir kullanıcı için device_uuid ile ara
                $existingRecord = $this->where('device_uuid', $deviceUuid)
                                      ->where('user_id IS NULL')
                                      ->first();
            }

            if ($existingRecord) {
                // Mevcut kaydı güncelle - SADECE BİR SATIR
                $consentData['updated_at'] = date('Y-m-d H:i:s');
                
                // Önceki verileri history'e kaydet
                $this->_saveToHistory($existingRecord, $consentData);
                
                $result = $this->update($existingRecord['id'], $consentData);
                
                $db->transComplete();
                return $result ? $existingRecord['id'] : false;
            } else {
                // Yeni kayıt oluştur
                $consentData['created_at'] = date('Y-m-d H:i:s');
                $consentData['updated_at'] = date('Y-m-d H:i:s');
                
                // İlk kayıt için saklama süresi belirle (7 yıl)
                $consentData['consent_expires_at'] = date('Y-m-d H:i:s', strtotime('+2555 days'));
                $consentData['legal_basis'] = 'KVKK Article 7, GDPR Article 6';
                
                $result = $this->insert($consentData);
                
                $db->transComplete();
                return $result ? $this->getInsertID() : false;
            }
        } catch (\Exception $e) {
            $db->transRollback();
            log_message('error', 'Consent upsert error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Geçmişe kaydet
     */
    private function _saveToHistory($existingRecord, $newData)
    {
        try {
            $historyModel = model('App\Models\ConsentHistoryModel');
            
            $historyData = [
                'user_id' => $existingRecord['user_id'],
                'device_uuid' => $existingRecord['device_uuid'],
                'kvkk_consent' => $existingRecord['kvkk_consent'] ?? '0',
                'gdpr_consent' => $existingRecord['gdpr_consent'] ?? '0',
                'privacy_consent' => $existingRecord['privacy_consent'] ?? '0',
                'marketing_consent' => $existingRecord['marketing_consent'] ?? '0',
                'analytics_consent' => $existingRecord['analytics_consent'] ?? '0',
                'device_info_consent' => $existingRecord['device_info_consent'] ?? '0',
                'push_notification_consent' => $existingRecord['push_consent'] ?? '0',
                'membership_agreement' => $existingRecord['membership_agreement'] ?? '0',
                'electronic_communication' => $existingRecord['electronic_communication'] ?? '0',
                'explicit_consent' => $existingRecord['explicit_consent'] ?? '0',
                'consent_version' => $existingRecord['consent_version'],
                'consent_text_versions' => $existingRecord['consent_text_versions'],
                'platform' => $existingRecord['platform'],
                'ip_address' => $existingRecord['ip_address'],
                'country_code' => $existingRecord['country_code'],
                'region' => $existingRecord['region'],
                'language' => $existingRecord['language'],
                'timestamp' => $existingRecord['updated_at'] ?? $existingRecord['created_at'],
                'is_authenticated' => $existingRecord['is_authenticated'] ?? '0',
                'user_agent' => $existingRecord['user_agent'],
                'legal_consents_group' => $existingRecord['legal_consents_group'] ?? '0',
                'communication_consents_group' => $existingRecord['communication_consents_group'] ?? '0',
                'experience_consents_group' => $existingRecord['experience_consents_group'] ?? '0',
                'change_type' => 'consent_update',
                'retention_expires_at' => date('Y-m-d H:i:s', strtotime('+2555 days')),
                'legal_basis' => 'KVKK Article 7, GDPR Article 6',
            ];

            // Cihaz bilgilerinden model bilgisini çıkar
            if (!empty($existingRecord['device_info'])) {
                try {
                    $deviceInfo = json_decode($existingRecord['device_info'], true);
                    if (is_array($deviceInfo)) {
                        $historyData['device_model'] = $deviceInfo['device_model'] ?? $deviceInfo['model'] ?? null;
                    }
                } catch (\Exception $e) {
                    log_message('error', 'Device info JSON decode error: ' . $e->getMessage());
                }
            }

            $historyModel->insert($historyData);
        } catch (\Exception $e) {
            log_message('error', 'Error saving consent history: ' . $e->getMessage());
        }
    }

    /**
     * Kullanıcının versiyon uyumluluğunu kontrol et
     */
    private function _checkUserVersionCompliance($userRecord)
    {
        $compliance = [
            'is_compliant' => true,
            'outdated_consents' => [],
            'missing_versions' => [],
            'last_update' => $userRecord['updated_at'] ?? $userRecord['created_at']
        ];

        // Versiyon bilgilerini çöz
        $userVersions = [];
        if (!empty($userRecord['consent_text_versions'])) {
            try {
                $userVersions = json_decode($userRecord['consent_text_versions'], true) ?? [];
            } catch (\Exception $e) {
                $compliance['is_compliant'] = false;
                $compliance['missing_versions'] = array_keys(self::CURRENT_CONSENT_VERSIONS);
                return $compliance;
            }
        }

        // Her izin türü için versiyon kontrolü
        foreach (self::CURRENT_CONSENT_VERSIONS as $consentType => $currentVersion) {
            $userVersion = $userVersions[$consentType . '_version'] ?? '0.0';
            
            if (version_compare($userVersion, $currentVersion, '<')) {
                $compliance['is_compliant'] = false;
                $compliance['outdated_consents'][] = [
                    'consent_type' => $consentType,
                    'current_version' => $userVersion,
                    'required_version' => $currentVersion,
                    'needs_reconfirmation' => $this->_requiresReconfirmation($consentType, $userVersion, $currentVersion)
                ];
            }
        }

        return $compliance;
    }

    /**
     * Versiyon değişikliğinin yeniden onay gerektirip gerektirmediğini kontrol et
     */
    private function _requiresReconfirmation($consentType, $oldVersion, $newVersion)
    {
        // v1.0 sabit olduğu için şu an için false
        return false;
    }

    /**
     * GDPR uyumluluğu için veri saklama süresi kontrolü
     */
    public function getExpiredConsentRecords()
    {
        $expirationDate = date('Y-m-d H:i:s', strtotime('-2555 days')); // 7 yıl
        
        return $this->where('created_at <', $expirationDate)
                   ->where('consent_expires_at IS NOT NULL')
                   ->where('consent_expires_at <', date('Y-m-d H:i:s'))
                   ->findAll();
    }

    /**
     * Tablo ve sütunları kontrol et, yoksa oluştur/güncelle
     */
    private function _checkAndUpdateTable()
    {
        $db = \Config\Database::connect();
        $forge = \Config\Database::forge();
        
        // Tablo var mı kontrol et
        $tables = $db->listTables();
        
        if (!in_array($this->table, $tables)) {
            // Tablo yok, oluştur
            $this->_createTable($forge);
        } else {
            // Tablo var, sütunları kontrol et ve eksikleri ekle
            $this->_updateTableColumns($db);
        }
    }

    /**
     * Tabloyu oluştur
     */
    private function _createTable($forge)
    {
        $forge->addField([
            'id' => [
                'type' => 'INT',
                'constraint' => 11,
                'unsigned' => true,
                'auto_increment' => true
            ],
            'user_id' => [
                'type' => 'INT',
                'constraint' => 11,
                'null' => true
            ],
            'device_uuid' => [
                'type' => 'VARCHAR',
                'constraint' => 255,
                'null' => false
            ],
            'kvkk_consent' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'gdpr_consent' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'privacy_consent' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'marketing_consent' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'analytics_consent' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'push_consent' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'device_info_consent' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'membership_agreement' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'electronic_communication' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'explicit_consent' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'consent_version' => [
                'type' => 'VARCHAR',
                'constraint' => 20,
                'null' => true
            ],
            'consent_text_versions' => [
                'type' => 'JSON',
                'null' => true
            ],
            'previous_consent_versions' => [
                'type' => 'JSON',
                'null' => true
            ],
            'version_upgrade_history' => [
                'type' => 'JSON',
                'null' => true
            ],
         'reconfirmation_required' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'last_version_check' => [
                'type' => 'TIMESTAMP',
                'null' => true
            ],
            'is_authenticated' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'ip_address' => [
                'type' => 'VARCHAR',
                'constraint' => 45,
                'null' => true
            ],
            'user_agent' => [
                'type' => 'TEXT',
                'null' => true
            ],
            'platform' => [
                'type' => 'VARCHAR',
                'constraint' => 50,
                'null' => true
            ],
            'country_code' => [
                'type' => 'VARCHAR',
                'constraint' => 10,
                'null' => true
            ],
            'country' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
                'null' => true
            ],
            'region' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
                'null' => true
            ],
            'language' => [
                'type' => 'VARCHAR',
                'constraint' => 10,
                'null' => true
            ],
            'device_info' => [
                'type' => 'JSON',
                'null' => true
            ],
            'browser' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
                'null' => true
            ],
            'os' => [
                'type' => 'VARCHAR',
                'constraint' => 100,
                'null' => true
            ],
            'legal_consents_group' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'communication_consents_group' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'experience_consents_group' => [
                'type' => 'CHAR',
                'constraint' => 1,
                'default' => '0'
            ],
            'created_at' => [
                'type' => 'TIMESTAMP',
                'null' => false,
                'default' => 'CURRENT_TIMESTAMP'
            ],
            'updated_at' => [
                'type' => 'TIMESTAMP',
                'null' => false,
                'default' => 'CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'
            ],
            'consent_expires_at' => [
                'type' => 'TIMESTAMP',
                'null' => true
            ],
            'legal_basis' => [
                'type' => 'VARCHAR',
                'constraint' => 255,
                'null' => true,
                'default' => 'KVKK Article 7, GDPR Article 6'
            ],
            'data_processing_purposes' => [
                'type' => 'TEXT',
                'null' => true
            ]
        ]);
        
        $forge->addKey('id', true);
        $forge->addKey('user_id');
        $forge->addKey('device_uuid');
        $forge->addKey('updated_at');
        $forge->addKey('consent_expires_at');
        
        $forge->createTable($this->table);
        
        log_message('info', "Consent table '{$this->table}' created successfully");
    }

    /**
     * Tablo sütunlarını güncelle - MySQL uyumlu
     */
    private function _updateTableColumns($db)
    {
        $existingColumns = $db->getFieldNames($this->table);
        
        // Eksik sütunlar için SQL sorguları - MySQL uyumlu
        $columnUpdates = [
            'membership_agreement' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN membership_agreement CHAR(1) NOT NULL DEFAULT '0'"
            ],
            'electronic_communication' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN electronic_communication CHAR(1) NOT NULL DEFAULT '0'"
            ],
            'explicit_consent' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN explicit_consent CHAR(1) NOT NULL DEFAULT '0'"
            ],
            'previous_consent_versions' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN previous_consent_versions JSON NULL"
            ],
            'version_upgrade_history' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN version_upgrade_history JSON NULL"
            ],
            'reconfirmation_required' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN reconfirmation_required CHAR(1) NOT NULL DEFAULT '0'"
            ],
            'last_version_check' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN last_version_check TIMESTAMP NULL"
            ],
            'browser' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN browser VARCHAR(100) NULL"
            ],
            'os' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN os VARCHAR(100) NULL"
            ],
            'updated_at' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"
            ],
            'consent_expires_at' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN consent_expires_at TIMESTAMP NULL"
            ],
            'legal_basis' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN legal_basis VARCHAR(255) NULL DEFAULT 'KVKK Article 7, GDPR Article 6'"
            ],
            'data_processing_purposes' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN data_processing_purposes TEXT NULL"
            ],
            'experience_consents_group' => [
                'sql' => "ALTER TABLE {$this->table} ADD COLUMN experience_consents_group CHAR(1) NOT NULL DEFAULT '0'"
            ]
        ];
        
        // Eksik sütunları ekle
        foreach ($columnUpdates as $columnName => $config) {
            if (!in_array($columnName, $existingColumns)) {
                try {
                    $db->query($config['sql']);
                    log_message('info', "Added column '{$columnName}' to consent table");
                } catch (\Exception $e) {
                    log_message('error', "Error adding column '{$columnName}': " . $e->getMessage());
                }
            }
        }

        // İndeksleri ekle/güncelle
        $this->_updateTableIndexes($db);
    }

    /**
     * Tablo indekslerini güncelle - MySQL uyumlu versiyon
     */
    private function _updateTableIndexes($db)
    {
        try {
            // Mevcut indeksleri kontrol et
            $existingIndexes = $this->_getExistingIndexes($db);
            
            // Eklenecek indeksler - MySQL uyumlu syntax
            $indexesToCreate = [
                'idx_reconfirmation_required' => [
                    'sql' => "CREATE INDEX idx_reconfirmation_required ON {$this->table} (reconfirmation_required)"
                ],
                'idx_consent_expires' => [
                    'sql' => "CREATE INDEX idx_consent_expires ON {$this->table} (consent_expires_at)"
                ],
                'idx_user_updated' => [
                    'sql' => "CREATE INDEX idx_user_updated ON {$this->table} (user_id, updated_at)"
                ],
                'idx_device_updated' => [
                    'sql' => "CREATE INDEX idx_device_updated ON {$this->table} (device_uuid, updated_at)"
                ],
                'idx_legal_basis' => [
                    'sql' => "CREATE INDEX idx_legal_basis ON {$this->table} (legal_basis)"
                ],
                'idx_latest_consent' => [
                    'sql' => "CREATE INDEX idx_latest_consent ON {$this->table} (user_id, device_uuid, updated_at)"
                ],
                'idx_explicit_consent' => [
                    'sql' => "CREATE INDEX idx_explicit_consent ON {$this->table} (explicit_consent)"
                ]
            ];
            
            // İndeksleri kontrol et ve ekle
            foreach ($indexesToCreate as $indexName => $indexConfig) {
                if (!in_array($indexName, $existingIndexes)) {
                    try {
                        $db->query($indexConfig['sql']);
                        log_message('info', "Created index '{$indexName}' on consent table");
                    } catch (\Exception $e) {
                        // İndeks zaten varsa hata almayı önle
                        if (!strpos($e->getMessage(), 'Duplicate key name')) {
                            log_message('error', "Error creating index '{$indexName}': " . $e->getMessage());
                        }
                    }
                }
            }
            
            log_message('info', 'Consent table indexes updated successfully');
        } catch (\Exception $e) {
            log_message('error', 'Error updating consent table indexes: ' . $e->getMessage());
        }
    }

    /**
     * Mevcut indeksleri getir - MySQL uyumlu
     */
    private function _getExistingIndexes($db)
    {
        try {
            $query = $db->query("SHOW INDEX FROM {$this->table}");
            $indexes = $query->getResultArray();
            
            $indexNames = [];
            foreach ($indexes as $index) {
                if ($index['Key_name'] !== 'PRIMARY') {
                    $indexNames[] = $index['Key_name'];
                }
            }
            
            return array_unique($indexNames);
        } catch (\Exception $e) {
            log_message('error', 'Error getting existing indexes: ' . $e->getMessage());
            return [];
        }
    }

    /**
     * Veritabanı bakımı - Eski kayıtları temizle
     */
    public function performMaintenance($dryRun = true)
    {
        $report = [
            'expired_records' => [],
            'duplicate_records' => [],
            'orphaned_records' => [],
            'actions_taken' => [],
            'dry_run' => $dryRun
        ];

        try {
            // Süresi dolmuş kayıtları bul
            $expiredRecords = $this->getExpiredConsentRecords();
            $report['expired_records'] = $expiredRecords;

            if (!$dryRun && !empty($expiredRecords)) {
                $expiredIds = array_column($expiredRecords, 'id');
                $this->anonymizeConsentRecords($expiredIds);
                $report['actions_taken'][] = 'Anonymized ' . count($expiredIds) . ' expired records';
            }

            // Yinelenen kayıtları bul (aynı user_id için birden fazla kayıt)
            $db = \Config\Database::connect();
            $duplicateQuery = $db->query("
                SELECT user_id, COUNT(*) as count
                FROM {$this->table}
                WHERE user_id IS NOT NULL
                GROUP BY user_id
                HAVING count > 1
            ");
            
            $duplicates = $duplicateQuery->getResultArray();
            $report['duplicate_records'] = $duplicates;

            if (!$dryRun && !empty($duplicates)) {
                foreach ($duplicates as $duplicate) {
                    // En yeni kaydı hariç diğerlerini sil
                    $records = $this->where('user_id', $duplicate['user_id'])
                                   ->orderBy('updated_at', 'DESC')
                                   ->findAll();
                    
                    // İlk kayıt (en yeni) hariç diğerlerini sil
                    for ($i = 1; $i < count($records); $i++) {
                        $this->delete($records[$i]['id']);
                    }
                    
                    $report['actions_taken'][] = 'Removed ' . (count($records) - 1) . ' duplicate records for user_id: ' . $duplicate['user_id'];
                }
            }

        } catch (\Exception $e) {
            log_message('error', 'Consent maintenance error: ' . $e->getMessage());
            $report['error'] = $e->getMessage();
        }

        return $report;
    }

    /**
     * İzin kayıtlarını anonimleştir (GDPR uyumluluğu)
     */
    public function anonymizeConsentRecords($recordIds)
    {
        $db = \Config\Database::connect();
        $db->transStart();

        try {
            foreach ($recordIds as $id) {
                $anonymizedData = [
                    'user_id' => null,
                    'device_uuid' => 'ANONYMIZED_' . substr(md5($id . time()), 0, 8),
                    'ip_address' => null,
                    'user_agent' => 'ANONYMIZED',
                    'device_info' => json_encode(['status' => 'anonymized']),
                    'legal_basis' => 'GDPR Article 17 - Right to be forgotten',
                    'updated_at' => date('Y-m-d H:i:s')
                ];

                $this->update($id, $anonymizedData);
            }

            $db->transComplete();
            return $db->transStatus();
        } catch (\Exception $e) {
            $db->transRollback();
            log_message('error', 'Consent anonymization error: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * Kullanıcı verilerini GDPR uyumlu şekilde dışa aktar
     */
    public function exportUserConsentData($userId)
    {
        $userConsents = $this->where('user_id', $userId)
                           ->orderBy('created_at', 'ASC')
                           ->findAll();

        $exportData = [
            'user_id' => $userId,
            'export_timestamp' => date('Y-m-d H:i:s'),
            'total_records' => count($userConsents),
            'data_retention_period' => '7 years (2555 days)',
            'legal_basis' => 'KVKK Article 7, GDPR Article 6',
            'consent_records' => []
        ];

        foreach ($userConsents as $record) {
            $exportRecord = [
                'record_id' => $record['id'],
                'created_at' => $record['created_at'],
                'updated_at' => $record['updated_at'],
                'consents' => [
                    'kvkk_consent' => $record['kvkk_consent'],
                    'gdpr_consent' => $record['gdpr_consent'],
                    'privacy_consent' => $record['privacy_consent'],
                    'marketing_consent' => $record['marketing_consent'],
                    'analytics_consent' => $record['analytics_consent'],
                    'device_info_consent' => $record['device_info_consent'],
                    'push_consent' => $record['push_consent'],
                    'membership_agreement' => $record['membership_agreement'],
                    'electronic_communication' => $record['electronic_communication'],
                    'explicit_consent' => $record['explicit_consent'] ?? '0',
                ],
                'version_information' => [
                    'consent_version' => $record['consent_version'],
                    'consent_text_versions' => !empty($record['consent_text_versions']) ? 
                        json_decode($record['consent_text_versions'], true) : null,
                    'previous_consent_versions' => !empty($record['previous_consent_versions']) ? 
                        json_decode($record['previous_consent_versions'], true) : null,
                    'version_upgrade_history' => !empty($record['version_upgrade_history']) ? 
                        json_decode($record['version_upgrade_history'], true) : null,
                ],
                'technical_information' => [
                    'platform' => $record['platform'],
                    'country_code' => $record['country_code'],
                    'language' => $record['language'],
                    'is_authenticated' => $record['is_authenticated'],
                ],
                'legal_information' => [
                    'legal_basis' => $record['legal_basis'],
                    'data_processing_purposes' => $record['data_processing_purposes'],
                    'consent_expires_at' => $record['consent_expires_at'],
                ]
            ];

            $exportData['consent_records'][] = $exportRecord;
        }

        return $exportData;
    }

    /**
     * İstatistiksel raporlama
     */
    public function getConsentStatistics()
    {
        $db = \Config\Database::connect();
        
        try {
            // Toplam kayıt sayısı
            $totalRecords = $this->countAll();
            
            // Aktif kullanıcı izinleri
            $activeUsersQuery = $db->query("
                SELECT COUNT(DISTINCT user_id) as count
                FROM {$this->table}
                WHERE user_id IS NOT NULL
                AND kvkk_consent = '1'
                AND gdpr_consent = '1'
                AND privacy_consent = '1'
                AND explicit_consent = '1'
            ");
            $activeUsers = $activeUsersQuery->getRow()->count;

            // İzin türlerine göre istatistikler
            $consentStats = [];
            $consentTypes = ['kvkk_consent', 'gdpr_consent', 'privacy_consent', 'marketing_consent', 
                           'analytics_consent', 'push_consent', 'device_info_consent', 
                           'membership_agreement', 'electronic_communication', 'explicit_consent'];

            foreach ($consentTypes as $type) {
                $acceptedQuery = $db->query("
                    SELECT COUNT(*) as count
                    FROM {$this->table}
                    WHERE {$type} = '1'
                ");
                $consentStats[$type] = [
                    'accepted' => $acceptedQuery->getRow()->count,
                    'percentage' => $totalRecords > 0 ? round(($acceptedQuery->getRow()->count / $totalRecords) * 100, 2) : 0
                ];
            }

            // Platform bazlı istatistikler
            $platformQuery = $db->query("
                SELECT platform, COUNT(*) as count
                FROM {$this->table}
                WHERE platform IS NOT NULL
                GROUP BY platform
            ");
            $platformStats = $platformQuery->getResultArray();

            // Ülke bazlı istatistikler
            $countryQuery = $db->query("
                SELECT country_code, COUNT(*) as count
                FROM {$this->table}
                WHERE country_code IS NOT NULL
                GROUP BY country_code
                ORDER BY count DESC
                LIMIT 10
            ");
            $countryStats = $countryQuery->getResultArray();

            return [
                'total_records' => $totalRecords,
                'active_users' => $activeUsers,
                'consent_statistics' => $consentStats,
                'platform_statistics' => $platformStats,
                'country_statistics' => $countryStats,
                'generated_at' => date('Y-m-d H:i:s')
            ];

        } catch (\Exception $e) {
            log_message('error', 'Error generating consent statistics: ' . $e->getMessage());
            return [
                'error' => 'Failed to generate statistics',
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * Kullanıcının versiyon uyumluluk durumunu getir
     */
    public function getVersionComplianceStatus($userId, $deviceUuid)
    {
        $latestRecord = $this->getLatestConsentRecord($userId, $deviceUuid);
        
        if (!$latestRecord) {
            return [
                'is_compliant' => false,
                'requires_consent' => true,
                'outdated_consents' => array_keys(self::CURRENT_CONSENT_VERSIONS),
                'message' => 'No consent record found'
            ];
        }

        return $this->_checkUserVersionCompliance($latestRecord);
    }
}

?>